diff --git a/.idea/modules.xml b/.idea/modules.xml index e77f8476248e..13115cca44e6 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -56,7 +56,6 @@ - diff --git a/build/scripts/common_tests.gant b/build/scripts/common_tests.gant index 5d91366077cf..855ba9bc7e9e 100644 --- a/build/scripts/common_tests.gant +++ b/build/scripts/common_tests.gant @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2017 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,12 @@ target(compile: "Compile project") { loadProject() prepareOutputFolder() + if (System.getProperty("tests.only")) { + ant.delete(dir: "$home/out") + ant.unzip(src: "$home/out.zip", dest: "$home/out") + return + } + if (!isDefined("avoid.project.rebuild")) { clearBuildCaches() projectBuilder.cleanOutput() diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/events/DebuggerCommandImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/events/DebuggerCommandImpl.java index 3bfedcecfafe..16d5c1e6534e 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/events/DebuggerCommandImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/events/DebuggerCommandImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2017 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.debugger.engine.events; import com.intellij.debugger.impl.DebuggerTaskImpl; +import org.jetbrains.annotations.Debugger; /** * @author lex @@ -40,6 +41,7 @@ public abstract class DebuggerCommandImpl extends DebuggerTaskImpl { } } + @Debugger.Insert public final void run() throws Exception{ try { action(); diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java b/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java index f80c2309628f..825e943d402a 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 JetBrains s.r.o. + * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.sun.jdi.VMDisconnectedException; +import org.jetbrains.annotations.Debugger; import org.jetbrains.annotations.NotNull; import java.util.concurrent.*; @@ -191,7 +192,7 @@ public abstract class InvokeThread { return request != null? request.getOwner() : null; } - public boolean schedule(E r) { + public boolean schedule(@Debugger.Capture E r) { if(LOG.isDebugEnabled()) { LOG.debug("schedule " + r + " in " + this); } diff --git a/java/debugger/impl/src/com/intellij/debugger/settings/CaptureConfigurable.java b/java/debugger/impl/src/com/intellij/debugger/settings/CaptureConfigurable.java index b66610b436e0..f6e8a99a688d 100644 --- a/java/debugger/impl/src/com/intellij/debugger/settings/CaptureConfigurable.java +++ b/java/debugger/impl/src/com/intellij/debugger/settings/CaptureConfigurable.java @@ -16,6 +16,9 @@ package com.intellij.debugger.settings; import com.intellij.debugger.DebuggerBundle; +import com.intellij.debugger.engine.JVMNameUtil; +import com.intellij.debugger.jdi.DecompiledLocalVariable; +import com.intellij.debugger.ui.JavaDebuggerSupport; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.diagnostic.Logger; @@ -27,10 +30,16 @@ import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; +import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.JDOMUtil; +import com.intellij.openapi.util.registry.Registry; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileWrapper; +import com.intellij.psi.*; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.search.searches.AnnotatedElementsSearch; import com.intellij.ui.*; import com.intellij.ui.table.JBTable; import com.intellij.util.PlatformIcons; @@ -42,6 +51,7 @@ import one.util.streamex.IntStreamEx; import one.util.streamex.StreamEx; import org.jdom.Document; import org.jdom.Element; +import org.jetbrains.annotations.Debugger; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -214,7 +224,92 @@ public class CaptureConfigurable implements SearchableConfigurable { static final String[] COLUMN_NAMES = new String[]{"", "Capture class name", "Capture method name", "Capture key expression", "Insert class name", "Insert method name", "Insert key expression"}; - List myCapturePoints = DebuggerSettings.getInstance().cloneCapturePoints(); + List myCapturePoints; + + private MyTableModel() { + myCapturePoints = DebuggerSettings.getInstance().cloneCapturePoints(); + scanPoints(); + } + + private void scanPoints() { + if (Registry.is("debugger.capture.points.annotations")) { + scanPointsInt(true); + scanPointsInt(false); + } + } + + private void scanPointsInt(boolean capture) { + try { + String annotationName = (capture ? Debugger.Capture.class : Debugger.Insert.class).getName().replace("$", "."); + Project project = JavaDebuggerSupport.getContextProjectForEditorFieldsInDebuggerConfigurables(); + GlobalSearchScope allScope = GlobalSearchScope.allScope(project); + PsiClass annotationClass = JavaPsiFacade.getInstance(project).findClass(annotationName, allScope); + if (annotationClass != null) { + AnnotatedElementsSearch.searchElements(annotationClass, allScope, PsiMethod.class, PsiParameter.class).forEach(e -> { + if (e instanceof PsiMethod) { + addCapturePointIfNeeded(e, (PsiMethod)e, annotationName, "this", capture); + } + else if (e instanceof PsiParameter) { + PsiParameter psiParameter = (PsiParameter)e; + PsiMethod psiMethod = (PsiMethod)psiParameter.getDeclarationScope(); + addCapturePointIfNeeded(psiParameter, psiMethod, annotationName, + DecompiledLocalVariable.PARAM_PREFIX + psiMethod.getParameterList().getParameterIndex(psiParameter), + capture); + } + }); + } + } + catch (Exception e) { + LOG.error(e); + } + } + + private void addCapturePointIfNeeded(PsiModifierListOwner psiElement, + PsiMethod psiMethod, + String annotationName, + String defaultExpression, + boolean capture) { + CapturePoint capturePoint = new CapturePoint(); + capturePoint.myEnabled = false; + if (capture) { + capturePoint.myClassName = JVMNameUtil.getNonAnonymousClassName(psiMethod.getContainingClass()); + capturePoint.myMethodName = JVMNameUtil.getJVMMethodName(psiMethod); + } + else { + capturePoint.myInsertClassName = JVMNameUtil.getNonAnonymousClassName(psiMethod.getContainingClass()); + capturePoint.myInsertMethodName = JVMNameUtil.getJVMMethodName(psiMethod); + } + + PsiModifierList modifierList = psiElement.getModifierList(); + if (modifierList != null) { + PsiAnnotation annotation = modifierList.findAnnotation(annotationName); + if (annotation != null) { + PsiAnnotationMemberValue attributeValue = annotation.findAttributeValue("keyExpression"); + String keyExpression = attributeValue != null ? StringUtil.unquoteString(attributeValue.getText()) : null; + if (StringUtil.isEmpty(keyExpression)) { + keyExpression = defaultExpression; + } + if (capture) { + capturePoint.myCaptureKeyExpression = keyExpression; + } + else { + capturePoint.myInsertKeyExpression = keyExpression; + } + } + } + + CapturePoint clone = capturePoint; + try { + clone = capturePoint.clone(); + clone.myEnabled = !clone.myEnabled; + } + catch (CloneNotSupportedException e) { + LOG.error(e); + } + if (!myCapturePoints.contains(capturePoint) && !myCapturePoints.contains(clone)) { + myCapturePoints.add(capturePoint); + } + } public String getColumnName(int column) { return COLUMN_NAMES[column]; @@ -325,6 +420,7 @@ public class CaptureConfigurable implements SearchableConfigurable { public void reset() { myCaptureVariables.setSelected(DebuggerSettings.getInstance().CAPTURE_VARIABLES); myTableModel.myCapturePoints = DebuggerSettings.getInstance().cloneCapturePoints(); + myTableModel.scanPoints(); myTableModel.fireTableDataChanged(); } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaMethodCallElement.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaMethodCallElement.java index 80894c903314..f90ede5ddc2b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaMethodCallElement.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaMethodCallElement.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2017 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,10 @@ package com.intellij.codeInsight.completion; import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.completion.util.MethodParenthesesHandler; +import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager; +import com.intellij.codeInsight.hint.ParameterInfoController; +import com.intellij.codeInsight.hint.ShowParameterInfoContext; +import com.intellij.codeInsight.hint.api.impls.MethodParameterInfoHandler; import com.intellij.codeInsight.lookup.*; import com.intellij.codeInsight.lookup.impl.JavaElementLookupRenderer; import com.intellij.codeInsight.template.*; @@ -26,10 +30,13 @@ import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.openapi.command.WriteCommandAction; +import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.Inlay; import com.intellij.openapi.editor.event.DocumentAdapter; import com.intellij.openapi.editor.event.DocumentEvent; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ClassConditionKey; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; @@ -44,6 +51,8 @@ import com.intellij.psi.util.TypeConversionUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** @@ -175,6 +184,7 @@ public class JavaMethodCallElement extends LookupItem implements Type } startArgumentLiveTemplate(context, method); + showParameterHints(context, method, methodCall); } static PsiCallExpression findCallAtOffset(InsertionContext context, int offset) { @@ -270,6 +280,45 @@ public class JavaMethodCallElement extends LookupItem implements Type return true; } + public static void showParameterHints(InsertionContext context, PsiMethod method, PsiCallExpression methodCall) { + PsiParameterList parameterList = method.getParameterList(); + int parametersCount = parameterList.getParametersCount(); + if (methodCall == null || + parametersCount == 0 || + context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR || + Registry.is("java.completion.argument.live.template") || + !Registry.is("java.completion.argument.hints")) { + return; + } + + Editor editor = context.getEditor(); + CaretModel caretModel = editor.getCaretModel(); + int offset = caretModel.getOffset(); + caretModel.moveToOffset(offset - 1); // avoid caret impact on hints location + editor.getDocument().insertString(offset, StringUtil.repeat(", ", parametersCount - 1)); + List addedHints = new ArrayList<>(parametersCount); + for (PsiParameter parameter : parameterList.getParameters()) { + String name = parameter.getName(); + if (name != null) { + addedHints.add(ParameterHintsPresentationManager.getInstance().addHint(editor, offset, name + ":", false, true)); + } + offset += 2; + } + int braceOffset = caretModel.getOffset(); + caretModel.moveToLogicalPosition(editor.offsetToLogicalPosition(braceOffset + 1).leanForward(true)); + + Project project = context.getProject(); + MethodParameterInfoHandler handler = new MethodParameterInfoHandler(); + ShowParameterInfoContext infoContext = new ShowParameterInfoContext(editor, project, context.getFile(), braceOffset, braceOffset); + handler.findElementForParameterInfo(infoContext); + + Disposer.register(new ParameterInfoController(project, editor, braceOffset, infoContext.getItemsToShow(), null, methodCall.getArgumentList(), handler, false, false), () -> { + for (Inlay inlay : addedHints) { + if (inlay != null) ParameterHintsPresentationManager.getInstance().unpin(inlay); + } + }); + } + private static void setupNonFilledArgumentRemoving(final Editor editor, final TemplateState templateState) { AtomicInteger maxEditedVariable = new AtomicInteger(-1); editor.getDocument().addDocumentListener(new DocumentAdapter() { diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchActionPromoter.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchActionPromoter.java new file mode 100644 index 000000000000..9e6d05723530 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchActionPromoter.java @@ -0,0 +1,31 @@ +/* + * Copyright 2000-2017 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.editorActions; + +import com.intellij.openapi.actionSystem.ActionPromoter; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.util.containers.ContainerUtil; + +import java.util.List; + +public class JavaMethodOverloadSwitchActionPromoter implements ActionPromoter { + @Override + public List promote(List actions, DataContext context) { + return ContainerUtil.findAll(actions, a -> a instanceof JavaMethodOverloadSwitchUpAction || + a instanceof JavaMethodOverloadSwitchDownAction); + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchDownAction.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchDownAction.java new file mode 100644 index 000000000000..1aef923d6217 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchDownAction.java @@ -0,0 +1,24 @@ +/* + * Copyright 2000-2017 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.editorActions; + +import com.intellij.openapi.editor.actionSystem.EditorAction; + +public class JavaMethodOverloadSwitchDownAction extends EditorAction { + public JavaMethodOverloadSwitchDownAction() { + super(new JavaMethodOverloadSwitchHandler(false)); + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchHandler.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchHandler.java new file mode 100644 index 000000000000..5d192522b6ec --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchHandler.java @@ -0,0 +1,149 @@ +/* + * Copyright 2000-2017 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.editorActions; + +import com.intellij.codeInsight.completion.CompletionMemory; +import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager; +import com.intellij.codeInsight.hint.ParameterInfoController; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Caret; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.Inlay; +import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.registry.Registry; +import com.intellij.psi.*; +import com.intellij.psi.infos.CandidateInfo; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; + +public class JavaMethodOverloadSwitchHandler extends EditorWriteActionHandler { + private static final Key> ENTERED_PARAMETERS = Key.create("entered.parameters"); + private final boolean mySwitchUp; + + public JavaMethodOverloadSwitchHandler(boolean up) { + mySwitchUp = up; + } + + @Override + protected boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { + if (!Registry.is("java.completion.argument.hints") || !ParameterInfoController.existsForEditor(editor)) return false; + + Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) return false; + + PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); + + PsiElement exprList = getExpressionList(editor, caret.getOffset(), project); + if (exprList == null) return false; + + int lbraceOffset = exprList.getTextRange().getStartOffset(); + return ParameterInfoController.findControllerAtOffset(editor, lbraceOffset) != null; + } + + @Nullable + private static PsiElement getExpressionList(@NotNull Editor editor, int offset, @NotNull Project project) { + PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); + return file != null ? ParameterInfoController.findArgumentList(file, offset, -1) : null; + } + + @Override + public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) { + if (caret == null) caret = editor.getCaretModel().getPrimaryCaret(); + Project project = CommonDataKeys.PROJECT.getData(dataContext); + if (project == null) return; + + PsiDocumentManager.getInstance(project).commitAllDocuments(); + + PsiElement exprList = getExpressionList(editor, caret.getOffset(), project); + if (!(exprList instanceof PsiExpressionList)) return; + + int lbraceOffset = exprList.getTextRange().getStartOffset(); + ParameterInfoController controller = ParameterInfoController.findControllerAtOffset(editor, lbraceOffset); + if (controller == null) return; + Object[] objects = controller.getObjects(); + Object highlighted = controller.getHighlighted(); + if (objects == null || objects.length <= 1 || highlighted == null) return; + + int currentIndex = ContainerUtil.indexOf(Arrays.asList(objects), highlighted); + if (currentIndex < 0) return; + + PsiMethod currentMethod = (PsiMethod)((CandidateInfo)objects[currentIndex]).getElement(); + + Map enteredParameters = exprList.getUserData(ENTERED_PARAMETERS); + if (enteredParameters == null) { + exprList.putUserData(ENTERED_PARAMETERS, enteredParameters = new HashMap<>()); + } + PsiExpression[] enteredExpressions = ((PsiExpressionList)exprList).getExpressions(); + assert enteredExpressions.length == 0 || enteredExpressions.length == currentMethod.getParameterList().getParametersCount(); + for (int i = 0; i < enteredExpressions.length; i++) { + PsiExpression expression = enteredExpressions[i]; + String value = expression.getText().trim(); + if (!value.isEmpty()) { + String key = getParameterKey(currentMethod, i); + enteredParameters.put(key, value); + } + } + + PsiMethod targetMethod = (PsiMethod)((CandidateInfo)objects[(currentIndex + (mySwitchUp ? -1 : 1) + objects.length) % objects.length]).getElement(); + PsiParameterList parameterList = targetMethod.getParameterList(); + int parametersCount = parameterList.getParametersCount(); + caret.moveToOffset(lbraceOffset); // avoid caret impact on hints location + int offset = lbraceOffset + 1; + int endOffset = exprList.getTextRange().getEndOffset() - 1; + List oldInlays = editor.getInlayModel().getInlineElementsInRange(offset, endOffset); + for (Inlay inlay : oldInlays) { + Disposer.dispose(inlay); + } + editor.getDocument().deleteString(offset, endOffset); + int targetCaretPosition = -1; + List addedHints = new ArrayList<>(parametersCount); + for (int i = 0; i < parametersCount; i++) { + String key = getParameterKey(targetMethod, i); + String value = enteredParameters.getOrDefault(key, ""); + if (value.isEmpty() && targetCaretPosition == -1) targetCaretPosition = offset; + if (i < parametersCount - 1) value += ", "; + editor.getDocument().insertString(offset, value); + String name = parameterList.getParameters()[i].getName(); + if (name != null) { + addedHints.add(ParameterHintsPresentationManager.getInstance().addHint(editor, offset, name + ":", false, true)); + } + offset += value.length(); + } + if (targetCaretPosition == -1) targetCaretPosition = offset; + caret.moveToLogicalPosition(editor.offsetToLogicalPosition(targetCaretPosition).leanForward(true)); + Disposer.register(controller, () -> { + for (Inlay hint : addedHints) { + if (hint != null) ParameterHintsPresentationManager.getInstance().unpin(hint); + } + }); + + PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); + CompletionMemory.registerChosenMethod(targetMethod, (PsiCall)exprList.getParent()); + controller.updateComponent(); // update popup immediately (otherwise, it will be updated only after delay) + } + + private static String getParameterKey(PsiMethod method, int parameterIndex) { + PsiParameter parameter = method.getParameterList().getParameters()[parameterIndex]; + return parameter.getName() + ":" + parameter.getType().getCanonicalText(); + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchUpAction.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchUpAction.java new file mode 100644 index 000000000000..50ba335ad4c3 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/JavaMethodOverloadSwitchUpAction.java @@ -0,0 +1,24 @@ +/* + * Copyright 2000-2017 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.editorActions; + +import com.intellij.openapi.editor.actionSystem.EditorAction; + +public class JavaMethodOverloadSwitchUpAction extends EditorAction { + public JavaMethodOverloadSwitchUpAction() { + super(new JavaMethodOverloadSwitchHandler(true)); + } +} diff --git a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java index 0ed2ffde8cdb..d1df957a9441 100644 --- a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java @@ -107,13 +107,6 @@ public class PsiMethodReferenceUtil { return false; } - PsiClass qContainingClass = getQualifierResolveResult(expression).getContainingClass(); - if (qContainingClass != null && containingClass != null && - isReceiverType(getFirstParameterType(functionalInterfaceType, expression), qContainingClass, subst)) { - subst = TypeConversionUtil.getClassSubstitutor(containingClass, qContainingClass, subst); - LOG.assertTrue(subst != null); - } - methodReturnType = subst.substitute(methodReturnType); } } diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaReadWriteAccessDetector.java b/java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaReadWriteAccessDetector.java index 542b65defc9f..3c93c6a1b1b3 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaReadWriteAccessDetector.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaReadWriteAccessDetector.java @@ -26,7 +26,7 @@ import org.jetbrains.annotations.NotNull; public class JavaReadWriteAccessDetector extends ReadWriteAccessDetector { @Override public boolean isReadWriteAccessible(@NotNull final PsiElement element) { - return element instanceof PsiVariable && !(element instanceof ImplicitVariable) || element instanceof PsiClass; + return element instanceof PsiVariable && !(element instanceof ImplicitVariable) || element instanceof PsiClass || element instanceof PsiAnnotationMethod && !(element instanceof PsiCompiledElement); } @Override @@ -49,7 +49,12 @@ public class JavaReadWriteAccessDetector extends ReadWriteAccessDetector { @NotNull @Override public Access getExpressionAccess(@NotNull final PsiElement expression) { - if (!(expression instanceof PsiExpression)) return Access.Read; + if (!(expression instanceof PsiExpression)) { + if (expression instanceof PsiNameValuePair || expression instanceof PsiIdentifier) { + return Access.Write; + } + return Access.Read; + } PsiExpression expr = (PsiExpression) expression; boolean readAccess = PsiUtil.isAccessedForReading(expr); boolean writeAccess = PsiUtil.isAccessedForWriting(expr); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java index 2b2255f1ee22..284673d2d47d 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java @@ -1607,7 +1607,8 @@ public class InferenceSession { if (receiverSubstitutor != null) { if (!method.hasTypeParameters()) { if (signature.getParameterTypes().length == 1 || PsiUtil.isRawSubstitutor(containingClass, receiverSubstitutor)) { - return receiverSubstitutor; + return methodContainingClass != null ? JavaClassSupers.getInstance().getSuperClassSubstitutor(methodContainingClass, containingClass, reference.getResolveScope(), receiverSubstitutor) + : receiverSubstitutor; } } mySiteSubstitutor = mySiteSubstitutor.putAll(receiverSubstitutor); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/StrictSubtypingConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/StrictSubtypingConstraint.java index 6bb3ba3ba570..3da15169078e 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/StrictSubtypingConstraint.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/StrictSubtypingConstraint.java @@ -185,6 +185,13 @@ public class StrictSubtypingConstraint implements ConstraintFormula { return true; } + if (myT instanceof PsiCapturedWildcardType) { + PsiType lowerBound = ((PsiCapturedWildcardType)myT).getLowerBound(); + if (lowerBound != PsiType.NULL) { + constraints.add(new StrictSubtypingConstraint(lowerBound, myS)); + } + } + return true; } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/LowerBoundOfCapturedWildcardInSubtypingConstraint.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/LowerBoundOfCapturedWildcardInSubtypingConstraint.java new file mode 100644 index 000000000000..02bf58cfa8df --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/LowerBoundOfCapturedWildcardInSubtypingConstraint.java @@ -0,0 +1,17 @@ + +import java.util.Collections; +import java.util.List; + +interface Processor

{ + void process(P t); +} + +class Test { + void foo(Processor> p) { + p.process(Collections.emptyList()); + } + + void bar(Processor> p) { + p.process(Collections.emptyList()); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/MethodInInheritorFoundBySecondSearch.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/MethodInInheritorFoundBySecondSearch.java new file mode 100644 index 000000000000..5ea4fc64d237 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/MethodInInheritorFoundBySecondSearch.java @@ -0,0 +1,15 @@ + +import java.util.function.BiFunction; +import java.util.function.Function; + +class Test { + interface MyBaseStream> { + MyStream map(Function mapper); + } + + interface MyStream extends MyBaseStream> {} + + { + BiFunction, Function, MyStream> streamMapper = MyStream::map; + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/CompletionHintsTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/CompletionHintsTest.java new file mode 100644 index 000000000000..5644f3681518 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/CompletionHintsTest.java @@ -0,0 +1,130 @@ +/* + * Copyright 2000-2017 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.completion; + +import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager; +import com.intellij.codeInsight.hint.ParameterInfoController; +import com.intellij.codeInsight.lookup.LookupElement; +import com.intellij.codeInsight.lookup.LookupElementPresentation; +import com.intellij.ide.highlighter.JavaFileType; +import com.intellij.openapi.util.registry.Registry; +import com.intellij.openapi.util.registry.RegistryValue; +import com.intellij.util.ui.UIUtil; + +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +public class CompletionHintsTest extends LightFixtureCompletionTestCase { + private RegistryValue myRegistryValue = Registry.get("java.completion.argument.hints"); + private boolean myStoredRegistryValue; + + @Override + protected void setUp() throws Exception { + super.setUp(); + myStoredRegistryValue = myRegistryValue.asBoolean(); + myRegistryValue.setValue(true); + } + + @Override + protected void tearDown() throws Exception { + try { + myRegistryValue.setValue(myStoredRegistryValue); + } + finally { + super.tearDown(); + } + } + + public void testBasicScenario() throws Exception { + // check hints appearance on completion + myFixture.configureByText(JavaFileType.INSTANCE, "class C { void m() { System.setPro } }"); + complete("setProperty"); + myFixture.checkResultWithInlays("class C { void m() { System.setProperty(, ) } }"); + + // check that hints don't disappear after daemon highlighting passes + myFixture.doHighlighting(); + myFixture.checkResultWithInlays("class C { void m() { System.setProperty(, ) } }"); + + // test Tab/Shift+Tab navigation + myFixture.checkResult("class C { void m() { System.setProperty(, ) } }"); + assertTrue(myFixture.getEditor().getCaretModel().getLogicalPosition().leansForward); + myFixture.performEditorAction("NextParameter"); + myFixture.checkResult("class C { void m() { System.setProperty(, ) } }"); + assertTrue(myFixture.getEditor().getCaretModel().getLogicalPosition().leansForward); + myFixture.performEditorAction("PrevParameter"); + myFixture.checkResult("class C { void m() { System.setProperty(, ) } }"); + assertTrue(myFixture.getEditor().getCaretModel().getLogicalPosition().leansForward); + + // test hints remain shown while entering parameter values + myFixture.type("\"a"); + myFixture.performEditorAction("NextParameter"); + myFixture.type("\"b"); + myFixture.doHighlighting(); + myFixture.checkResultWithInlays("class C { void m() { System.setProperty(\"a\", \"b\") } }"); + + // test hints disappearance when caret moves out of parameter list + myFixture.performEditorAction("EditorRight"); + myFixture.performEditorAction("EditorRight"); + ParameterInfoController.waitForDelayedActions(getEditor(), 10, TimeUnit.SECONDS); + + myFixture.doHighlighting(); + waitTillAnimationCompletes(); + myFixture.checkResultWithInlays("class C { void m() { System.setProperty(\"a\", \"b\") } }"); + } + + public void testSwitchingOverloads() { + myFixture.configureByText(JavaFileType.INSTANCE, "class C { void m() { Character.to } }"); + complete("toChars(int codePoint)"); + myFixture.checkResultWithInlays("class C { void m() { Character.toChars() } }"); + showParameterInfo(); + myFixture.performEditorAction("MethodOverloadSwitchDown"); + myFixture.checkResultWithInlays("class C { void m() { Character.toChars(, , ) } }"); + } + + public void testSwitchingOverloadsWithParameterFilled() { + myFixture.configureByText(JavaFileType.INSTANCE, "class C { void m() { Character.to } }"); + complete("toChars(int codePoint)"); + type("123"); + myFixture.checkResultWithInlays("class C { void m() { Character.toChars(123) } }"); + showParameterInfo(); + myFixture.performEditorAction("MethodOverloadSwitchDown"); + myFixture.checkResultWithInlays("class C { void m() { Character.toChars(123, , ) } }"); + myFixture.checkResult("class C { void m() { Character.toChars(123, , ) } }"); + } + + private void showParameterInfo() { + myFixture.performEditorAction("ParameterInfo"); + UIUtil.dispatchAllInvocationEvents(); + } + + private void complete(String partOfItemText) { + LookupElement[] elements = myFixture.completeBasic(); + LookupElement element = Stream.of(elements).filter(e -> { + LookupElementPresentation p = new LookupElementPresentation(); + e.renderElement(p); + return (p.getItemText() + p.getTailText()).contains(partOfItemText); + }).findAny().get(); + selectItem(element); + } + + private void waitTillAnimationCompletes() { + long deadline = System.currentTimeMillis() + 60_000; + while (ParameterHintsPresentationManager.getInstance().isAnimationInProgress(getEditor())) { + if (System.currentTimeMillis() > deadline) fail("Too long waiting for animation to finish"); + UIUtil.dispatchAllInvocationEvents(); + } + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java index 70a6e9d942a9..1447275e3aef 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java @@ -1005,6 +1005,10 @@ public class GenericsHighlighting8Test extends LightDaemonAnalyzerTestCase { doTest(true); } + public void testLowerBoundOfCapturedWildcardInSubtypingConstraint() throws Exception { + doTest(true); + } + public void testMembersContainedInCapturedWildcardType() throws Exception { doTest(); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java index af4633b87e9b..79a9e1db466c 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java @@ -537,6 +537,10 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase { doTest(); } + public void testMethodInInheritorFoundBySecondSearch() throws Exception { + doTest(); + } + public void testNonExactMethodReferenceOnRawClassType() throws Exception { doTest(); } diff --git a/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectAnnotator.java b/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectAnnotator.java index ec1ea6798856..ffb9b2cff586 100644 --- a/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectAnnotator.java +++ b/json/src/com/jetbrains/jsonSchema/impl/JsonBySchemaObjectAnnotator.java @@ -39,7 +39,7 @@ import java.util.*; /** * @author Irina.Chernushina on 8/31/2015. */ -class JsonBySchemaObjectAnnotator implements Annotator { +public class JsonBySchemaObjectAnnotator implements Annotator { private final static Logger LOG = Logger.getInstance("#com.jetbrains.jsonSchema.JsonBySchemaAnnotator"); private static final Key> ANNOTATED_PROPERTIES = Key.create("JsonSchema.Properties.Annotated"); @NotNull private final VirtualFile mySchemaFile; diff --git a/platform/core-api/src/com/intellij/ide/HelpIdProvider.java b/platform/core-api/src/com/intellij/ide/HelpIdProvider.java index 77dd11c91334..80329e1b53f4 100644 --- a/platform/core-api/src/com/intellij/ide/HelpIdProvider.java +++ b/platform/core-api/src/com/intellij/ide/HelpIdProvider.java @@ -15,8 +15,10 @@ */ package com.intellij.ide; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; public interface HelpIdProvider { - @Nullable String getHelpId(); + @Nullable @NonNls + String getHelpId(); } diff --git a/platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt b/platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt index fc4d38632a27..494b0366d992 100644 --- a/platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt +++ b/platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt @@ -53,7 +53,7 @@ class UISettings : BaseState(), PersistentStateComponent { @get:Property(filter = FontFilter::class) @get:OptionTag("FONT_SIZE") - var fontSize by storedProperty(10) + var fontSize by storedProperty(12) @get:Property(filter = FontFilter::class) @get:OptionTag("FONT_SCALE") diff --git a/platform/editor-ui-api/src/com/intellij/openapi/editor/colors/FontPreferences.java b/platform/editor-ui-api/src/com/intellij/openapi/editor/colors/FontPreferences.java index 76cb55b0e6d4..8d5271faee51 100644 --- a/platform/editor-ui-api/src/com/intellij/openapi/editor/colors/FontPreferences.java +++ b/platform/editor-ui-api/src/com/intellij/openapi/editor/colors/FontPreferences.java @@ -29,6 +29,9 @@ public interface FontPreferences { int DEFAULT_FONT_SIZE = FontSize.SMALL.getSize(); float DEFAULT_LINE_SPACING = 1.0f; + String MAC_OS_DEFAULT_FONT_FAMILY = "Menlo"; + String LINUX_DEFAULT_FONT_FAMILY = "DejaVu Sans Mono"; + String WINDOWS_DEFAULT_FONT_FAMILY = "Monospaced"; @NotNull List getEffectiveFontFamilies(); @@ -74,14 +77,14 @@ public interface FontPreferences { } static String getDefaultFontName() { - if (SystemInfo.isMacOSSnowLeopard) return "Menlo"; + if (SystemInfo.isMacOSSnowLeopard) return MAC_OS_DEFAULT_FONT_FAMILY; if (SystemInfo.isXWindow && !GraphicsEnvironment.isHeadless()) { for (Font font : GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()) { - if ("DejaVu Sans Mono".equals(font.getName())) { + if (LINUX_DEFAULT_FONT_FAMILY.equals(font.getName())) { return font.getFontName(); } } } - return "Monospaced"; + return WINDOWS_DEFAULT_FONT_FAMILY; } } diff --git a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java index 8350f2fd9e08..122cc01fe328 100644 --- a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java +++ b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/AbstractColorsScheme.java @@ -35,7 +35,6 @@ import com.intellij.util.PlatformUtils; import com.intellij.util.containers.ContainerUtilRt; import com.intellij.util.containers.HashMap; import com.intellij.util.ui.JBUI; -import com.intellij.util.ui.UIUtil; import gnu.trove.THashMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; @@ -54,6 +53,7 @@ import static com.intellij.openapi.editor.markup.TextAttributes.USE_INHERITED_MA import static com.intellij.openapi.util.Couple.of; import static com.intellij.ui.ColorUtil.fromHex; +@SuppressWarnings("UseJBColor") public abstract class AbstractColorsScheme implements EditorColorsScheme, SerializableScheme { private static final int CURR_VERSION = 142; @@ -422,10 +422,11 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme, Serial } continue; } - TextAttributes attr = myValueReader.read(TextAttributes.class, valueElement); - myAttributesMap.put(key, attr); - migrateErrorStripeColorFrom14(key, attr); + if (attr != null) { + myAttributesMap.put(key, attr); + migrateErrorStripeColorFrom14(key, attr); + } } } @@ -522,10 +523,11 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme, Serial } private int readFontSize(Element element, boolean isDefault, Float fontScale) { - Float size = (float)myValueReader.read(Integer.class, element); - if (size == null) { + Integer intSize = myValueReader.read(Integer.class, element); + if (intSize == null) { return -1; } + Float size = (float)intSize; if (!isDefault) { size = (fontScale != null) ? size / fontScale : DEFAULT_FONT_SIZE.getSize(); } @@ -562,7 +564,7 @@ public abstract class AbstractColorsScheme implements EditorColorsScheme, Serial parentNode.setAttribute(NAME_ATTR, getName()); parentNode.setAttribute(VERSION_ATTR, Integer.toString(myVersion)); - /** + /* * FONT_SCALE is used to correctly identify the font size in both the JRE-managed HiDPI mode and * the IDE-managed HiDPI mode: {@link UIUtil#isJreHiDPIEnabled()}. Also, it helps to distinguish * the "hidpi-aware" scheme version from the previous one. Namely, the absence of the FONT_SCALE diff --git a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/ValueElementReader.java b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/ValueElementReader.java index 791b622ec74b..bb686942f56c 100644 --- a/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/ValueElementReader.java +++ b/platform/editor-ui-ex/src/com/intellij/openapi/editor/colors/impl/ValueElementReader.java @@ -20,6 +20,7 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import org.jdom.Element; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.Nullable; import java.awt.Color; @@ -32,6 +33,7 @@ import java.awt.Color; * * @author Sergey.Malenkov */ +@SuppressWarnings("UseJBColor") class ValueElementReader { @NonNls private static final String VALUE = "value"; @NonNls private static final String MAC = "mac"; @@ -60,6 +62,7 @@ class ValueElementReader { * @param the result type * @return a value or {@code null} if it cannot be read */ + @Nullable public T read(Class type, Element element) { T value = null; if (element != null) { diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/AbstractExternalSystemRunConfigurationProducer.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/AbstractExternalSystemRunConfigurationProducer.java index 3dd8fbcb03ed..830893c5bc02 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/AbstractExternalSystemRunConfigurationProducer.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/AbstractExternalSystemRunConfigurationProducer.java @@ -20,11 +20,12 @@ import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings; -import com.intellij.openapi.externalSystem.model.execution.ExternalTaskExecutionInfo; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * @author Vladislav.Soroka @@ -37,7 +38,7 @@ public abstract class AbstractExternalSystemRunConfigurationProducer extends Run } @Override - public boolean shouldReplace(ConfigurationFromContext self, ConfigurationFromContext other) { + public boolean shouldReplace(@NotNull ConfigurationFromContext self, @NotNull ConfigurationFromContext other) { return true; } @@ -45,34 +46,33 @@ public abstract class AbstractExternalSystemRunConfigurationProducer extends Run protected boolean setupConfigurationFromContext(ExternalSystemRunConfiguration configuration, ConfigurationContext context, Ref sourceElement) { - Location location = context.getLocation(); - if (!(location instanceof ExternalSystemTaskLocation)) { + Project project = getProjectFromContext(context); + if (project == null) return false; + + ExternalSystemTaskExecutionSettings contextTaskExecutionSettings = getTaskSettingsFromContext(context); + if (contextTaskExecutionSettings == null) return false; + + ExternalSystemTaskExecutionSettings taskExecutionSettings = configuration.getSettings(); + if (!contextTaskExecutionSettings.getExternalSystemId().equals(taskExecutionSettings.getExternalSystemId())) { return false; } - ExternalSystemTaskLocation taskLocation = (ExternalSystemTaskLocation)location; - ExternalSystemTaskExecutionSettings taskExecutionSettings = configuration.getSettings(); - ExternalTaskExecutionInfo task = taskLocation.getTaskInfo(); - taskExecutionSettings.setExternalProjectPath(task.getSettings().getExternalProjectPath()); - taskExecutionSettings.setTaskNames(task.getSettings().getTaskNames()); - configuration.setName(AbstractExternalSystemTaskConfigurationType.generateName(location.getProject(), taskExecutionSettings)); + taskExecutionSettings.setExternalProjectPath(contextTaskExecutionSettings.getExternalProjectPath()); + taskExecutionSettings.setTaskNames(contextTaskExecutionSettings.getTaskNames()); + configuration.setName(AbstractExternalSystemTaskConfigurationType.generateName(project, taskExecutionSettings)); return true; } @Override public boolean isConfigurationFromContext(ExternalSystemRunConfiguration configuration, ConfigurationContext context) { - final Location contextLocation = context.getLocation(); - if (contextLocation == null) return false; + Project project = getProjectFromContext(context); + if (project == null) return false; - if (!(contextLocation instanceof ExternalSystemTaskLocation)) { - return false; - } + ExternalSystemTaskExecutionSettings contextTaskExecutionSettings = getTaskSettingsFromContext(context); + if (contextTaskExecutionSettings == null) return false; - ExternalSystemTaskLocation taskLocation = (ExternalSystemTaskLocation)contextLocation; - ExternalSystemTaskExecutionSettings contextTaskExecutionSettings = taskLocation.getTaskInfo().getSettings(); ExternalSystemTaskExecutionSettings taskExecutionSettings = configuration.getSettings(); - - if(!contextTaskExecutionSettings.getExternalSystemId().equals(taskExecutionSettings.getExternalSystemId())) { + if (!contextTaskExecutionSettings.getExternalSystemId().equals(taskExecutionSettings.getExternalSystemId())) { return false; } if (!StringUtil.equals(contextTaskExecutionSettings.getExternalProjectPath(), taskExecutionSettings.getExternalProjectPath())) { @@ -81,4 +81,22 @@ public abstract class AbstractExternalSystemRunConfigurationProducer extends Run if (!contextTaskExecutionSettings.getTaskNames().equals(taskExecutionSettings.getTaskNames())) return false; return true; } + + @Nullable + private static ExternalSystemTaskExecutionSettings getTaskSettingsFromContext(ConfigurationContext context) { + final Location contextLocation = context.getLocation(); + if (!(contextLocation instanceof ExternalSystemTaskLocation)) { + return null; + } + return ((ExternalSystemTaskLocation)contextLocation).getTaskInfo().getSettings(); + } + + @Nullable + private static Project getProjectFromContext(ConfigurationContext context) { + final Location contextLocation = context.getLocation(); + if (!(contextLocation instanceof ExternalSystemTaskLocation)) { + return null; + } + return contextLocation.getProject(); + } } \ No newline at end of file diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/IdeModelsProviderImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/IdeModelsProviderImpl.java index 20e3e0193287..1ac5390e3ee1 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/IdeModelsProviderImpl.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/IdeModelsProviderImpl.java @@ -15,7 +15,6 @@ */ package com.intellij.openapi.externalSystem.service.project; -import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys; import com.intellij.openapi.externalSystem.model.project.*; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleGrouperKt; @@ -103,11 +102,9 @@ public class IdeModelsProviderImpl implements IdeModelsProvider { } private static boolean isApplicableIdeModule(@NotNull ModuleData moduleData, @NotNull Module ideModule) { - if (ideModule.getProject().getUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT) == Boolean.TRUE) { - for (VirtualFile root : ModuleRootManager.getInstance(ideModule).getContentRoots()) { - if (pathsEqual(root.getPath(), moduleData.getLinkedExternalProjectPath())) { - return true; - } + for (VirtualFile root : ModuleRootManager.getInstance(ideModule).getContentRoots()) { + if (pathsEqual(root.getPath(), moduleData.getLinkedExternalProjectPath())) { + return true; } } return isExternalSystemAwareModule(moduleData.getOwner(), ideModule) && diff --git a/platform/indexing-api/src/com/intellij/lang/findUsages/FindUsagesProvider.java b/platform/indexing-api/src/com/intellij/lang/findUsages/FindUsagesProvider.java index b4faf829c909..46319061e507 100644 --- a/platform/indexing-api/src/com/intellij/lang/findUsages/FindUsagesProvider.java +++ b/platform/indexing-api/src/com/intellij/lang/findUsages/FindUsagesProvider.java @@ -17,6 +17,7 @@ package com.intellij.lang.findUsages; import com.intellij.lang.cacheBuilder.WordsScanner; import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -54,7 +55,7 @@ public interface FindUsagesProvider { * @param psiElement the element for which the help topic is requested. * @return the help topic ID, or null if no help is available. */ - @Nullable + @Nullable @NonNls String getHelpId(@NotNull PsiElement psiElement); /** diff --git a/platform/lang-api/src/com/intellij/ide/util/gotoByName/ChooseByNameModel.java b/platform/lang-api/src/com/intellij/ide/util/gotoByName/ChooseByNameModel.java index 9497519d9809..a0a29b98f2a8 100644 --- a/platform/lang-api/src/com/intellij/ide/util/gotoByName/ChooseByNameModel.java +++ b/platform/lang-api/src/com/intellij/ide/util/gotoByName/ChooseByNameModel.java @@ -15,6 +15,7 @@ */ package com.intellij.ide.util.gotoByName; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -59,7 +60,7 @@ public interface ChooseByNameModel { @Nullable String getFullName(Object element); - @Nullable + @Nullable @NonNls String getHelpId(); boolean willOpenEditor(); diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/InlineElementData.java b/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/InlineElementData.java index 6f027c47346e..c73357770e53 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/InlineElementData.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/highlighting/InlineElementData.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 JetBrains s.r.o. + * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ public class InlineElementData extends HighlightData { @Override public void addHighlToView(Editor view, EditorColorsScheme scheme, Map displayText) { int offset = getStartOffset(); - ParameterHintsPresentationManager.getInstance().addHint(view, offset, myText, false); + ParameterHintsPresentationManager.getInstance().addHint(view, offset, myText, false, false); List inlays = view.getInlayModel().getInlineElementsInRange(offset, offset); for (Inlay inlay : inlays) { EditorCustomElementRenderer renderer = inlay.getRenderer(); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java index 98015fc61b8b..6aec6f29809f 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java @@ -863,8 +863,12 @@ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzerEx implements Pers public void run() { ApplicationManager.getApplication().assertIsDispatchThread(); Project project = myProject; - DaemonCodeAnalyzerImpl daemonCodeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project); - if (project == null || !project.isInitialized() || project.isDisposed() || PowerSaveMode.isEnabled() || daemonCodeAnalyzer.myDisposed) { + DaemonCodeAnalyzerImpl daemonCodeAnalyzer; + if (project == null || + !project.isInitialized() || + project.isDisposed() || + PowerSaveMode.isEnabled() || + (daemonCodeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project)).myDisposed) { return; } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ParameterHintsPresentationManager.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ParameterHintsPresentationManager.java index 32389bf0c34e..c1f2cb5d5c05 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ParameterHintsPresentationManager.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ParameterHintsPresentationManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 JetBrains s.r.o. + * Copyright 2000-2017 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,7 @@ import com.intellij.util.Alarm; import com.intellij.util.ui.GraphicsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.awt.*; @@ -42,6 +43,7 @@ import java.util.Iterator; import java.util.Set; public class ParameterHintsPresentationManager implements Disposable { + private static final Key PINNED = Key.create("parameter.hint.pinned"); private static final Key HINT_FONT_METRICS = Key.create("ParameterHintFontMetrics"); private static final Key ANIMATION_STEP = Key.create("ParameterHintAnimationStep"); @@ -62,17 +64,27 @@ public class ParameterHintsPresentationManager implements Disposable { return inlay.getRenderer() instanceof MyRenderer; } + public boolean isPinned(@NotNull Inlay inlay) { + return Boolean.TRUE.equals(inlay.getUserData(PINNED)); + } + + public void unpin(@NotNull Inlay inlay) { + inlay.putUserData(PINNED, null); + } + public String getHintText(@NotNull Inlay inlay) { EditorCustomElementRenderer renderer = inlay.getRenderer(); return renderer instanceof MyRenderer ? ((MyRenderer)renderer).getText() : null; } - public void addHint(@NotNull Editor editor, int offset, @NotNull String hintText, boolean useAnimation) { + public Inlay addHint(@NotNull Editor editor, int offset, @NotNull String hintText, boolean useAnimation, boolean pinned) { MyRenderer renderer = new MyRenderer(editor, hintText, useAnimation); Inlay inlay = editor.getInlayModel().addInlineElement(offset, renderer); - if (useAnimation && inlay != null) { - scheduleRendererUpdate(editor, inlay); + if (inlay != null) { + if (pinned) inlay.putUserData(PINNED, Boolean.TRUE); + if (useAnimation) scheduleRendererUpdate(editor, inlay); } + return inlay; } public void deleteHint(@NotNull Editor editor, @NotNull Inlay hint) { @@ -109,6 +121,12 @@ public class ParameterHintsPresentationManager implements Disposable { myAlarm.addRequest(step, ANIMATION_STEP_MS, ModalityState.any()); } + @TestOnly + public boolean isAnimationInProgress(@NotNull Editor editor) { + ApplicationManager.getApplication().assertIsDispatchThread(); + return editor.getUserData(ANIMATION_STEP) != null; + } + private static Font getFont(@NotNull Editor editor) { return getFontMetrics(editor).getFont(); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoComponent.java index e2c530389028..d56e0ae0926f 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoComponent.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2017 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. @@ -140,10 +140,6 @@ public class ParameterInfoComponent extends JPanel { return myHighlighted; } - public void setRequestFocus(boolean requestFocus) { - myRequestFocus = requestFocus; - } - public boolean isRequestFocus() { return myRequestFocus; } 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 10220feb168b..c0b39419367e 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java @@ -16,18 +16,19 @@ package com.intellij.codeInsight.hint; +import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.ide.IdeTooltip; +import com.intellij.injected.editor.EditorWindow; import com.intellij.lang.parameterInfo.ParameterInfoHandler; import com.intellij.lang.parameterInfo.ParameterInfoHandlerWithTabActionSupport; import com.intellij.lang.parameterInfo.ParameterInfoUtils; import com.intellij.lang.parameterInfo.UpdateParameterInfoContext; import com.intellij.openapi.Disposable; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.RangeMarker; -import com.intellij.openapi.editor.ScrollType; +import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.project.DumbService; @@ -36,19 +37,21 @@ import com.intellij.openapi.ui.popup.Balloon.Position; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; -import com.intellij.psi.PsiDocumentManager; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.psi.TokenType; +import com.intellij.openapi.util.TextRange; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.psi.*; import com.intellij.psi.util.PsiUtilBase; import com.intellij.psi.util.PsiUtilCore; +import com.intellij.ui.HintHint; import com.intellij.ui.LightweightHint; import com.intellij.util.Alarm; import com.intellij.util.containers.JBIterable; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.text.CharArrayUtil; +import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.awt.*; @@ -56,6 +59,8 @@ import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; public class ParameterInfoController implements Disposable { private final Project myProject; @@ -64,15 +69,16 @@ public class ParameterInfoController implements Disposable { private final RangeMarker myLbraceMarker; private final LightweightHint myHint; private final ParameterInfoComponent myComponent; + private final boolean myKeepOnHintHidden; private final CaretListener myEditorCaretListener; @NotNull private final ParameterInfoHandler myHandler; - private final ShowParameterInfoHandler.BestLocationPointProvider myProvider; + private final MyBestLocationPointProvider myProvider; private final Alarm myAlarm = new Alarm(); private static final int DELAY = 200; - private boolean myDisposed = false; + private boolean myDisposed; /** * Keeps Vector of ParameterInfoController's in Editor @@ -85,7 +91,7 @@ public class ParameterInfoController implements Disposable { ParameterInfoController controller = allControllers.get(i); if (controller.myLbraceMarker.getStartOffset() == offset) { - if (controller.myHint.isVisible()) return controller; + if (controller.myKeepOnHintHidden || controller.myHint.isVisible()) return controller; Disposer.dispose(controller); --i; } @@ -103,27 +109,40 @@ public class ParameterInfoController implements Disposable { return array; } - public static boolean isShownForEditor(@NotNull Editor editor) { + public static boolean existsForEditor(@NotNull Editor editor) { return !getAllControllers(editor).isEmpty(); } public static boolean isAlreadyShown(Editor editor, int lbraceOffset) { - return findControllerAtOffset(editor, lbraceOffset) != null; + ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset); + return controller != null && controller.myHint.isVisible(); } public ParameterInfoController(@NotNull Project project, @NotNull Editor editor, int lbraceOffset, - @NotNull LightweightHint hint, + Object[] descriptors, + Object highlighted, + PsiElement parameterOwner, @NotNull ParameterInfoHandler handler, - @NotNull ShowParameterInfoHandler.BestLocationPointProvider provider) { + boolean showHint, + boolean requestFocus) { myProject = project; myEditor = editor; myHandler = handler; - myProvider = provider; + myProvider = new MyBestLocationPointProvider(editor); myLbraceMarker = editor.getDocument().createRangeMarker(lbraceOffset, lbraceOffset); - myHint = hint; - myComponent = (ParameterInfoComponent)myHint.getComponent(); + myComponent = new ParameterInfoComponent(descriptors, editor, handler, requestFocus); + myHint = new LightweightHint(myComponent); + myKeepOnHintHidden = !showHint; + + myHint.setSelectingHint(true); + myComponent.setParameterOwner(parameterOwner); + myComponent.setHighlightedParameter(highlighted); + myComponent.update(); // to have correct preferred size + if (showHint) { + showHint(requestFocus); + } List allControllers = getAllControllers(myEditor); allControllers.add(this); @@ -175,12 +194,26 @@ public class ParameterInfoController implements Disposable { public void dispose(){ if (myDisposed) return; myDisposed = true; - + myHint.hide(); List allControllers = getAllControllers(myEditor); allControllers.remove(this); myEditor.getCaretModel().removeCaretListener(myEditorCaretListener); } + public void showHint(boolean requestFocus) { + Pair pos = myProvider.getBestPointPosition(myHint, myComponent.getParameterOwner(), myLbraceMarker.getStartOffset(), true, HintManager.UNDER); + HintHint hintHint = HintManagerImpl.createHintHint(myEditor, pos.getFirst(), myHint, pos.getSecond()); + hintHint.setExplicitClose(true); + hintHint.setRequestFocus(requestFocus); + + Editor editorToShow = myEditor instanceof EditorWindow ? ((EditorWindow)myEditor).getDelegate() : myEditor; + // is case of injection we need to calculate position for EditorWindow + // also we need to show the hint in the main editor because of intention bulb + HintManagerImpl.getInstanceImpl().showEditorHint(myHint, editorToShow, pos.getFirst(), HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false, hintHint); + + updateComponent(); + } + private void adjustPositionForLookup(@NotNull Lookup lookup) { if (!myHint.isVisible() || myEditor.isDisposed()) { Disposer.dispose(this); @@ -221,8 +254,34 @@ public class ParameterInfoController implements Disposable { myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent())); } - private void updateComponent(){ - if (!myHint.isVisible()){ + public void updateComponent(){ + if (myKeepOnHintHidden) { + boolean removeHints = true; + PsiElement owner = myComponent.getParameterOwner(); + if (owner != null && owner.isValid()) { + int caretOffset = myEditor.getCaretModel().getOffset(); + TextRange ownerTextRange = owner.getTextRange(); + if (ownerTextRange != null) { + if (caretOffset > ownerTextRange.getStartOffset() && caretOffset < ownerTextRange.getEndOffset()) { + removeHints = false; + } + else { + for (PsiElement element : owner.getChildren()) { + if (element instanceof PsiErrorElement) { + removeHints = false; + break; + } + } + } + } + } + if (removeHints) { + Disposer.dispose(this); + return; + } + } + + if (!myHint.isVisible() && !myKeepOnHintHidden && !ApplicationManager.getApplication().isUnitTestMode()) { Disposer.dispose(this); return; } @@ -290,12 +349,26 @@ public class ParameterInfoController implements Disposable { PsiElement argsList = findArgumentList(file, offset, -1); if (argsList == null) return; - myEditor.getCaretModel().moveToOffset(offset); + offset = adjustOffsetToInlay(offset); + + myEditor.getCaretModel().moveToLogicalPosition(myEditor.offsetToLogicalPosition(offset).leanForward(true)); myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); myEditor.getSelectionModel().removeSelection(); myHandler.updateParameterInfo(argsList, new MyUpdateParameterInfoContext(offset, file)); } + private int adjustOffsetToInlay(int offset) { + CharSequence text = myEditor.getDocument().getImmutableCharSequence(); + String whitespaceChars = " \t"; + int whitespaceStart = CharArrayUtil.shiftBackward(text, offset, whitespaceChars) + 1; + int whitespaceEnd = CharArrayUtil.shiftForward(text, offset, whitespaceChars); + List inlays = myEditor.getInlayModel().getInlineElementsInRange(whitespaceStart, whitespaceEnd); + for (Inlay inlay : inlays) { + if (ParameterHintsPresentationManager.getInstance().isParameterHint(inlay)) return inlay.getOffset(); + } + return offset; + } + private int getPrevOrNextParameterOffset(boolean isNext) { if (!(myHandler instanceof ParameterInfoHandlerWithTabActionSupport)) return -1; ParameterInfoHandlerWithTabActionSupport handler = (ParameterInfoHandlerWithTabActionSupport)myHandler; @@ -338,7 +411,93 @@ public class ParameterInfoController implements Disposable { return null; } - private class MyUpdateParameterInfoContext implements UpdateParameterInfoContext { + public Object[] getObjects() { + return myComponent.getObjects(); + } + + public Object getHighlighted() { + return myComponent.getHighlighted(); + } + + @TestOnly + public static void waitForDelayedActions(@NotNull Editor editor, long timeout, @NotNull TimeUnit unit) throws TimeoutException { + long deadline = System.currentTimeMillis() + unit.toMillis(timeout); + while (System.currentTimeMillis() < deadline) { + List controllers = getAllControllers(editor); + boolean hasPendingRequests = false; + for (ParameterInfoController controller : controllers) { + if (!controller.myAlarm.isEmpty()) { + hasPendingRequests = true; + break; + } + } + if (hasPendingRequests) UIUtil.dispatchAllInvocationEvents(); + else return; + } + throw new TimeoutException(); + } + + /** + * @return Point in layered pane coordinate system + */ + static Pair chooseBestHintPosition(Project project, + Editor editor, + LogicalPosition pos, + LightweightHint hint, + boolean awtTooltip, short preferredPosition) { + if (ApplicationManager.getApplication().isUnitTestMode()) return Pair.pair(new Point(), HintManager.DEFAULT); + + HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); + Dimension hintSize = hint.getComponent().getPreferredSize(); + JComponent editorComponent = editor.getComponent(); + JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane(); + + Point p1; + Point p2; + boolean isLookupShown = LookupManager.getInstance(project).getActiveLookup() != null; + if (isLookupShown) { + p1 = hintManager.getHintPosition(hint, editor, HintManager.UNDER); + p2 = hintManager.getHintPosition(hint, editor, HintManager.ABOVE); + } + else { + p1 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.UNDER); + p2 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.ABOVE); + } + + if (!awtTooltip) { + p1.x = Math.min(p1.x, layeredPane.getWidth() - hintSize.width); + p1.x = Math.max(p1.x, 0); + p2.x = Math.min(p2.x, layeredPane.getWidth() - hintSize.width); + p2.x = Math.max(p2.x, 0); + } + + boolean p1Ok = p1.y + hintSize.height < layeredPane.getHeight(); + boolean p2Ok = p2.y >= 0; + + if (isLookupShown) { + if (p1Ok) return new Pair<>(p1, HintManager.UNDER); + if (p2Ok) return new Pair<>(p2, HintManager.ABOVE); + } + else { + if (preferredPosition != HintManager.DEFAULT) { + if (preferredPosition == HintManager.ABOVE) { + if (p2Ok) return new Pair<>(p2, HintManager.ABOVE); + } else if (preferredPosition == HintManager.UNDER) { + if (p1Ok) return new Pair<>(p1, HintManager.UNDER); + } + } + + if (p1Ok) return new Pair<>(p1, HintManager.UNDER); + if (p2Ok) return new Pair<>(p2, HintManager.ABOVE); + } + + int underSpace = layeredPane.getHeight() - p1.y; + int aboveSpace = p2.y; + return aboveSpace > underSpace ? new Pair<>(new Point(p2.x, 0), HintManager.UNDER) : new Pair<>(p1, + HintManager.ABOVE); + } + + public class MyUpdateParameterInfoContext implements UpdateParameterInfoContext { private final int myOffset; private final PsiFile myFile; @@ -415,4 +574,46 @@ public class ParameterInfoController implements Disposable { } } + + private static class MyBestLocationPointProvider { + private final Editor myEditor; + private int previousOffset = -1; + private Point previousBestPoint; + private Short previousBestPosition; + + public MyBestLocationPointProvider(final Editor editor) { + myEditor = editor; + } + + @NotNull + public Pair getBestPointPosition(LightweightHint hint, + final PsiElement list, + int offset, + final boolean awtTooltip, + short preferredPosition) { + if (list != null) { + TextRange range = list.getTextRange(); + if (!range.contains(offset)) { + offset = range.getStartOffset() + 1; + } + } + if (previousOffset == offset) return Pair.create(previousBestPoint, previousBestPosition); + + final boolean isMultiline = list != null && StringUtil.containsAnyChar(list.getText(), "\n\r"); + final LogicalPosition pos = myEditor.offsetToLogicalPosition(offset).leanForward(true); + Pair position; + + if (!isMultiline) { + position = chooseBestHintPosition(myEditor.getProject(), myEditor, pos, hint, awtTooltip, preferredPosition); + } + else { + Point p = HintManagerImpl.getHintPosition(hint, myEditor, pos, HintManager.ABOVE); + position = new Pair<>(p, HintManager.ABOVE); + } + previousBestPoint = position.getFirst(); + previousBestPosition = position.getSecond(); + previousOffset = offset; + return position; + } + } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/PrevNextParameterHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/PrevNextParameterHandler.java index da5f8b1554d5..30e686ff0c35 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/PrevNextParameterHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/PrevNextParameterHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2017 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. @@ -40,7 +40,7 @@ public class PrevNextParameterHandler extends EditorActionHandler { @Override protected boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { - if (!ParameterInfoController.isShownForEditor(editor)) return false; + if (!ParameterInfoController.existsForEditor(editor)) return false; Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) return false; @@ -49,7 +49,7 @@ public class PrevNextParameterHandler extends EditorActionHandler { if (exprList == null) return false; int lbraceOffset = exprList.getTextRange().getStartOffset(); - return ParameterInfoController.isAlreadyShown(editor, lbraceOffset) && + return ParameterInfoController.findControllerAtOffset(editor, lbraceOffset) != null && ParameterInfoController.hasPrevOrNextParameter(editor, lbraceOffset, myIsNextParameterHandler); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoContext.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoContext.java index 624103856dfb..421b536819e1 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoContext.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2017 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,29 +15,18 @@ */ package com.intellij.codeInsight.hint; -import com.intellij.codeInsight.lookup.LookupManager; -import com.intellij.injected.editor.EditorWindow; import com.intellij.lang.parameterInfo.CreateParameterInfoContext; import com.intellij.lang.parameterInfo.ParameterInfoHandler; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.TextRange; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; -import com.intellij.ui.HintHint; -import com.intellij.ui.LightweightHint; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.swing.*; -import java.awt.*; - /** * @author peter */ @@ -131,20 +120,6 @@ public class ShowParameterInfoContext implements CreateParameterInfoContext { if (ParameterInfoController.isAlreadyShown(editor, elementStart)) return; if (editor.isDisposed() || !editor.getComponent().isVisible()) return; - final ParameterInfoComponent component = new ParameterInfoComponent(descriptors, editor,handler,requestFocus); - component.setParameterOwner(element); - component.setRequestFocus(requestFocus); - if (highlighted != null) { - component.setHighlightedParameter(highlighted); - } - - component.update(); // to have correct preferred size - - final LightweightHint hint = new LightweightHint(component); - hint.setSelectingHint(true); - final HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); - final ShowParameterInfoHandler.BestLocationPointProvider provider = new MyBestLocationPointProvider(editor); - final Pair pos = provider.getBestPointPosition(hint, element, elementStart, true, HintManager.UNDER); PsiDocumentManager.getInstance(project).performLaterWhenAllCommitted(() -> { if (editor.isDisposed() || DumbService.isDumb(project)) return; @@ -152,15 +127,13 @@ public class ShowParameterInfoContext implements CreateParameterInfoContext { final Document document = editor.getDocument(); if (document.getTextLength() < elementStart) return; - HintHint hintHint = HintManagerImpl.createHintHint(editor, pos.getFirst(), hint, pos.getSecond()); - hintHint.setExplicitClose(true); - hintHint.setRequestFocus(requestFocus); - - Editor editorToShow = editor instanceof EditorWindow ? ((EditorWindow)editor).getDelegate() : editor; - // is case of injection we need to calculate position for EditorWindow - // also we need to show the hint in the main editor because of intention bulb - hintManager.showEditorHint(hint, editorToShow, pos.getFirst(), HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false, hintHint); - new ParameterInfoController(project, editor, elementStart, hint, handler, provider); + ParameterInfoController controller = ParameterInfoController.findControllerAtOffset(editor, elementStart); + if (controller == null) { + new ParameterInfoController(project, editor, elementStart, descriptors, highlighted, element, handler, true, requestFocus); + } + else { + controller.showHint(requestFocus); + } }); } @@ -175,66 +148,6 @@ public class ShowParameterInfoContext implements CreateParameterInfoContext { showParameterHint(list, editor, candidates, project, candidates.length > 1 ? highlighted : null, offset, handler, requestFocus); } - /** - * @return Point in layered pane coordinate system - */ - static Pair chooseBestHintPosition(Project project, - Editor editor, - int line, - int col, - LightweightHint hint, - boolean awtTooltip, short preferredPosition) { - HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); - Dimension hintSize = hint.getComponent().getPreferredSize(); - JComponent editorComponent = editor.getComponent(); - JLayeredPane layeredPane = editorComponent.getRootPane().getLayeredPane(); - - Point p1; - Point p2; - boolean isLookupShown = LookupManager.getInstance(project).getActiveLookup() != null; - if (isLookupShown) { - p1 = hintManager.getHintPosition(hint, editor, HintManager.UNDER); - p2 = hintManager.getHintPosition(hint, editor, HintManager.ABOVE); - } - else { - LogicalPosition pos = new LogicalPosition(line, col); - p1 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.UNDER); - p2 = HintManagerImpl.getHintPosition(hint, editor, pos, HintManager.ABOVE); - } - - if (!awtTooltip) { - p1.x = Math.min(p1.x, layeredPane.getWidth() - hintSize.width); - p1.x = Math.max(p1.x, 0); - p2.x = Math.min(p2.x, layeredPane.getWidth() - hintSize.width); - p2.x = Math.max(p2.x, 0); - } - - boolean p1Ok = p1.y + hintSize.height < layeredPane.getHeight(); - boolean p2Ok = p2.y >= 0; - - if (isLookupShown) { - if (p1Ok) return new Pair<>(p1, HintManager.UNDER); - if (p2Ok) return new Pair<>(p2, HintManager.ABOVE); - } - else { - if (preferredPosition != HintManager.DEFAULT) { - if (preferredPosition == HintManager.ABOVE) { - if (p2Ok) return new Pair<>(p2, HintManager.ABOVE); - } else if (preferredPosition == HintManager.UNDER) { - if (p1Ok) return new Pair<>(p1, HintManager.UNDER); - } - } - - if (p1Ok) return new Pair<>(p1, HintManager.UNDER); - if (p2Ok) return new Pair<>(p2, HintManager.ABOVE); - } - - int underSpace = layeredPane.getHeight() - p1.y; - int aboveSpace = p2.y; - return aboveSpace > underSpace ? new Pair<>(new Point(p2.x, 0), HintManager.UNDER) : new Pair<>(p1, - HintManager.ABOVE); - } - public void setRequestFocus(boolean requestFocus) { myRequestFocus = requestFocus; } @@ -242,47 +155,4 @@ public class ShowParameterInfoContext implements CreateParameterInfoContext { public boolean isRequestFocus() { return myRequestFocus; } - - static class MyBestLocationPointProvider implements ShowParameterInfoHandler.BestLocationPointProvider { - private final Editor myEditor; - private int previousOffset = -1; - private Point previousBestPoint; - private Short previousBestPosition; - - public MyBestLocationPointProvider(final Editor editor) { - myEditor = editor; - } - - @Override - @NotNull - public Pair getBestPointPosition(LightweightHint hint, - final PsiElement list, - int offset, - final boolean awtTooltip, - short preferredPosition) { - if (list != null) { - TextRange range = list.getTextRange(); - if (!range.contains(offset)) { - offset = range.getStartOffset() + 1; - } - } - if (previousOffset == offset) return Pair.create(previousBestPoint, previousBestPosition); - - final boolean isMultiline = list != null && StringUtil.containsAnyChar(list.getText(), "\n\r"); - final LogicalPosition pos = myEditor.offsetToLogicalPosition(offset); - Pair position; - - if (!isMultiline) { - position = chooseBestHintPosition(myEditor.getProject(), myEditor, pos.line, pos.column, hint, awtTooltip, preferredPosition); - } - else { - Point p = HintManagerImpl.getHintPosition(hint, myEditor, pos, HintManager.ABOVE); - position = new Pair<>(p, HintManager.ABOVE); - } - previousBestPoint = position.getFirst(); - previousBestPosition = position.getSecond(); - previousOffset = offset; - return position; - } - } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java index 99e514bbe09c..33df15faee48 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ShowParameterInfoHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 JetBrains s.r.o. + * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -142,7 +142,7 @@ public class ShowParameterInfoHandler implements CodeInsightActionHandler { final LightweightHint hint = new LightweightHint(component); hint.setSelectingHint(true); final HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl(); - final Pair pos = ShowParameterInfoContext.chooseBestHintPosition(project, editor, -1, -1, hint, true, HintManager.DEFAULT); + final Pair pos = ParameterInfoController.chooseBestHintPosition(project, editor, null, hint, true, HintManager.DEFAULT); ApplicationManager.getApplication().invokeLater(() -> { if (!editor.getComponent().isShowing()) return; hintManager.showEditorHint(hint, editor, pos.getFirst(), @@ -160,15 +160,5 @@ public class ShowParameterInfoHandler implements CodeInsightActionHandler { if (handlers.isEmpty()) return null; return handlers.toArray(new ParameterInfoHandler[handlers.size()]); } - - interface BestLocationPointProvider { - @NotNull - Pair getBestPointPosition(LightweightHint hint, - final PsiElement list, - int offset, - final boolean awtTooltip, - short preferredPosition); - } - } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hints/ParameterHintsPassFactory.java b/platform/lang-impl/src/com/intellij/codeInsight/hints/ParameterHintsPassFactory.java index a98ddb0eb360..aca1d04682fc 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hints/ParameterHintsPassFactory.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hints/ParameterHintsPassFactory.java @@ -146,7 +146,7 @@ public class ParameterHintsPassFactory extends AbstractProjectComponent implemen String newText = myAnnotations.remove(offset); String oldText = presentationManager.getHintText(inlay); - if (delayRemoval(inlay, caretMap)) continue; + if (delayRemoval(inlay, caretMap) || presentationManager.isPinned(inlay)) continue; if (!Objects.equals(newText, oldText)) { if (newText == null) { removedHints.add(oldText); @@ -160,7 +160,7 @@ public class ParameterHintsPassFactory extends AbstractProjectComponent implemen for (Map.Entry e : myAnnotations.entrySet()) { int offset = e.getKey(); String text = e.getValue(); - presentationManager.addHint(myEditor, offset, text, !firstTime && !removedHints.contains(text)); + presentationManager.addHint(myEditor, offset, text, !firstTime && !removedHints.contains(text), false); } keeper.restoreOriginalLocation(); myEditor.putUserData(REPEATED_PASS, Boolean.TRUE); diff --git a/platform/lvcs-impl/src/com/intellij/openapi/command/impl/FileUndoProvider.java b/platform/lvcs-impl/src/com/intellij/openapi/command/impl/FileUndoProvider.java index d7916a7493d1..a1083c00d80b 100644 --- a/platform/lvcs-impl/src/com/intellij/openapi/command/impl/FileUndoProvider.java +++ b/platform/lvcs-impl/src/com/intellij/openapi/command/impl/FileUndoProvider.java @@ -46,13 +46,13 @@ public class FileUndoProvider extends VirtualFileAdapter implements UndoProvider private long myLastChangeId; - @SuppressWarnings({"UnusedDeclaration"}) + @SuppressWarnings("UnusedDeclaration") public FileUndoProvider() { this(null); } - public FileUndoProvider(Project project) { - myProject = project; + private FileUndoProvider(Project project) { + myProject = project; if (myProject == null) return; LocalHistoryImpl localHistory = LocalHistoryImpl.getInstanceImpl(); @@ -99,7 +99,7 @@ public class FileUndoProvider extends VirtualFileAdapter implements UndoProvider } private void processEvent(VirtualFileEvent e) { - if (shouldNotProcess(e)) return; + if (!shouldProcess(e)) return; if (isUndoable(e)) { registerUndoableAction(e); } @@ -110,14 +110,14 @@ public class FileUndoProvider extends VirtualFileAdapter implements UndoProvider @Override public void beforeContentsChange(@NotNull VirtualFileEvent e) { - if (shouldNotProcess(e)) return; + if (!shouldProcess(e)) return; if (isUndoable(e)) return; registerNonUndoableAction(e); } @Override public void beforeFileDeletion(@NotNull VirtualFileEvent e) { - if (shouldNotProcess(e)) { + if (!shouldProcess(e)) { invalidateActionsFor(e); return; } @@ -132,6 +132,7 @@ public class FileUndoProvider extends VirtualFileAdapter implements UndoProvider @Override public void fileDeleted(@NotNull VirtualFileEvent e) { + if (!shouldProcess(e)) return; VirtualFile f = e.getFile(); DocumentReference ref = f.getUserData(DELETION_WAS_UNDOABLE); @@ -141,13 +142,11 @@ public class FileUndoProvider extends VirtualFileAdapter implements UndoProvider } } - private boolean shouldNotProcess(VirtualFileEvent e) { - return isProjectClosed() || !LocalHistory.getInstance().isUnderControl(e.getFile()) || !myIsInsideCommand - || FileContentUtilCore.FORCE_RELOAD_REQUESTOR.equals(e.getRequestor()); - } - - private boolean isProjectClosed() { - return myProject.isDisposed(); + private boolean shouldProcess(VirtualFileEvent e) { + return !myProject.isDisposed() && + LocalHistory.getInstance().isUnderControl(e.getFile()) && + myIsInsideCommand && + !FileContentUtilCore.FORCE_RELOAD_REQUESTOR.equals(e.getRequestor()); } private static boolean isUndoable(VirtualFileEvent e) { @@ -167,7 +166,9 @@ public class FileUndoProvider extends VirtualFileAdapter implements UndoProvider } private void invalidateActionsFor(VirtualFileEvent e) { - getUndoManager().invalidateActionsFor(createDocumentReference(e)); + if (myProject == null || !myProject.isDisposed()) { + getUndoManager().invalidateActionsFor(createDocumentReference(e)); + } } private static DocumentReference createDocumentReference(VirtualFileEvent e) { @@ -185,7 +186,7 @@ public class FileUndoProvider extends VirtualFileAdapter implements UndoProvider private ChangeRange myActionChangeRange; private ChangeRange myUndoChangeRange; - public MyUndoableAction(DocumentReference r) { + MyUndoableAction(DocumentReference r) { super(r); myActionChangeRange = new ChangeRange(myGateway, myLocalHistory, myLastChangeId); } diff --git a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java index 49f54b5f47e6..bcb0c16df896 100644 --- a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java +++ b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizardStepEx.java @@ -18,6 +18,7 @@ package com.intellij.ide.wizard; import com.intellij.openapi.Disposable; import com.intellij.util.EventDispatcher; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -97,6 +98,7 @@ public abstract class AbstractWizardStepEx implements Step, Disposable { @Nullable public abstract JComponent getPreferredFocusedComponent(); + @NonNls public String getHelpId() { return null; } 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 55b8b3f8dd0e..c16a7ac8d0f4 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java @@ -1526,7 +1526,7 @@ public abstract class DialogWrapper { /** * @return the help identifier or null if no help is available. */ - @Nullable + @Nullable @NonNls protected String getHelpId() { return null; } diff --git a/platform/platform-impl/src/com/intellij/codeInsight/hint/HintManagerImpl.java b/platform/platform-impl/src/com/intellij/codeInsight/hint/HintManagerImpl.java index 35ee1af03c91..db9be510e1f5 100644 --- a/platform/platform-impl/src/com/intellij/codeInsight/hint/HintManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/codeInsight/hint/HintManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 JetBrains s.r.o. + * Copyright 2000-2017 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. @@ -654,23 +654,19 @@ public class HintManagerImpl extends HintManager implements Disposable { @PositionFlags short constraint, boolean showByBalloon) { Dimension hintSize = hint.getComponent().getPreferredSize(); - int line1 = pos1.line; - int col1 = pos1.column; - int line2 = pos2.line; - int col2 = pos2.column; Point location; JComponent externalComponent = getExternalComponent(editor); JComponent internalComponent = editor.getContentComponent(); if (constraint == RIGHT_UNDER) { - Point p = editor.logicalPositionToXY(new LogicalPosition(line2, col2)); + Point p = editor.logicalPositionToXY(pos2); if (!showByBalloon) { p.y += editor.getLineHeight(); } location = SwingUtilities.convertPoint(internalComponent, p, externalComponent); } else { - Point p = editor.logicalPositionToXY(new LogicalPosition(line1, col1)); + Point p = editor.logicalPositionToXY(pos1); if (constraint == UNDER) { p.y += editor.getLineHeight(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/application/impl/LaterInvocator.java b/platform/platform-impl/src/com/intellij/openapi/application/impl/LaterInvocator.java index 4de7628f1e76..0ffcf398c708 100644 --- a/platform/platform-impl/src/com/intellij/openapi/application/impl/LaterInvocator.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/impl/LaterInvocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 JetBrains s.r.o. + * Copyright 2000-2017 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. @@ -36,10 +36,7 @@ import com.intellij.util.containers.Stack; import com.intellij.util.containers.WeakHashMap; import com.intellij.util.ui.UIUtil; import io.netty.util.internal.SystemPropertyUtil; -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 javax.swing.*; import java.awt.*; @@ -63,6 +60,7 @@ public class LaterInvocator { @NotNull private final Condition expired; @NotNull private final ActionCallback callback; + @Debugger.Capture RunnableInfo(@NotNull Runnable runnable, @NotNull ModalityState modalityState, @NotNull Condition expired, @@ -401,6 +399,7 @@ public class LaterInvocator { } } + @Debugger.Insert(keyExpression = "lastInfo") private boolean runNextEvent() { final RunnableInfo lastInfo = getNextEvent(true); myLastInfo = lastInfo; diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentUndoProvider.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentUndoProvider.java index 6fa97f85d663..1a5025fb356d 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentUndoProvider.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/DocumentUndoProvider.java @@ -62,7 +62,7 @@ public class DocumentUndoProvider implements Disposable { @Override public void beforeDocumentChange(DocumentEvent e) { Document document = e.getDocument(); - if (shouldBeIgnored(document)) return; + if (!shouldProcess(document)) return; UndoManagerImpl undoManager = getUndoManager(); if (undoManager.isActive() && isUndoable(document) && (undoManager.isUndoInProgress() || undoManager.isRedoInProgress()) && @@ -74,7 +74,7 @@ public class DocumentUndoProvider implements Disposable { @Override public void documentChanged(final DocumentEvent e) { Document document = e.getDocument(); - if (shouldBeIgnored(document)) return; + if (!shouldProcess(document)) return; UndoManagerImpl undoManager = getUndoManager(); if (undoManager.isActive() && isUndoable(document)) { @@ -85,11 +85,12 @@ public class DocumentUndoProvider implements Disposable { } } - private boolean shouldBeIgnored(Document document) { - return UndoManagerImpl.isCopy(document) // if we don't ignore copy's events, we will receive notification - // for the same event twice (from original document too) - // and undo will work incorrectly - || !shouldRecordActions(document); + private boolean shouldProcess(Document document) { + if (myProject != null && myProject.isDisposed()) return false; + return !UndoManagerImpl.isCopy(document) // if we don't ignore copy's events, we will receive notification + // for the same event twice (from original document too) + // and undo will work incorrectly + && shouldRecordActions(document); } private boolean shouldRecordActions(final Document document) { @@ -116,11 +117,7 @@ public class DocumentUndoProvider implements Disposable { if (file != null && file.getUserData(UndoConstants.FORCE_RECORD_UNDO) == Boolean.TRUE) { return true; } - else { - if (!UndoManagerImpl.isRefresh()) return true; - } - - return getUndoManager().isUndoOrRedoAvailable(ref); + return !UndoManagerImpl.isRefresh() || getUndoManager().isUndoOrRedoAvailable(ref); } } } diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoManagerImpl.java index 0cca606de483..b1e02f76f0d9 100644 --- a/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/UndoManagerImpl.java @@ -79,10 +79,8 @@ public class UndoManagerImpl extends UndoManager implements Disposable { private int myCommandTimestamp = 1; private int myCommandLevel; - private static final int NONE = 0; - private static final int UNDO = 1; - private static final int REDO = 2; - private int myCurrentOperationState = NONE; + private enum OperationState { NONE, UNDO, REDO } + private OperationState myCurrentOperationState = OperationState.NONE; private DocumentReference myOriginatorReference; @@ -129,16 +127,19 @@ public class UndoManagerImpl extends UndoManager implements Disposable { @Override public void commandStarted(CommandEvent event) { + if (myProject != null && myProject.isDisposed()) return; onCommandStarted(event.getProject(), event.getUndoConfirmationPolicy(), event.shouldRecordActionForOriginalDocument()); } @Override public void commandFinished(CommandEvent event) { + if (myProject != null && myProject.isDisposed()) return; onCommandFinished(event.getProject(), event.getCommandName(), event.getCommandGroupId()); } @Override public void undoTransparentActionStarted() { + if (myProject != null && myProject.isDisposed()) return; if (!isInsideCommand()) { myStarted = true; onCommandStarted(myProject, UndoConfirmationPolicy.DEFAULT, true); @@ -147,6 +148,7 @@ public class UndoManagerImpl extends UndoManager implements Disposable { @Override public void undoTransparentActionFinished() { + if (myProject != null && myProject.isDisposed()) return; if (myStarted) { myStarted = false; onCommandFinished(myProject, "", null); @@ -277,14 +279,16 @@ public class UndoManagerImpl extends UndoManager implements Disposable { @Override public void nonundoableActionPerformed(@NotNull final DocumentReference ref, final boolean isGlobal) { ApplicationManager.getApplication().assertIsDispatchThread(); + if (myProject != null && myProject.isDisposed()) return; undoableActionPerformed(new NonUndoableAction(ref, isGlobal)); } @Override public void undoableActionPerformed(@NotNull UndoableAction action) { ApplicationManager.getApplication().assertIsDispatchThread(); + if (myProject != null && myProject.isDisposed()) return; - if (myCurrentOperationState != NONE) return; + if (myCurrentOperationState != OperationState.NONE) return; if (myCommandLevel == 0) { LOG.assertTrue(action instanceof NonUndoableAction, @@ -355,7 +359,7 @@ public class UndoManagerImpl extends UndoManager implements Disposable { } private void undoOrRedo(final FileEditor editor, final boolean isUndo) { - myCurrentOperationState = isUndo ? UNDO : REDO; + myCurrentOperationState = isUndo ? OperationState.UNDO : OperationState.REDO; final RuntimeException[] exception = new RuntimeException[1]; Runnable executeUndoOrRedoAction = () -> { @@ -370,7 +374,7 @@ public class UndoManagerImpl extends UndoManager implements Disposable { exception[0] = ex; } finally { - myCurrentOperationState = NONE; + myCurrentOperationState = OperationState.NONE; } }; @@ -382,12 +386,12 @@ public class UndoManagerImpl extends UndoManager implements Disposable { @Override public boolean isUndoInProgress() { - return myCurrentOperationState == UNDO; + return myCurrentOperationState == OperationState.UNDO; } @Override public boolean isRedoInProgress() { - return myCurrentOperationState == REDO; + return myCurrentOperationState == OperationState.REDO; } @Override @@ -518,7 +522,7 @@ public class UndoManagerImpl extends UndoManager implements Disposable { } protected void compact() { - if (myCurrentOperationState == NONE && myCommandTimestamp % COMMAND_TO_RUN_COMPACT == 0) { + if (myCurrentOperationState == OperationState.NONE && myCommandTimestamp % COMMAND_TO_RUN_COMPACT == 0) { doCompact(); } } @@ -597,6 +601,7 @@ public class UndoManagerImpl extends UndoManager implements Disposable { @TestOnly private void flushMergers() { + assert myProject == null || !myProject.isDisposed(); // Run dummy command in order to flush all mergers... CommandProcessor.getInstance().executeCommand(myProject, EmptyRunnable.getInstance(), CommonBundle.message("drop.undo.history.command.name"), null); } diff --git a/platform/platform-impl/src/com/intellij/platform/WebProjectGenerator.java b/platform/platform-impl/src/com/intellij/platform/WebProjectGenerator.java index 5d63c6186f12..6a73e01a794c 100644 --- a/platform/platform-impl/src/com/intellij/platform/WebProjectGenerator.java +++ b/platform/platform-impl/src/com/intellij/platform/WebProjectGenerator.java @@ -22,6 +22,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -47,7 +48,7 @@ public abstract class WebProjectGenerator implements DirectoryProjectGenerato return null; } - @Nullable + @Nullable @NonNls public String getHelpId() { return null; } diff --git a/platform/platform-impl/src/com/intellij/ui/wizard/WizardStep.java b/platform/platform-impl/src/com/intellij/ui/wizard/WizardStep.java index 42c32e0ec70f..4bc09a1516a0 100644 --- a/platform/platform-impl/src/com/intellij/ui/wizard/WizardStep.java +++ b/platform/platform-impl/src/com/intellij/ui/wizard/WizardStep.java @@ -15,6 +15,7 @@ */ package com.intellij.ui.wizard; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -48,7 +49,7 @@ public abstract class WizardStep { myIcon = icon; } - public WizardStep(String title, String explanation, Icon icon, String helpId) { + public WizardStep(String title, String explanation, Icon icon, @NonNls String helpId) { myTitle = title; myExplanation = explanation; myIcon = icon; @@ -90,6 +91,7 @@ public abstract class WizardStep { return myIcon; } + @NonNls public String getHelpId() { return myHelpId; } diff --git a/platform/platform-resources-en/src/messages/ActionsBundle.properties b/platform/platform-resources-en/src/messages/ActionsBundle.properties index 138dda07bfc7..ff1e6554cb6b 100644 --- a/platform/platform-resources-en/src/messages/ActionsBundle.properties +++ b/platform/platform-resources-en/src/messages/ActionsBundle.properties @@ -1578,4 +1578,7 @@ action.ToggleDistractionFreeMode.exit=Exit Distraction Free Mode action.TogglePresentationMode.exit=Exit Presentation Mode action.TogglePresentationMode.enter=Enter Presentation Mode -action.EmojiAndSymbols.description=Input special characters using macOS system palette \ No newline at end of file +action.EmojiAndSymbols.description=Input special characters using macOS system palette + +action.MethodOverloadSwitchUp.text=Previous Method Overload +action.MethodOverloadSwitchDown.text=Next Method Overload \ No newline at end of file diff --git a/platform/platform-resources/src/keymaps/$default.xml b/platform/platform-resources/src/keymaps/$default.xml index ca88b59a9742..a00d6a63132d 100644 --- a/platform/platform-resources/src/keymaps/$default.xml +++ b/platform/platform-resources/src/keymaps/$default.xml @@ -80,6 +80,9 @@ + + + diff --git a/platform/testFramework/extensions/src/com/intellij/keymap/KeymapsTestCase.java b/platform/testFramework/extensions/src/com/intellij/keymap/KeymapsTestCase.java index 802d1d66e31f..19f6db8ee1c2 100644 --- a/platform/testFramework/extensions/src/com/intellij/keymap/KeymapsTestCase.java +++ b/platform/testFramework/extensions/src/com/intellij/keymap/KeymapsTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2016 JetBrains s.r.o. + * Copyright 2000-2017 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. @@ -94,7 +94,7 @@ public abstract class KeymapsTestCase extends PlatformTestCase { { "control 3", "GotoBookmark3", "FileChooser.GotoModule"}, { "control ADD", "ExpandAll", "ExpandRegion"}, { "control DIVIDE", "CommentByLineComment", "Images.Editor.ActualSize"}, - { "control DOWN", "EditorScrollDown", "EditorLookupDown"}, + { "control DOWN", "EditorScrollDown", "EditorLookupDown", "MethodOverloadSwitchDown"}, { "control ENTER", "EditorSplitLine", "ViewSource", "Console.Execute.Multiline"}, { "control EQUALS", "ExpandAll", "ExpandRegion"}, { "control F5", "Refresh", "Rerun"}, @@ -106,7 +106,7 @@ public abstract class KeymapsTestCase extends PlatformTestCase { { "control R", "Replace", "Console.TableResult.Reload", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"}, { "control SLASH", "CommentByLineComment", "Images.Editor.ActualSize"}, { "control U", "GotoSuperMethod", "CommanderSwapPanels"}, - { "control UP", "EditorScrollUp", "EditorLookupUp"}, + { "control UP", "EditorScrollUp", "EditorLookupUp", "MethodOverloadSwitchUp"}, { "control alt A", "ChangesView.AddUnversioned", "Diagram.DeselectAll"}, { "control alt E", "PerforceDirect.Edit", "Console.History.Browse"}, { "control alt DOWN", "NextOccurence", "Console.TableResult.NextPage"}, @@ -162,6 +162,8 @@ public abstract class KeymapsTestCase extends PlatformTestCase { { "meta 3", "ActivateFindToolWindow", "FileChooser.GotoModule"}, { "meta N", "FileChooser.NewFolder", "Generate", "NewElement"}, { "meta O", "GotoClass", "GotoChangedFile"}, + { "meta UP", "ShowNavBar", "MethodOverloadSwitchUp"}, + { "meta DOWN", "EditSource", "MethodOverloadSwitchDown"}, { "shift meta G", "ClassTemplateNavigation", "GoToClass", "FindPrevious"}, { "shift meta LEFT", "EditorLineStartWithSelection", "ResizeToolWindowLeft", }, { "shift meta RIGHT", "EditorLineEndWithSelection", "ResizeToolWindowRight", }, @@ -211,8 +213,8 @@ public abstract class KeymapsTestCase extends PlatformTestCase { { "control X", "GotoFile", "SaveAll", "NextTab", "PreviousTab", "CloseContent", "CloseAllEditors", "NextSplitter", "GotoNextError", "NextProjectWindow", "EditorSwapSelectionBoundaries", "SplitVertically", "SplitHorizontally", "UnsplitAll", "Switcher", "$SelectAll"}, - { "control UP", "EditorBackwardParagraph", "EditorLookupUp"}, - { "control DOWN", "EditorForwardParagraph", "EditorLookupDown"}, + { "control UP", "EditorBackwardParagraph", "EditorLookupUp", "MethodOverloadSwitchUp"}, + { "control DOWN", "EditorForwardParagraph", "EditorLookupDown", "MethodOverloadSwitchDown"}, { "control alt A", "MethodUp", "ChangesView.AddUnversioned", "Diagram.DeselectAll"}, { "control alt E", "MethodDown", "PerforceDirect.Edit", "Console.History.Browse"}, { "control alt G", "GotoDeclaration", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction", "Mvc.RunTarget"}, diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java index e29a5dcf0d1e..ea62ba05ca2b 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java @@ -423,10 +423,10 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da append(() -> ((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests()). append(() -> ((DocumentReferenceManagerImpl)DocumentReferenceManager.getInstance()).cleanupForNextTest()). append(() -> TemplateDataLanguageMappings.getInstance(project).cleanupForNextTest()). + append(() -> ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest()). append(() -> ProjectManagerEx.getInstanceEx().closeTestProject(project)). append(() -> application.setDataProvider(null)). append(() -> ourTestCase = null). - append(() -> ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest()). append(() -> CompletionProgressIndicator.cleanupForNextTest()). append(() -> UIUtil.dispatchAllInvocationEvents()). append(() -> { diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestFixture.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestFixture.java index e06f47071a97..fb0c476546b2 100644 --- a/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestFixture.java +++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestFixture.java @@ -542,6 +542,8 @@ public interface CodeInsightTestFixture extends IdeaProjectTestFixture { void testInlays(); + void checkResultWithInlays(String text); + void assertPreferredCompletionItems(int selected, @NotNull String... expected); /** diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java index bbb4a31feef7..d21b2136fcc0 100644 --- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java +++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java @@ -27,6 +27,7 @@ import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.codeInsight.daemon.impl.*; import com.intellij.codeInsight.folding.CodeFoldingManager; import com.intellij.codeInsight.highlighting.actions.HighlightUsagesAction; +import com.intellij.codeInsight.hints.InlayInfo; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.impl.IntentionListStep; import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler; @@ -1705,6 +1706,15 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig } } + @Override + public void checkResultWithInlays(String text) { + Document checkDocument = new DocumentImpl(text); + InlayHintsChecker checker = new InlayHintsChecker(this); + List inlayInfos = checker.extractInlays(checkDocument); + checkResult(checkDocument.getText()); + checker.verifyInlays(inlayInfos, text); + } + @Override public void assertPreferredCompletionItems(final int selected, @NotNull final String... expected) { final LookupImpl lookup = getLookup(); diff --git a/platform/testFramework/src/com/intellij/testFramework/utils/inlays/InlayParameterHintsTest.kt b/platform/testFramework/src/com/intellij/testFramework/utils/inlays/InlayParameterHintsTest.kt index c6516436d310..12630cde0fbd 100644 --- a/platform/testFramework/src/com/intellij/testFramework/utils/inlays/InlayParameterHintsTest.kt +++ b/platform/testFramework/src/com/intellij/testFramework/utils/inlays/InlayParameterHintsTest.kt @@ -17,7 +17,6 @@ package com.intellij.testFramework.utils.inlays import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.InlayInfo -import com.intellij.codeInsight.hints.InlayParameterHintsExtension import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Document @@ -57,10 +56,17 @@ class InlayHintsChecker(private val myFixture: CodeInsightTestFixture) { val document = myFixture.getDocument(file) val originalText = document.text val expectedInlays: List = extractInlays(document) + myFixture.doHighlighting(); + verifyInlays(expectedInlays, originalText) + } + + fun verifyInlays(expectedInlays : List, originalText: String) { + val file = myFixture.file + val document = myFixture.getDocument(file) val actual: List> = getActualInlays() - + val expected = expectedInlays.map { Pair(it.offset, it.text) } - + if (expectedInlays.size != actual.size || actual.zip(expected).any { it.first != it.second }) { val proposedText = StringBuilder(document.text) actual.asReversed().forEach { proposedText.insert(it.first, "") } @@ -70,9 +76,8 @@ class InlayHintsChecker(private val myFixture: CodeInsightTestFixture) { } ?: throw ComparisonFailure("Hints differ", originalText, proposedText.toString()) } } - + private fun getActualInlays(): List> { - myFixture.doHighlighting() val editor = myFixture.editor val allInlays = editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength) diff --git a/platform/util/resources/misc/registry.properties b/platform/util/resources/misc/registry.properties index 9496b715965f..befc90c5ae50 100644 --- a/platform/util/resources/misc/registry.properties +++ b/platform/util/resources/misc/registry.properties @@ -259,6 +259,7 @@ debugger.emulate.method.breakpoints.description=Emulate method breakpoints with debugger.intern.string.literals=false debugger.intern.string.literals.description=Make string literal refer to the same instance of class String debugger.capture.points=true +debugger.capture.points.annotations=false analyze.exceptions.on.the.fly=false analyze.exceptions.on.the.fly.description=Automatically analyze clipboard on frame activation,\ @@ -369,6 +370,9 @@ show.live.templates.in.completion.description=Show live templates in completion java.completion.make.outer.variables.final=true java.completion.make.outer.variables.final.description=Make variables accessed from inner class final automatically +java.completion.argument.hints=false +java.completion.argument.hints.description=When completing a method call, show hints in place of all arguments + java.completion.argument.live.template=false java.completion.argument.live.template.description=When completing a method call, start a live template with all arguments diff --git a/platform/util/src/org/jetbrains/annotations/Debugger.java b/platform/util/src/org/jetbrains/annotations/Debugger.java new file mode 100644 index 000000000000..9000c7a9ee67 --- /dev/null +++ b/platform/util/src/org/jetbrains/annotations/Debugger.java @@ -0,0 +1,51 @@ +/* + * Copyright 2000-2017 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.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +/** + * @author egor + */ +public class Debugger { + + /** + * Advise IDEA Debugger to capture stack frames and use as a key: + *

    + *
  • {@code keyExpression} (if specified)
  • + *
  • annotated parameter value
  • + *
  • {@code this} value (if used on a method)
  • + *
+ */ + @Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER}) + public @interface Capture { + String keyExpression() default ""; + } + + /** + * Advise IDEA Debugger to replace the stack frames with the captured information and use as a key: + *
    + *
  • {@code keyExpression} (if specified)
  • + *
  • annotated parameter value
  • + *
  • {@code this} value (if used on a method)
  • + *
+ */ + @Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER}) + public @interface Insert { + String keyExpression() default ""; + } +} diff --git a/platform/vcs-api/src/com/intellij/openapi/vcs/changes/CommitExecutorWithHelp.java b/platform/vcs-api/src/com/intellij/openapi/vcs/changes/CommitExecutorWithHelp.java index 98afafaecb3e..124361592741 100644 --- a/platform/vcs-api/src/com/intellij/openapi/vcs/changes/CommitExecutorWithHelp.java +++ b/platform/vcs-api/src/com/intellij/openapi/vcs/changes/CommitExecutorWithHelp.java @@ -15,9 +15,12 @@ */ package com.intellij.openapi.vcs.changes; +import org.jetbrains.annotations.NonNls; + /** * @author irengrig */ public interface CommitExecutorWithHelp extends CommitExecutor { + @NonNls String getHelpId(); } diff --git a/platform/vcs-api/src/com/intellij/openapi/vcs/changes/CommitSession.java b/platform/vcs-api/src/com/intellij/openapi/vcs/changes/CommitSession.java index dd5ece12d63e..9f56a5495155 100644 --- a/platform/vcs-api/src/com/intellij/openapi/vcs/changes/CommitSession.java +++ b/platform/vcs-api/src/com/intellij/openapi/vcs/changes/CommitSession.java @@ -18,6 +18,7 @@ package com.intellij.openapi.vcs.changes; import com.intellij.openapi.ui.ValidationInfo; import org.jetbrains.annotations.CalledInAwt; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -69,6 +70,7 @@ public interface CommitSession { * @return the ID of the help topic to show for the dialog * @since 10.5 */ + @NonNls String getHelpId(); @CalledInAwt diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxModuleUtil.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxModuleUtil.java index dd42df925d60..9d092b72b3a0 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxModuleUtil.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxModuleUtil.java @@ -110,7 +110,10 @@ public class JavaFxModuleUtil { } private static ModificationTracker getModificationTracker(@NotNull Project project) { - return project.getUserData(KEY); + return () -> { + final ModificationTracker tracker = project.getUserData(KEY); + return tracker != null ? tracker.getModificationCount() + 1 : 0; + }; } @Override diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/RepeatSvnActionThroughBusy.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/RepeatSvnActionThroughBusy.java index 896015cbe6e2..e68035cf65ec 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/RepeatSvnActionThroughBusy.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/RepeatSvnActionThroughBusy.java @@ -32,24 +32,20 @@ import org.tmatesoft.svn.core.SVNException; public abstract class RepeatSvnActionThroughBusy { public static final int REPEAT = 10; - public static final Processor ourBusyExceptionProcessor = new Processor() { - @SuppressWarnings("ThrowableResultOfMethodCallIgnored") - @Override - public boolean process(Exception e) { - if (e instanceof SVNException) { - final SVNErrorCode errorCode = ((SVNException)e).getErrorMessage().getErrorCode(); - if (SVNErrorCode.WC_LOCKED.equals(errorCode)) { - return true; - } - else if (SVNErrorCode.SQLITE_ERROR.equals(errorCode)) { - Throwable cause = ((SVNException)e).getErrorMessage().getCause(); - if (cause instanceof SqlJetException) { - return SqlJetErrorCode.BUSY.equals(((SqlJetException)cause).getErrorCode()); - } + public static final Processor ourBusyExceptionProcessor = e -> { + if (e instanceof SVNException) { + final SVNErrorCode errorCode = ((SVNException)e).getErrorMessage().getErrorCode(); + if (SVNErrorCode.WC_LOCKED.equals(errorCode)) { + return true; + } + else if (SVNErrorCode.SQLITE_ERROR.equals(errorCode)) { + Throwable cause = ((SVNException)e).getErrorMessage().getCause(); + if (cause instanceof SqlJetException) { + return SqlJetErrorCode.BUSY.equals(((SqlJetException)cause).getErrorCode()); } } - return false; } + return false; }; protected int myCnt = REPEAT; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/RootsToWorkingCopies.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/RootsToWorkingCopies.java index b6d0f517ef46..0e4fceb111d6 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/RootsToWorkingCopies.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/RootsToWorkingCopies.java @@ -57,14 +57,12 @@ public class RootsToWorkingCopies implements VcsListener { myRootMapping = new HashMap<>(); myUnversioned = new HashSet<>(); myVcs = vcs; - myRechecker = new Runnable() { - public void run() { - final VirtualFile[] roots = ProjectLevelVcsManager.getInstance(myProject).getRootsUnderVcs(myVcs); - synchronized (myLock) { - clear(); - for (VirtualFile root : roots) { - addRoot(root); - } + myRechecker = () -> { + final VirtualFile[] roots = ProjectLevelVcsManager.getInstance(myProject).getRootsUnderVcs(myVcs); + synchronized (myLock) { + clear(); + for (VirtualFile root : roots) { + addRoot(root); } } }; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnAbstractWriteOperationLocks.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnAbstractWriteOperationLocks.java deleted file mode 100644 index c155d26a0645..000000000000 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnAbstractWriteOperationLocks.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2000-2014 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.idea.svn; - -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.vcs.changes.FilePathsHelper; -import com.intellij.util.TimeoutUtil; -import org.jetbrains.annotations.Nullable; -import org.tmatesoft.sqljet.core.SqlJetException; -import org.tmatesoft.sqljet.core.table.ISqlJetBusyHandler; -import org.tmatesoft.sqljet.core.table.ISqlJetTransaction; -import org.tmatesoft.sqljet.core.table.SqlJetDb; -import org.tmatesoft.svn.core.SVNException; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * Created with IntelliJ IDEA. - * User: Irina.Chernushina - * Date: 10/19/12 - * Time: 12:09 PM - */ -// TODO: Such locking functionality is not required anymore. Likely to be removed (together with SvnProxies). -public abstract class SvnAbstractWriteOperationLocks { - private final long myTimeout; - private final static Map myLockMap = new HashMap<>(); - private final static Object myLock = new Object(); - private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.svn.SvnAbstractWriteOperationLocks"); - private ISqlJetBusyHandler ourBusyHandler; - private volatile boolean myDisposed; - - protected SvnAbstractWriteOperationLocks(long timeout) { - myTimeout = timeout; - ourBusyHandler = new ISqlJetBusyHandler() { - @Override - public boolean call(int i) { - if (myDisposed) return false; - TimeoutUtil.sleep(myTimeout); - return true; - } - }; - } - - public void dispose() { - myDisposed = true; - } - - // null if not 1.7+ copy - @Nullable - private Lock getLockObject(File file) throws SVNException { - final boolean directory = file.isDirectory(); - final WorkingCopy wcRoot = getCopy(file, directory); - if (! wcRoot.is17Copy()) return null; - Lock lock; - final String path = FilePathsHelper.convertPath(wcRoot.getFile().getPath()); - synchronized (myLock) { - lock = myLockMap.get(path); - if (lock == null) { - lock = new ReentrantLock(); - myLockMap.put(path, lock); - } - } - return lock; - } - - protected abstract WorkingCopy getCopy(File file, boolean directory) throws SVNException; - - public void lockWrite(final File file) throws SVNException { - final Lock lock = getLockObject(file); - if (lock != null) { - lock.lock(); - } - } - - public void unlockWrite(final File file) throws SVNException { - final Lock lock = getLockObject(file); - if (lock != null) { - lock.unlock(); - } - } - - // would wait until read is available - public void wrapRead(final File file, final Runnable runnable) throws SVNException { - final WorkingCopy copy = getCopy(file, file.isDirectory()); - if (! copy.is17Copy()) { - runnable.run(); - return; - } - - final File root = copy.getFile(); - SqlJetDb open = null; - final boolean run[] = new boolean[1]; - run[0] = false; - try { - open = SqlJetDb.open(SvnUtil.getWcDb(root), false); - open.setBusyHandler(ourBusyHandler); - try { - final SqlJetDb finalOpen = open; - open.runReadTransaction(new ISqlJetTransaction() { - @Override - public Object run(SqlJetDb db) throws SqlJetException { - run[0] = true; - runnable.run(); - return null; - } - }); - } finally { - open.rollback(); - } - } - catch (SqlJetException e) { - LOG.info(e); - if (! run[0]) { - runnable.run(); - } - } - finally { - if (open != null) { - try { - open.close(); - } - catch (SqlJetException e) { - LOG.info(e); - } - } - } - } -} diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangeProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangeProvider.java index a77f05af2a37..2ddc296d03bd 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangeProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangeProvider.java @@ -59,13 +59,7 @@ public class SvnChangeProvider implements ChangeProvider { private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.svn.SvnChangeProvider"); public static final String PROPERTY_LAYER = "Property"; - private static final NotNullFactory> NAME_TO_FILE_MAP_FACTORY = new NotNullFactory>() { - @NotNull - @Override - public Map create() { - return ContainerUtil.newHashMap(); - } - }; + private static final NotNullFactory> NAME_TO_FILE_MAP_FACTORY = () -> ContainerUtil.newHashMap(); @NotNull private final SvnVcs myVcs; @NotNull private final VcsContextFactory myFactory; @@ -176,12 +170,7 @@ public class SvnChangeProvider implements ChangeProvider { } } - return new ISVNStatusFileProvider() { - @Override - public Map getChildrenFiles(File parent) { - return result.get(parent.getAbsolutePath()); - } - }; + return parent -> result.get(parent.getAbsolutePath()); } private void processCopiedAndDeleted(@NotNull SvnChangeProviderContext context, @Nullable VcsDirtyScope dirtyScope) throws SVNException { @@ -285,12 +274,10 @@ public class SvnChangeProvider implements ChangeProvider { final Change change = context .createMovedChange(createBeforeRevision(deletedFile, true), CurrentContentRevision.create(oldPath), copiedStatus, deletedFile.getStatus()); - final boolean isUnder = dirtyScope == null ? true : ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public Boolean compute() { - return ChangeListManagerImpl.isUnder(change, dirtyScope); - } - }); + final boolean isUnder = dirtyScope == null + ? true + : ApplicationManager.getApplication() + .runReadAction((Computable)() -> ChangeListManagerImpl.isUnder(change, dirtyScope)); if (isUnder) { context.getBuilder().removeRegisteredChangeFor(oldPath); context.getBuilder().processChangeInList(change, clName, SvnVcs.getKey()); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangelistListener.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangelistListener.java index 1b2b38075a13..b44fbebfa4da 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangelistListener.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnChangelistListener.java @@ -44,12 +44,9 @@ public class SvnChangelistListener implements ChangeListListener { public SvnChangelistListener(@NotNull SvnVcs vcs) { myVcs = vcs; - myUnderSvnCondition = new Condition() { - @Override - public boolean value(@NotNull FilePath path) { - final AbstractVcs vcs = ProjectLevelVcsManager.getInstance(myVcs.getProject()).getVcsFor(path); - return vcs != null && SvnVcs.VCS_NAME.equals(vcs.getName()); - } + myUnderSvnCondition = path -> { + final AbstractVcs vcs1 = ProjectLevelVcsManager.getInstance(myVcs.getProject()).getVcsFor(path); + return vcs1 != null && SvnVcs.VCS_NAME.equals(vcs1.getName()); }; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnCompatibilityChecker.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnCompatibilityChecker.java index 83ecbff2ff74..f14240f44a55 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnCompatibilityChecker.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnCompatibilityChecker.java @@ -20,7 +20,6 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.MessageType; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier; import com.intellij.openapi.vfs.VirtualFile; @@ -55,30 +54,21 @@ public class SvnCompatibilityChecker { myCounter = 0; ++ myInvocationCounter; final Application application = ApplicationManager.getApplication(); - application.executeOnPooledThread(new Runnable() { - public void run() { - final List suspicious = new ArrayList<>(); - for (VirtualFile vf : result) { - if (SvnUtil.seemsLikeVersionedDir(vf)) { - suspicious.add(vf); - } - } - if (! suspicious.isEmpty()) { - final String message = (suspicious.size() == 1) ? - "Root '" + suspicious.get(0).getPresentableName() + "' is likely to be of unsupported Subversion format" : - "Some roots are likely to be of unsupported Subversion format"; - application.invokeLater(new Runnable() { - public void run() { - new VcsBalloonProblemNotifier(myProject, message, MessageType.WARNING).run(); - } - }, ModalityState.NON_MODAL, new Condition() { - @Override - public boolean value(Object o) { - return (! myProject.isOpen()) || myProject.isDisposed(); - } - }); + application.executeOnPooledThread(() -> { + final List suspicious = new ArrayList<>(); + for (VirtualFile vf : result) { + if (SvnUtil.seemsLikeVersionedDir(vf)) { + suspicious.add(vf); } } + if (!suspicious.isEmpty()) { + final String message = (suspicious.size() == 1) + ? "Root '" + suspicious.get(0).getPresentableName() + "' is likely to be of unsupported Subversion format" + : "Some roots are likely to be of unsupported Subversion format"; + application + .invokeLater(() -> new VcsBalloonProblemNotifier(myProject, message, MessageType.WARNING).run(), ModalityState.NON_MODAL, + o -> (!myProject.isOpen()) || myProject.isDisposed()); + } }); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfigurable.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfigurable.java index 6be64c7de411..f5a6227395c2 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfigurable.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfigurable.java @@ -37,7 +37,6 @@ import com.intellij.ui.MultiLineTooltipUI; import com.intellij.ui.components.JBCheckBox; import com.intellij.ui.components.JBRadioButton; import com.intellij.ui.components.labels.LinkLabel; -import com.intellij.ui.components.labels.LinkListener; import com.intellij.util.Consumer; import com.intellij.util.net.HttpProxyConfigurable; import com.intellij.util.ui.UIUtil; @@ -51,10 +50,6 @@ import org.jetbrains.idea.svn.svnkit.SvnKitManager; import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.io.File; public class SvnConfigurable implements Configurable { @@ -96,79 +91,52 @@ public class SvnConfigurable implements Configurable { public SvnConfigurable(Project project) { myProject = project; - myWithCommandLineClient.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - enableCommandLineClientOptions(); - } - }); + myWithCommandLineClient.addItemListener(e -> enableCommandLineClientOptions()); enableCommandLineClientOptions(); - myUseDefaultCheckBox.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - boolean enabled = !myUseDefaultCheckBox.isSelected(); - myConfigurationDirectoryText.setEnabled(enabled); - myConfigurationDirectoryText.setEditable(enabled); - myConfigurationDirectoryLabel.setEnabled(enabled); - SvnConfiguration configuration = SvnConfiguration.getInstance(myProject); - String path = configuration.getConfigurationDirectory(); - if (!enabled || path == null) { - myConfigurationDirectoryText.setText(IdeaSubversionConfigurationDirectory.getPath()); - } - else { - myConfigurationDirectoryText.setText(path); - } + myUseDefaultCheckBox.addActionListener(e -> { + boolean enabled = !myUseDefaultCheckBox.isSelected(); + myConfigurationDirectoryText.setEnabled(enabled); + myConfigurationDirectoryText.setEditable(enabled); + myConfigurationDirectoryLabel.setEnabled(enabled); + SvnConfiguration configuration = SvnConfiguration.getInstance(myProject); + String path = configuration.getConfigurationDirectory(); + if (!enabled || path == null) { + myConfigurationDirectoryText.setText(IdeaSubversionConfigurationDirectory.getPath()); + } + else { + myConfigurationDirectoryText.setText(path); } }); myCommandLineClient.addBrowseFolderListener("Subversion", "Select path to Subversion executable (1.7+)", project, FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor()); - myClearAuthButton.addActionListener(new ActionListener(){ - public void actionPerformed(final ActionEvent e) { - SvnAuthenticationNotifier.clearAuthenticationCache(myProject, myComponent, myConfigurationDirectoryText.getText()); - } - }); + myClearAuthButton.addActionListener( + e -> SvnAuthenticationNotifier.clearAuthenticationCache(myProject, myComponent, myConfigurationDirectoryText.getText())); - - myConfigurationDirectoryText.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - @NonNls String path = myConfigurationDirectoryText.getText().trim(); - selectConfigurationDirectory(path, new Consumer() { - @Override - public void consume(String s) { - myConfigurationDirectoryText.setText(s); - } - }, myProject, myComponent); - } + myConfigurationDirectoryText.addActionListener(e -> { + @NonNls String path = myConfigurationDirectoryText.getText().trim(); + selectConfigurationDirectory(path, s -> myConfigurationDirectoryText.setText(s), myProject, myComponent); }); myConfigurationDirectoryLabel.setLabelFor(myConfigurationDirectoryText); myUseCommonProxy.setText(SvnBundle.message("use.idea.proxy.as.default", ApplicationNamesInfo.getInstance().getProductName())); - myNavigateToCommonProxyLink.setListener(new LinkListener() { - @Override - public void linkSelected(LinkLabel aSource, Object aLinkData) { - Settings settings = Settings.KEY.getData(DataManager.getInstance().getDataContext(myComponent)); + myNavigateToCommonProxyLink.setListener((aSource, aLinkData) -> { + Settings settings = Settings.KEY.getData(DataManager.getInstance().getDataContext(myComponent)); - if (settings != null) { - settings.select(settings.find(HttpProxyConfigurable.class)); - } + if (settings != null) { + settings.select(settings.find(HttpProxyConfigurable.class)); } }, null); - myEditProxiesButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - final SvnConfigureProxiesDialog dialog = new SvnConfigureProxiesDialog(myProject); - dialog.show(); - myHttpTimeout.setValue(Long.valueOf(SvnConfiguration.getInstance(myProject).getHttpTimeout() / 1000)); - } + myEditProxiesButton.addActionListener(e -> { + final SvnConfigureProxiesDialog dialog = new SvnConfigureProxiesDialog(myProject); + dialog.show(); + myHttpTimeout.setValue(Long.valueOf(SvnConfiguration.getInstance(myProject).getHttpTimeout() / 1000)); }); - myMaximumNumberOfRevisionsCheckBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - myNumRevsInAnnotations.setEnabled(myMaximumNumberOfRevisionsCheckBox.isSelected()); - } - }); + myMaximumNumberOfRevisionsCheckBox + .addActionListener(e -> myNumRevsInAnnotations.setEnabled(myMaximumNumberOfRevisionsCheckBox.isSelected())); myNumRevsInAnnotations.setEnabled(myMaximumNumberOfRevisionsCheckBox.isSelected()); final ButtonGroup bg = new ButtonGroup(); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfiguration.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfiguration.java index e56129752ac3..779fe47fce7b 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfiguration.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnConfiguration.java @@ -17,7 +17,6 @@ package org.jetbrains.idea.svn; -import com.intellij.openapi.Disposable; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; @@ -374,12 +373,7 @@ public class SvnConfiguration implements PersistentStateComponent myAuthManager = null); getInteractiveManager(svnVcs); // to init myAuthManager.setAuthenticationProvider(new SvnAuthenticationProvider(svnVcs, myInteractiveProvider, myAuthManager)); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnCopiesRefreshManager.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnCopiesRefreshManager.java index d32d5c00124b..b92ca7db687d 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnCopiesRefreshManager.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnCopiesRefreshManager.java @@ -17,7 +17,6 @@ package org.jetbrains.idea.svn; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.RequestsMerger; -import com.intellij.util.Consumer; import com.intellij.util.concurrency.Semaphore; public class SvnCopiesRefreshManager { @@ -28,24 +27,12 @@ public class SvnCopiesRefreshManager { public SvnCopiesRefreshManager(final SvnFileUrlMappingImpl mapping) { mySemaphore = new Semaphore(); // svn mappings refresh inside also uses asynchronous pass -> we need to pass callback that will ping our "single-threaded" executor here - myMappingCallback = new Runnable() { - @Override - public void run() { - mySemaphore.up(); - } - }; - myRequestsMerger = new RequestsMerger(new Runnable() { - @Override - public void run() { - mySemaphore.down(); - mapping.realRefresh(myMappingCallback); - mySemaphore.waitFor(); - } - }, new Consumer() { - public void consume(final Runnable runnable) { - ApplicationManager.getApplication().executeOnPooledThread(runnable); - } - }); + myMappingCallback = () -> mySemaphore.up(); + myRequestsMerger = new RequestsMerger(() -> { + mySemaphore.down(); + mapping.realRefresh(myMappingCallback); + mySemaphore.waitFor(); + }, runnable -> ApplicationManager.getApplication().executeOnPooledThread(runnable)); } public void asynchRequest() { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnDiffProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnDiffProvider.java index 1cb055e026c4..8a95d618ad81 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnDiffProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnDiffProvider.java @@ -40,7 +40,6 @@ import org.jetbrains.idea.svn.info.InfoConsumer; import org.jetbrains.idea.svn.properties.PropertyValue; import org.jetbrains.idea.svn.status.Status; import org.jetbrains.idea.svn.status.StatusType; -import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc2.SvnTarget; @@ -118,18 +117,15 @@ public class SvnDiffProvider extends DiffProviderEx implements DiffProvider, Dif @NotNull private static InfoConsumer createInfoHandler(@NotNull final Map revisionMap, @NotNull final Map fileMap) { - return new InfoConsumer() { - @Override - public void consume(Info info) throws SVNException { - if (info != null) { - VirtualFile file = fileMap.get(info.getFile().getAbsolutePath()); + return info -> { + if (info != null) { + VirtualFile file = fileMap.get(info.getFile().getAbsolutePath()); - if (file != null) { - revisionMap.put(file, getRevision(info)); - } - else { - LOG.info("Could not find virtual file for path " + info.getFile().getAbsolutePath()); - } + if (file != null) { + revisionMap.put(file, getRevision(info)); + } + else { + LOG.info("Could not find virtual file for path " + info.getFile().getAbsolutePath()); } } }; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnFileSystemListener.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnFileSystemListener.java index ec1b961e55ac..c732a6f6d928 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnFileSystemListener.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnFileSystemListener.java @@ -40,7 +40,6 @@ import com.intellij.openapi.vfs.LocalFileOperationsHandler; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.RefreshQueue; -import com.intellij.util.Processor; import com.intellij.util.ThrowableConsumer; import com.intellij.util.containers.Convertor; import com.intellij.util.containers.MultiMap; @@ -359,22 +358,19 @@ public class SvnFileSystemListener extends CommandAdapter implements LocalFileOp private static void copyUnversionedMembersOfDirectory(final File src, final File dst) throws SvnBindException { if (src.isDirectory()) { final SvnBindException[] exc = new SvnBindException[1]; - FileUtil.processFilesRecursively(src, new Processor() { - @Override - public boolean process(File file) { - String relativePath = FileUtil.getRelativePath(src, file); - File newFile = new File(dst, relativePath); - if (!newFile.exists()) { - try { - FileUtil.copyFileOrDir(src, dst); - } - catch (IOException e) { - exc[0] = new SvnBindException(e); - return false; - } + FileUtil.processFilesRecursively(src, file -> { + String relativePath = FileUtil.getRelativePath(src, file); + File newFile = new File(dst, relativePath); + if (!newFile.exists()) { + try { + FileUtil.copyFileOrDir(src, dst); + } + catch (IOException e) { + exc[0] = new SvnBindException(e); + return false; } - return true; } + return true; }); if (exc[0] != null) { throw exc[0]; @@ -709,15 +705,13 @@ public class SvnFileSystemListener extends CommandAdapter implements LocalFileOp // if refresh asynchronously, local changes would also be notified that they are dirty asynchronously, // and commit could be executed while not all changes are visible filterOutInvalid(myFilesToRefresh); - RefreshQueue.getInstance().refresh(true, true, new Runnable() { - public void run() { - if (project.isDisposed()) return; - filterOutInvalid(toRefreshFiles); - filterOutInvalid(toRefreshDirs); + RefreshQueue.getInstance().refresh(true, true, () -> { + if (project.isDisposed()) return; + filterOutInvalid(toRefreshFiles); + filterOutInvalid(toRefreshDirs); - final VcsDirtyScopeManager vcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(project); - vcsDirtyScopeManager.filesDirty(toRefreshFiles, toRefreshDirs); - } + final VcsDirtyScopeManager vcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(project); + vcsDirtyScopeManager.filesDirty(toRefreshFiles, toRefreshDirs); }, myFilesToRefresh); myFilesToRefresh.clear(); } @@ -748,18 +742,15 @@ public class SvnFileSystemListener extends CommandAdapter implements LocalFileOp // Current method could be invoked under write action (for instance, during project import). So we explicitly use // Application.invokeLater() in such cases to prevent deadlocks (while accessing vcs root mappings) and also not to show dialog under // write action. - runNotUnderWriteAction(project, new Runnable() { - @Override - public void run() { - final AbstractVcsHelper vcsHelper = AbstractVcsHelper.getInstance(project); - final Collection filesToProcess = promptAboutAddition(vcs, addedVFiles, value, vcsHelper); - if (filesToProcess != null && !filesToProcess.isEmpty()) { - final List exceptions = new ArrayList<>(); - runInBackground(project, "Adding files to Subversion", - createAdditionRunnable(project, vcs, copyFromMap, filesToProcess, exceptions)); - if (!exceptions.isEmpty()) { - vcsHelper.showErrors(exceptions, SvnBundle.message("add.files.errors.title")); - } + runNotUnderWriteAction(project, () -> { + final AbstractVcsHelper vcsHelper = AbstractVcsHelper.getInstance(project); + final Collection filesToProcess = promptAboutAddition(vcs, addedVFiles, value, vcsHelper); + if (filesToProcess != null && !filesToProcess.isEmpty()) { + final List exceptions = new ArrayList<>(); + runInBackground(project, "Adding files to Subversion", + createAdditionRunnable(project, vcs, copyFromMap, filesToProcess, exceptions)); + if (!exceptions.isEmpty()) { + vcsHelper.showErrors(exceptions, SvnBundle.message("add.files.errors.title")); } } }); @@ -789,44 +780,41 @@ public class SvnFileSystemListener extends CommandAdapter implements LocalFileOp final Map copyFromMap, final Collection filesToProcess, final List exceptions) { - return new Runnable() { - @Override - public void run() { - for(VirtualFile file: filesToProcess) { - final File ioFile = new File(file.getPath()); - try { - final File copyFrom = copyFromMap.get(file); - if (copyFrom != null) { - try { - new ActionWithTempFile(ioFile) { - protected void executeInternal() throws VcsException { - // not recursive - new RepeatSvnActionThroughBusy() { - @Override - protected void executeImpl() throws VcsException { - vcs.getFactory(copyFrom).createCopyMoveClient().copy(copyFrom, ioFile, true, false); - } - }.execute(); - } - }.execute(); - } - catch (VcsException e) { - exceptions.add(e); - } - } - else { - new RepeatSvnActionThroughBusy() { - @Override - protected void executeImpl() throws VcsException { - vcs.getFactory(ioFile).createAddClient().add(ioFile, null, false, false, true, null); + return () -> { + for (VirtualFile file : filesToProcess) { + final File ioFile = new File(file.getPath()); + try { + final File copyFrom = copyFromMap.get(file); + if (copyFrom != null) { + try { + new ActionWithTempFile(ioFile) { + protected void executeInternal() throws VcsException { + // not recursive + new RepeatSvnActionThroughBusy() { + @Override + protected void executeImpl() throws VcsException { + vcs.getFactory(copyFrom).createCopyMoveClient().copy(copyFrom, ioFile, true, false); + } + }.execute(); } }.execute(); } - VcsDirtyScopeManager.getInstance(project).fileDirty(file); + catch (VcsException e) { + exceptions.add(e); + } } - catch (VcsException e) { - exceptions.add(e); + else { + new RepeatSvnActionThroughBusy() { + @Override + protected void executeImpl() throws VcsException { + vcs.getFactory(ioFile).createAddClient().add(ioFile, null, false, false, true, null); + } + }.execute(); } + VcsDirtyScopeManager.getInstance(project).fileDirty(file); + } + catch (VcsException e) { + exceptions.add(e); } } }; @@ -907,12 +895,7 @@ public class SvnFileSystemListener extends CommandAdapter implements LocalFileOp if (!filesToProcess.isEmpty()) { runInBackground(project, "Deleting files from Subversion", createDeleteRunnable(project, vcs, filesToProcess, exceptions)); } - final List deletedFilesFiles = ObjectsConvertor.convert(deletedFiles, new Convertor, FilePath>() { - @Override - public FilePath convert(Pair o) { - return o.getFirst(); - } - }); + final List deletedFilesFiles = ObjectsConvertor.convert(deletedFiles, o -> o.getFirst()); for (FilePath file : deletedFilesFiles) { final FilePath parent = file.getParentPath(); if (parent != null) { @@ -936,25 +919,23 @@ public class SvnFileSystemListener extends CommandAdapter implements LocalFileOp final SvnVcs vcs, final Collection filesToProcess, final List exceptions) { - return new Runnable() { - public void run() { - for(FilePath file: filesToProcess) { - VirtualFile vFile = file.getVirtualFile(); // for deleted directories - final File ioFile = new File(file.getPath()); - try { - createDeleteAction(vcs, ioFile, true).execute(); - if (vFile != null && vFile.isValid() && vFile.isDirectory()) { - vFile.refresh(true, true); - VcsDirtyScopeManager.getInstance(project).dirDirtyRecursively(vFile); - } - else { - VcsDirtyScopeManager.getInstance(project).fileDirty(file); - } + return () -> { + for (FilePath file : filesToProcess) { + VirtualFile vFile = file.getVirtualFile(); // for deleted directories + final File ioFile = new File(file.getPath()); + try { + createDeleteAction(vcs, ioFile, true).execute(); + if (vFile != null && vFile.isValid() && vFile.isDirectory()) { + vFile.refresh(true, true); + VcsDirtyScopeManager.getInstance(project).dirDirtyRecursively(vFile); } - catch (VcsException e) { - exceptions.add(e); + else { + VcsDirtyScopeManager.getInstance(project).fileDirty(file); } } + catch (VcsException e) { + exceptions.add(e); + } } }; } @@ -963,13 +944,7 @@ public class SvnFileSystemListener extends CommandAdapter implements LocalFileOp SvnVcs vcs, VcsShowConfirmationOption.Value value, AbstractVcsHelper vcsHelper) { - final Convertor, FilePath> convertor = - new Convertor, FilePath>() { - @Override - public FilePath convert(Pair o) { - return o.getFirst(); - } - }; + final Convertor, FilePath> convertor = o -> o.getFirst(); Collection filesToProcess; if (value == VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY) { filesToProcess = ObjectsConvertor.convert(deletedFiles, convertor); @@ -1016,14 +991,12 @@ public class SvnFileSystemListener extends CommandAdapter implements LocalFileOp private void processMovedFiles(final Project project) { if (myMovedFiles.isEmpty()) return; - final Runnable runnable = new Runnable() { - public void run() { - for (Iterator iterator = myMovedFiles.iterator(); iterator.hasNext();) { - MovedFileInfo movedFileInfo = iterator.next(); - if (movedFileInfo.myProject == project) { - doMove(SvnVcs.getInstance(project), movedFileInfo.mySrc, movedFileInfo.myDst); - iterator.remove(); - } + final Runnable runnable = () -> { + for (Iterator iterator = myMovedFiles.iterator(); iterator.hasNext(); ) { + MovedFileInfo movedFileInfo = iterator.next(); + if (movedFileInfo.myProject == project) { + doMove(SvnVcs.getInstance(project), movedFileInfo.mySrc, movedFileInfo.myDst); + iterator.remove(); } } }; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnNativeCallsTranslator.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnNativeCallsTranslator.java index 59f6f298b8b5..5ec3cf82abfb 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnNativeCallsTranslator.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnNativeCallsTranslator.java @@ -165,18 +165,16 @@ public class SvnNativeCallsTranslator { } static { - ourAdvices.put(-25293, new Convertor() { - @Override - public String convert(NativeLogReader.CallInfo callInfo) { - if (! SystemInfo.isMac) return null; - final Trinity trinity = MacParser.macMessages.get(callInfo.getResultCode()); - if (trinity == null) return null; - return MessageFormat.format(ourGenericAdvice, callInfo.getFunctionName(), - new StringBuilder().append(callInfo.getResultCode()).append(" ( ").append(trinity.getFirst()) - .append(" - ").append(trinity.getSecond()).append(")").append("\nYou are likely to have modified ") - .append(ApplicationInfo.getInstance().getVersionName()).append(" bundle.\n") - .append("Please try to reinstall ").append(ApplicationInfo.getInstance().getVersionName()).toString()); - } + ourAdvices.put(-25293, callInfo -> { + if (!SystemInfo.isMac) return null; + final Trinity trinity = MacParser.macMessages.get(callInfo.getResultCode()); + if (trinity == null) return null; + return MessageFormat.format(ourGenericAdvice, callInfo.getFunctionName(), + new StringBuilder().append(callInfo.getResultCode()).append(" ( ").append(trinity.getFirst()) + .append(" - ").append(trinity.getSecond()).append(")").append("\nYou are likely to have modified ") + .append(ApplicationInfo.getInstance().getVersionName()).append(" bundle.\n") + .append("Please try to reinstall ").append(ApplicationInfo.getInstance().getVersionName()) + .toString()); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRecursiveStatusWalker.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRecursiveStatusWalker.java index 4ad69fe040cf..f28a25927618 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRecursiveStatusWalker.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRecursiveStatusWalker.java @@ -20,17 +20,14 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Processor; +import com.intellij.openapi.vfs.VirtualFileVisitor; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,13 +42,17 @@ import org.jetbrains.idea.svn.status.StatusType; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNException; -import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.wc.ISVNStatusFileProvider; import org.tmatesoft.svn.core.wc.SVNRevision; import java.io.File; import java.util.LinkedList; +import static com.intellij.openapi.vfs.VfsUtilCore.visitChildrenRecursively; +import static com.intellij.openapi.vfs.VirtualFileVisitor.ONE_LEVEL_DEEP; +import static com.intellij.openapi.vfs.VirtualFileVisitor.SKIP_ROOT; +import static com.intellij.util.containers.ContainerUtil.ar; + public class SvnRecursiveStatusWalker { private static final Logger LOG = Logger.getInstance("#org.jetbrains.idea.svn.SvnRecursiveStatusWalker"); @@ -129,12 +130,9 @@ public class SvnRecursiveStatusWalker { } public boolean isIgnoredByVcs(@NotNull final VirtualFile vFile) { - return ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public Boolean compute() { - if (myVcs.getProject().isDisposed()) throw new ProcessCanceledException(); - return myVcsManager.isIgnored(vFile); - } + return ApplicationManager.getApplication().runReadAction((Computable)() -> { + if (myVcs.getProject().isDisposed()) throw new ProcessCanceledException(); + return myVcsManager.isIgnored(vFile); }); } @@ -198,57 +196,28 @@ public class SvnRecursiveStatusWalker { myReceiver.processIgnored(vFile); return; } - final Depth newDepth = Depth.INFINITY.equals(prevDepth) ? Depth.INFINITY : Depth.EMPTY; - final File ioFile = new File(vFile.getPath()); - final Processor processor; - final Processor directoryFilter; - final Ref lastIgnored = new Ref<>(); - final Processor checkDirProcessor = new Processor() { + Depth newDepth = Depth.INFINITY.equals(prevDepth) ? Depth.INFINITY : Depth.EMPTY; + VirtualFileVisitor.Option[] options = newDepth.equals(Depth.EMPTY) ? ar(SKIP_ROOT, ONE_LEVEL_DEEP) : new VirtualFileVisitor.Option[0]; + + visitChildrenRecursively(vFile, new VirtualFileVisitor(options) { + @NotNull @Override - public boolean process(File file) { - FilePath path = VcsUtil.getFilePath(file, true); - VirtualFile vf = VfsUtil.findFileByIoFile(file, true); - if (vf != null && isIgnoredIdeaLevel(vf)) { - lastIgnored.set(file); - myReceiver.processIgnored(vf); + public Result visitFileEx(@NotNull VirtualFile file) { + if (isIgnoredIdeaLevel(file)) { + myReceiver.processIgnored(file); + return SKIP_CHILDREN; } - else if (file.isDirectory() && new File(file, SVNFileUtil.getAdminDirectoryName()).exists()) { - myQueue.add(createItem(path, newDepth, true)); + else if (file.isDirectory() && file.findChild(SvnUtil.SVN_ADMIN_DIR_NAME) != null) { + myQueue.add(createItem(VcsUtil.getFilePath(file), newDepth, true)); + return SKIP_CHILDREN; } - else if (vf != null) { - myReceiver.processUnversioned(vf); + else { + myReceiver.processUnversioned(file); + return CONTINUE; } - return true; } - }; - if (Depth.EMPTY.equals(newDepth)) { - // just process immediate children - so only root directory itself should satisfy filter - directoryFilter = new Processor() { - @Override - public boolean process(File file) { - return FileUtil.filesEqual(ioFile, file); - } - }; - processor = new Processor() { - @Override - public boolean process(File file) { - // TODO: check if we should still call checkDirProcessor() here - or we really could not check ignore settings but just call - // TODO: myReceiver.processUnversioned() for all immediate children - // here we deal only with immediate children - so ignored on IDEA level for children is not important - return FileUtil.filesEqual(ioFile, file) || checkDirProcessor.process(file); - } - }; - } else { - directoryFilter = new Processor() { - @Override - public boolean process(File file) { - return ! Comparing.equal(lastIgnored, file) && (myQueue.isEmpty() || ! FileUtil.filesEqual(myQueue.getLast().getPath().getIOFile(), file)); - } - }; - processor = checkDirProcessor; - } - FileUtil.processFilesRecursively(ioFile, processor, directoryFilter); + }); } @NotNull diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRootsDetector.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRootsDetector.java index 5cf3ebbd7d3b..04a25dbc2bd2 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRootsDetector.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnRootsDetector.java @@ -16,17 +16,13 @@ package org.jetbrains.idea.svn; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.ObjectsConvertor; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.InvokeAfterUpdateMode; -import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.Convertor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.status.Status; @@ -94,11 +90,7 @@ public class SvnRootsDetector { } private void addNestedRoots(final boolean clearState, final Runnable callback) { - final List basicVfRoots = ObjectsConvertor.convert(myResult.myTopRoots, new Convertor() { - public VirtualFile convert(final RootUrlInfo real) { - return real.getVirtualFile(); - } - }); + final List basicVfRoots = ObjectsConvertor.convert(myResult.myTopRoots, real -> real.getVirtualFile()); final ChangeListManager clManager = ChangeListManager.getInstance(myVcs.getProject()); @@ -106,38 +98,34 @@ public class SvnRootsDetector { // clear what was reported before (could be for currently-not-existing roots) myNestedCopiesHolder.getAndClear(); } - clManager.invokeAfterUpdate(new Runnable() { - public void run() { - final List nestedRoots = new ArrayList<>(); + clManager.invokeAfterUpdate(() -> { + final List nestedRoots = new ArrayList<>(); - for (NestedCopyInfo info : myNestedCopiesHolder.getAndClear()) { - if (NestedCopyType.external.equals(info.getType()) || NestedCopyType.switched.equals(info.getType())) { - RootUrlInfo topRoot = findTopRoot(VfsUtilCore.virtualToIoFile(info.getFile())); + for (NestedCopyInfo info : myNestedCopiesHolder.getAndClear()) { + if (NestedCopyType.external.equals(info.getType()) || NestedCopyType.switched.equals(info.getType())) { + RootUrlInfo topRoot = findTopRoot(VfsUtilCore.virtualToIoFile(info.getFile())); - if (topRoot != null) { - // TODO: Seems that type is not set in ForNestedRootChecker as we could not determine it for sure. Probably, for the case - // TODO: (or some other cases) when vcs root from settings belongs is in externals of some other working copy upper - // TODO: the tree (I did not check this). Leave this setter for now. - topRoot.setType(info.getType()); - continue; - } - if (!refreshPointInfo(info)) { - continue; - } + if (topRoot != null) { + // TODO: Seems that type is not set in ForNestedRootChecker as we could not determine it for sure. Probably, for the case + // TODO: (or some other cases) when vcs root from settings belongs is in externals of some other working copy upper + // TODO: the tree (I did not check this). Leave this setter for now. + topRoot.setType(info.getType()); + continue; + } + if (!refreshPointInfo(info)) { + continue; } - registerRootUrlFromNestedPoint(info, nestedRoots); } - - myResult.myTopRoots.addAll(nestedRoots); - myMapping.applyDetectionResult(myResult); - - callback.run(); + registerRootUrlFromNestedPoint(info, nestedRoots); } - }, InvokeAfterUpdateMode.SILENT_CALLBACK_POOLED, null, new Consumer() { - public void consume(VcsDirtyScopeManager vcsDirtyScopeManager) { - if (clearState) { - vcsDirtyScopeManager.filesDirty(null, basicVfRoots); - } + + myResult.myTopRoots.addAll(nestedRoots); + myMapping.applyDetectionResult(myResult); + + callback.run(); + }, InvokeAfterUpdateMode.SILENT_CALLBACK_POOLED, null, vcsDirtyScopeManager -> { + if (clearState) { + vcsDirtyScopeManager.filesDirty(null, basicVfRoots); } }, null); } @@ -185,22 +173,12 @@ public class SvnRootsDetector { @Nullable private RootUrlInfo findTopRoot(@NotNull final File file) { - return ContainerUtil.find(myResult.myTopRoots, new Condition() { - @Override - public boolean value(RootUrlInfo topRoot) { - return FileUtil.filesEqual(topRoot.getIoFile(), file); - } - }); + return ContainerUtil.find(myResult.myTopRoots, topRoot -> FileUtil.filesEqual(topRoot.getIoFile(), file)); } @Nullable private RootUrlInfo findAncestorTopRoot(@NotNull final VirtualFile file) { - return ContainerUtil.find(myResult.myTopRoots, new Condition() { - @Override - public boolean value(RootUrlInfo topRoot) { - return VfsUtilCore.isAncestor(topRoot.getVirtualFile(), file, true); - } - }); + return ContainerUtil.find(myResult.myTopRoots, topRoot -> VfsUtilCore.isAncestor(topRoot.getVirtualFile(), file, true)); } private static class RepositoryRoots { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnTestWriteOperationLocks.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnTestWriteOperationLocks.java deleted file mode 100644 index efea2f93de08..000000000000 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnTestWriteOperationLocks.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.svn; - -import org.tmatesoft.svn.core.SVNException; - -import java.io.File; - -/** - * Created with IntelliJ IDEA. - * User: Irina.Chernushina - * Date: 10/23/12 - * Time: 2:31 PM - */ -// TODO: Used only in SvnLockingTest which is not required anymore. Likely to be removed. -public class SvnTestWriteOperationLocks extends SvnAbstractWriteOperationLocks { - private final WorkingCopy myWorkingCopy; - - public SvnTestWriteOperationLocks(WorkingCopy copy) { - super(10); - myWorkingCopy = copy; - } - - @Override - protected WorkingCopy getCopy(File file, boolean directory) throws SVNException { - return myWorkingCopy; - } -} diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnUtil.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnUtil.java index f767416251d1..6af28a3d5dcc 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnUtil.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnUtil.java @@ -41,7 +41,6 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.wm.impl.status.StatusBarUtil; import com.intellij.util.ArrayUtil; -import com.intellij.util.NotNullFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.containers.MultiMap; @@ -55,7 +54,6 @@ import org.jetbrains.idea.svn.api.ProgressEvent; import org.jetbrains.idea.svn.api.ProgressTracker; import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationManager; import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationNew; -import org.jetbrains.idea.svn.browse.DirectoryEntry; import org.jetbrains.idea.svn.browse.DirectoryEntryConsumer; import org.jetbrains.idea.svn.commandLine.SvnBindException; import org.jetbrains.idea.svn.dialogs.LockDialog; @@ -67,7 +65,6 @@ import org.tmatesoft.sqljet.core.internal.table.ISqlJetBtreeSchemaTable; import org.tmatesoft.sqljet.core.internal.table.SqlJetBtreeSchemaTable; import org.tmatesoft.sqljet.core.table.ISqlJetOptions; import org.tmatesoft.sqljet.core.table.SqlJetDb; -import org.tmatesoft.sqljet.core.table.engine.ISqlJetEngineSynchronized; import org.tmatesoft.sqljet.core.table.engine.SqlJetEngine; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; @@ -224,27 +221,25 @@ public class SvnUtil { } }; - Runnable command = new Runnable() { - public void run() { - ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + Runnable command = () -> { + ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - try { + try { + if (progress != null) { + progress.setText(SvnBundle.message("progress.text.locking.files")); + } + for (File ioFile : ioFiles) { if (progress != null) { - progress.setText(SvnBundle.message("progress.text.locking.files")); + progress.checkCanceled(); } - for (File ioFile : ioFiles) { - if (progress != null) { - progress.checkCanceled(); - } - if (progress != null) { - progress.setText2(SvnBundle.message("progress.text2.processing.file", ioFile.getName())); - } - activeVcs.getFactory(ioFile).createLockClient().lock(ioFile, force, lockMessage, eventHandler); + if (progress != null) { + progress.setText2(SvnBundle.message("progress.text2.processing.file", ioFile.getName())); } + activeVcs.getFactory(ioFile).createLockClient().lock(ioFile, force, lockMessage, eventHandler); } - catch (VcsException e) { - exception[0] = e; - } + } + catch (VcsException e) { + exception[0] = e; } }; @@ -289,27 +284,25 @@ public class SvnUtil { } }; - Runnable command = new Runnable() { - public void run() { - ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + Runnable command = () -> { + ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - try { + try { + if (progress != null) { + progress.setText(SvnBundle.message("progress.text.unlocking.files")); + } + for (File ioFile : ioFiles) { if (progress != null) { - progress.setText(SvnBundle.message("progress.text.unlocking.files")); + progress.checkCanceled(); } - for (File ioFile : ioFiles) { - if (progress != null) { - progress.checkCanceled(); - } - if (progress != null) { - progress.setText2(SvnBundle.message("progress.text2.processing.file", ioFile.getName())); - } - activeVcs.getFactory(ioFile).createLockClient().unlock(ioFile, force, eventHandler); + if (progress != null) { + progress.setText2(SvnBundle.message("progress.text2.processing.file", ioFile.getName())); } + activeVcs.getFactory(ioFile).createLockClient().unlock(ioFile, force, eventHandler); } - catch (VcsException e) { - exception[0] = e; - } + } + catch (VcsException e) { + exception[0] = e; } }; @@ -332,26 +325,17 @@ public class SvnUtil { @NotNull public static MultiMap, Change> splitChangesIntoWc(@NotNull SvnVcs vcs, @NotNull List changes) { - return splitIntoRepositoriesMap(vcs, changes, new Convertor() { - @Override - public FilePath convert(@NotNull Change change) { - return ChangesUtil.getFilePath(change); - } - }); + return splitIntoRepositoriesMap(vcs, changes, change -> ChangesUtil.getFilePath(change)); } @NotNull public static MultiMap, T> splitIntoRepositoriesMap(@NotNull final SvnVcs vcs, @NotNull Collection items, @NotNull final Convertor converter) { - return ContainerUtil.groupBy(items, new NotNullFunction>() { - @NotNull - @Override - public Pair fun(@NotNull T item) { - RootUrlInfo path = vcs.getSvnFileUrlMapping().getWcRootForFilePath(converter.convert(item).getIOFile()); + return ContainerUtil.groupBy(items, item -> { + RootUrlInfo path = vcs.getSvnFileUrlMapping().getWcRootForFilePath(converter.convert(item).getIOFile()); - return path == null ? UNKNOWN_REPOSITORY_AND_FORMAT : Pair.create(path.getRepositoryUrlUrl(), path.getFormat()); - } + return path == null ? UNKNOWN_REPOSITORY_AND_FORMAT : Pair.create(path.getRepositoryUrlUrl(), path.getFormat()); }); } @@ -487,12 +471,8 @@ public class SvnUtil { public static VirtualFile getVirtualFile(final String filePath) { @NonNls final String path = VfsUtilCore.pathToUrl(filePath.replace(File.separatorChar, '/')); - return ApplicationManager.getApplication().runReadAction(new Computable() { - @Nullable - public VirtualFile compute() { - return VirtualFileManager.getInstance().findFileByUrl(path); - } - }); + return ApplicationManager.getApplication() + .runReadAction((Computable)() -> VirtualFileManager.getInstance().findFileByUrl(path)); } @Nullable @@ -597,13 +577,9 @@ public class SvnUtil { public static boolean remoteFolderIsEmpty(@NotNull SvnVcs vcs, @NotNull String url) throws VcsException { SvnTarget target = SvnTarget.fromURL(createUrl(url)); Ref result = new Ref<>(true); - DirectoryEntryConsumer handler = new DirectoryEntryConsumer() { - - @Override - public void consume(final DirectoryEntry entry) throws SVNException { - if (entry != null) { - result.set(false); - } + DirectoryEntryConsumer handler = entry -> { + if (entry != null) { + result.set(false); } }; @@ -990,15 +966,13 @@ public class SvnUtil { String result = ""; try { - result = (String)runSynchronized(new ISqlJetEngineSynchronized() { - public Object runSynchronized(SqlJetEngine engine) throws SqlJetException { - btree.enter(); - try { - return readDbSchema(); - } - finally { - btree.leave(); - } + result = (String)runSynchronized(engine -> { + btree.enter(); + try { + return readDbSchema(); + } + finally { + btree.leave(); } }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java index d15ba352fc21..2eb16a31b5a5 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnVcs.java @@ -185,12 +185,7 @@ public class SvnVcs extends AbstractVcs { myChangeListListener = new SvnChangelistListener(this); - myVcsListener = new VcsListener() { - @Override - public void directoryMappingChanged() { - invokeRefreshSvnRoots(); - } - }; + myVcsListener = () -> invokeRefreshSvnRoots(); } myFrameStateListener = project.isDefault() ? null : new MyFrameStateListener(ChangeListManager.getInstance(project), @@ -205,12 +200,9 @@ public class SvnVcs extends AbstractVcs { if (myProject.isDefault()) return; myCopiesRefreshManager = new SvnCopiesRefreshManager((SvnFileUrlMappingImpl)getSvnFileUrlMapping()); if (!myConfiguration.isCleanupRun()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - cleanup17copies(); - myConfiguration.setCleanupRun(true); - } + ApplicationManager.getApplication().invokeLater(() -> { + cleanup17copies(); + myConfiguration.setCleanupRun(true); }, ModalityState.NON_MODAL, myProject.getDisposed()); } else { @@ -261,26 +253,23 @@ public class SvnVcs extends AbstractVcs { private void upgradeIfNeeded(final MessageBus bus) { final MessageBusConnection connection = bus.connect(); - connection.subscribe(ChangeListManagerImpl.LISTS_LOADED, new LocalChangeListsLoadedListener() { - @Override - public void processLoadedLists(final List lists) { - if (lists.isEmpty()) return; - try { - ChangeListManager.getInstance(myProject).setReadOnly(LocalChangeList.DEFAULT_NAME, true); + connection.subscribe(ChangeListManagerImpl.LISTS_LOADED, lists -> { + if (lists.isEmpty()) return; + try { + ChangeListManager.getInstance(myProject).setReadOnly(LocalChangeList.DEFAULT_NAME, true); - if (!myConfiguration.changeListsSynchronized()) { - processChangeLists(lists); - } + if (!myConfiguration.changeListsSynchronized()) { + processChangeLists(lists); } - catch (ProcessCanceledException e) { - // - } - finally { - myConfiguration.upgrade(); - } - - connection.disconnect(); } + catch (ProcessCanceledException e) { + // + } + finally { + myConfiguration.upgrade(); + } + + connection.disconnect(); }); } @@ -301,12 +290,7 @@ public class SvnVcs extends AbstractVcs { finally { final Application appManager = ApplicationManager.getApplication(); if (appManager.isDispatchThread()) { - appManager.executeOnPooledThread(new Runnable() { - @Override - public void run() { - plVcsManager.stopBackgroundVcsOperation(); - } - }); + appManager.executeOnPooledThread(() -> plVcsManager.stopBackgroundVcsOperation()); } else { plVcsManager.stopBackgroundVcsOperation(); @@ -356,24 +340,21 @@ public class SvnVcs extends AbstractVcs { } // do one time after project loaded - StartupManager.getInstance(myProject).runWhenProjectIsInitialized(new DumbAwareRunnable() { - @Override - public void run() { - postStartup(); + StartupManager.getInstance(myProject).runWhenProjectIsInitialized((DumbAwareRunnable)() -> { + postStartup(); - // for IDEA, it takes 2 minutes - and anyway this can be done in background, no sense... - // once it could be mistaken about copies for 2 minutes on start... + // for IDEA, it takes 2 minutes - and anyway this can be done in background, no sense... + // once it could be mistaken about copies for 2 minutes on start... - /*if (! myMapping.getAllWcInfos().isEmpty()) { - invokeRefreshSvnRoots(); - return; - } - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - myCopiesRefreshManager.getCopiesRefresh().ensureInit(); - } - }, SvnBundle.message("refreshing.working.copies.roots.progress.text"), true, myProject);*/ + /*if (! myMapping.getAllWcInfos().isEmpty()) { + invokeRefreshSvnRoots(); + return; } + ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { + public void run() { + myCopiesRefreshManager.getCopiesRefresh().ensureInit(); + } + }, SvnBundle.message("refreshing.working.copies.roots.progress.text"), true, myProject);*/ }); myProject.getMessageBus().connect().subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, myRootsToWorkingCopies); @@ -818,12 +799,7 @@ public class SvnVcs extends AbstractVcs { infos.add(new MyPair<>(vf, url.toString(), s)); } final List> filtered = new UniqueRootsFilter().filter(infos); - final List converted = ObjectsConvertor.convert(filtered, new Convertor, S>() { - @Override - public S convert(final MyPair o) { - return o.getSrc(); - } - }); + final List converted = ObjectsConvertor.convert(filtered, o -> o.getSrc()); if (!notMatched.isEmpty()) { // potential bug is here: order is not kept. but seems it only occurs for cases where result is sorted after filtering so ok converted.addAll(notMatched); @@ -917,10 +893,10 @@ public class SvnVcs extends AbstractVcs { /** * Detects appropriate client factory based on project root directory working copy format. - * + *

* Try to avoid usages of this method (for now) as it could not correctly for all cases * detect svn 1.8 working copy format to guarantee command line client. - * + *

* For instance, when working copies of several formats are presented in project * (though it seems to be rather unlikely case). * diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnWriteOperationLocks.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnWriteOperationLocks.java deleted file mode 100644 index d7222b83f1af..000000000000 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/SvnWriteOperationLocks.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.idea.svn; - -import com.intellij.openapi.vcs.changes.ChangesUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.vcsUtil.VcsUtil; -import org.tmatesoft.svn.core.SVNErrorCode; -import org.tmatesoft.svn.core.SVNErrorMessage; -import org.tmatesoft.svn.core.SVNException; - -import java.io.File; - -/** - * Created with IntelliJ IDEA. - * User: Irina.Chernushina - * Date: 10/23/12 - * Time: 2:29 PM - */ -// TODO: Such locking functionality is not required anymore. Likely to be removed. -public class SvnWriteOperationLocks extends SvnAbstractWriteOperationLocks { - private final RootsToWorkingCopies myRootsToWorkingCopies; - - public SvnWriteOperationLocks(RootsToWorkingCopies rootsToWorkingCopies) { - super(1000); - myRootsToWorkingCopies = rootsToWorkingCopies; - } - - protected WorkingCopy getCopy(File file, boolean directory) throws SVNException { - final VirtualFile parentOrSelf = ChangesUtil.findValidParentAccurately(VcsUtil.getFilePath(file, directory)); - final WorkingCopy wcRoot = myRootsToWorkingCopies.getWcRoot(parentOrSelf); - if (wcRoot == null) { - throw new SVNException(SVNErrorMessage.create(directory ? SVNErrorCode.WC_NOT_WORKING_COPY : SVNErrorCode.WC_NOT_FILE)); - } - // todo check about externals! - return wcRoot; - } -} diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/UniqueRootsFilter.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/UniqueRootsFilter.java index 07883a64b098..6a77750a14d8 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/UniqueRootsFilter.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/UniqueRootsFilter.java @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.svn; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; @@ -24,7 +23,6 @@ import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.List; /** @@ -46,20 +44,11 @@ public class UniqueRootsFilter { } private static void sort(List list) { - Collections.sort(list, new Comparator() { - public int compare(final RootUrlPair o1, final RootUrlPair o2) { - return o1.getVirtualFile().getPath().compareTo(o2.getVirtualFile().getPath()); - } - }); + Collections.sort(list, (o1, o2) -> o1.getVirtualFile().getPath().compareTo(o2.getVirtualFile().getPath())); } private static boolean alreadyRegistered(@NotNull final T child, @NotNull List registered) { - return ContainerUtil.exists(registered, new Condition() { - @Override - public boolean value(T parent) { - return isSamePath(child, parent) || isSameSupposedUrl(child, parent); - } - }); + return ContainerUtil.exists(registered, parent -> isSamePath(child, parent) || isSameSupposedUrl(child, parent)); } private static boolean isSamePath(@NotNull T child, @NotNull T parent) { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/BasicAction.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/BasicAction.java index 4d9cfab16658..fe1ddc7c0e2e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/BasicAction.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/BasicAction.java @@ -27,7 +27,6 @@ import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.AbstractVcsHelper; import com.intellij.openapi.vcs.ProjectLevelVcsManager; -import com.intellij.openapi.vcs.TransactionRunnable; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vfs.VirtualFile; @@ -59,24 +58,22 @@ public abstract class BasicAction extends AnAction implements DumbAware { AbstractVcsHelper helper = AbstractVcsHelper.getInstance(project); try { - List exceptions = helper.runTransactionRunnable(vcs, new TransactionRunnable() { - public void run(List exceptions) { - VirtualFile badFile = null; - try { - if (isBatchAction()) { - batchExecute(vcs, files, e.getDataContext()); - } - else { - for (VirtualFile file : files) { - badFile = file; - execute(vcs, file, e.getDataContext()); - } + List exceptions = helper.runTransactionRunnable(vcs, exceptionList -> { + VirtualFile badFile = null; + try { + if (isBatchAction()) { + batchExecute(vcs, files, e.getDataContext()); + } + else { + for (VirtualFile file : files) { + badFile = file; + execute(vcs, file, e.getDataContext()); } } - catch (VcsException ex) { - ex.setVirtualFile(badFile); - exceptions.add(ex); - } + } + catch (VcsException ex) { + ex.setVirtualFile(badFile); + exceptionList.add(ex); } }, null); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/ExclusiveBackgroundVcsAction.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/ExclusiveBackgroundVcsAction.java index a01b60a1c98d..82181e37ffc6 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/ExclusiveBackgroundVcsAction.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/ExclusiveBackgroundVcsAction.java @@ -32,11 +32,7 @@ public class ExclusiveBackgroundVcsAction { } finally { final Application application = ApplicationManager.getApplication(); if (application.isDispatchThread()) { - application.executeOnPooledThread(new Runnable() { - public void run() { - plVcsManager.stopBackgroundVcsOperation(); - } - }); + application.executeOnPooledThread(() -> plVcsManager.stopBackgroundVcsOperation()); } else { plVcsManager.stopBackgroundVcsOperation(); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/MarkResolvedAction.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/MarkResolvedAction.java index 90a7b03da1f9..0d4095aed659 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/MarkResolvedAction.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/MarkResolvedAction.java @@ -35,9 +35,7 @@ import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.commandLine.SvnBindException; import org.jetbrains.idea.svn.conflict.ConflictClient; import org.jetbrains.idea.svn.dialogs.SelectFilesDialog; -import org.jetbrains.idea.svn.status.Status; import org.jetbrains.idea.svn.status.StatusClient; -import org.jetbrains.idea.svn.status.StatusConsumer; import org.jetbrains.idea.svn.status.StatusType; import org.tmatesoft.svn.core.wc.SVNRevision; @@ -127,13 +125,10 @@ public class MarkResolvedAction extends BasicAction { File path = VfsUtilCore.virtualToIoFile(file); StatusClient client = vcs.getFactory(path).createStatusClient(); - client.doStatus(path, SVNRevision.UNDEFINED, Depth.INFINITY, false, false, false, false, new StatusConsumer() { - @Override - public void consume(@NotNull Status status) { - if (status.getContentsStatus() == StatusType.STATUS_CONFLICTED || - status.getPropertiesStatus() == StatusType.STATUS_CONFLICTED) { - result.add(status.getFile().getAbsolutePath()); - } + client.doStatus(path, SVNRevision.UNDEFINED, Depth.INFINITY, false, false, false, false, status -> { + if (status.getContentsStatus() == StatusType.STATUS_CONFLICTED || + status.getPropertiesStatus() == StatusType.STATUS_CONFLICTED) { + result.add(status.getFile().getAbsolutePath()); } }, null); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/ShareWholeProject.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/ShareWholeProject.java index 8aaf8a3548b1..6ec9ef7cd2d6 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/ShareWholeProject.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/ShareWholeProject.java @@ -42,7 +42,7 @@ public class ShareWholeProject extends AnAction implements DumbAware { final Presentation presentation = e.getPresentation(); presentation.setEnabled(checker.isEnabled()); - + presentation.setVisible(checker.isVisible()); if (checker.isEnabled()) { presentation.setText(SvnBundle.message("action.share.whole.project.text")); @@ -73,19 +73,20 @@ public class ShareWholeProject extends AnAction implements DumbAware { myHadNoMappings = MyCheckResult.notMapped.equals(result); if (MyCheckResult.notMapped.equals(result)) { // no change list manager working - if(SvnUtil.seemsLikeVersionedDir(baseDir)) return; - } else if (SvnStatusUtil.isUnderControl(myProject, baseDir)) { + if (SvnUtil.seemsLikeVersionedDir(baseDir)) return; + } + else if (SvnStatusUtil.isUnderControl(myProject, baseDir)) { return; } - if ((! myHadNoMappings) && (! SvnVcs.getInstance(myProject).getSvnFileUrlMapping().isEmpty())) { + if ((!myHadNoMappings) && (!SvnVcs.getInstance(myProject).getSvnFileUrlMapping().isEmpty())) { // there are some versioned dirs under project dir return; } // visible: already checked above myVisible = true; - myEnabled = (! vcsManager.isBackgroundVcsOperationRunning()); + myEnabled = (!vcsManager.isBackgroundVcsOperationRunning()); } private static enum MyCheckResult { @@ -137,7 +138,7 @@ public class ShareWholeProject extends AnAction implements DumbAware { public void actionPerformed(AnActionEvent e) { final MyChecker checker = new MyChecker(); checker.execute(e); - if (! checker.isEnabled()) return; + if (!checker.isEnabled()) return; final Project project = checker.getProject(); final VirtualFile baseDir = project.getBaseDir(); @@ -146,26 +147,21 @@ public class ShareWholeProject extends AnAction implements DumbAware { boolean excThrown = false; try { success = ShareProjectAction.share(project, baseDir); - } catch (VcsException exc) { + } + catch (VcsException exc) { AbstractVcsHelper.getInstance(project).showError(exc, "Failed to Share Project"); excThrown = true; - } finally { + } + finally { // if success = false -> either action was cancelled or exception was thrown, so also check for exception if (success || excThrown) { - baseDir.refresh(true, true, new Runnable() { - public void run() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - VcsDirtyScopeManager.getInstance(project).dirDirtyRecursively(project.getBaseDir()); - if (checker.isHadNoMappings() && SvnUtil.seemsLikeVersionedDir(baseDir)) { - final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project); - vcsManager.setDirectoryMappings(Arrays.asList(new VcsDirectoryMapping("", SvnVcs.VCS_NAME))); - } - } - }, ModalityState.NON_MODAL, project.getDisposed()); + baseDir.refresh(true, true, () -> ApplicationManager.getApplication().invokeLater(() -> { + VcsDirtyScopeManager.getInstance(project).dirDirtyRecursively(project.getBaseDir()); + if (checker.isHadNoMappings() && SvnUtil.seemsLikeVersionedDir(baseDir)) { + final ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project); + vcsManager.setDirectoryMappings(Arrays.asList(new VcsDirectoryMapping("", SvnVcs.VCS_NAME))); } - }); + }, ModalityState.NON_MODAL, project.getDisposed())); } } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/SvnExcludingIgnoredOperation.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/SvnExcludingIgnoredOperation.java index 94fc2e11c96e..332e4eb582c0 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/SvnExcludingIgnoredOperation.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/SvnExcludingIgnoredOperation.java @@ -67,12 +67,7 @@ public class SvnExcludingIgnoredOperation { } private boolean isIgnoredByVcs(final VirtualFile file) { - return ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public Boolean compute() { - return myVcsManager.isIgnored(file); - } - }); + return ApplicationManager.getApplication().runReadAction((Computable)() -> myVcsManager.isIgnored(file)); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/SvnMergeProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/SvnMergeProvider.java index 86f3b3c68c37..023dc39f1edb 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/SvnMergeProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/SvnMergeProvider.java @@ -58,53 +58,53 @@ public class SvnMergeProvider implements MergeProvider { @NotNull public MergeData loadRevisions(@NotNull final VirtualFile file) throws VcsException { final MergeData data = new MergeData(); - VcsRunnable runnable = new VcsRunnable() { - public void run() throws VcsException { - File oldFile = null; - File newFile = null; - File workingFile = null; - boolean mergeCase = false; - SvnVcs vcs = SvnVcs.getInstance(myProject); - Info info = vcs.getInfo(file); + VcsRunnable runnable = () -> { + File oldFile = null; + File newFile = null; + File workingFile = null; + boolean mergeCase = false; + SvnVcs vcs = SvnVcs.getInstance(myProject); + Info info = vcs.getInfo(file); - if (info != null) { - oldFile = info.getConflictOldFile(); - newFile = info.getConflictNewFile(); - workingFile = info.getConflictWrkFile(); - mergeCase = workingFile == null || workingFile.getName().contains("working"); - // for debug - if (workingFile == null) { - LOG.info("Null working file when merging text conflict for " + file.getPath() + " old file: " + oldFile + " new file: " + newFile); - } - if (mergeCase) { - // this is merge case - oldFile = info.getConflictNewFile(); - newFile = info.getConflictOldFile(); - workingFile = info.getConflictWrkFile(); - } - data.LAST_REVISION_NUMBER = new SvnRevisionNumber(info.getRevision()); - } else { - throw new VcsException("Could not get info for " + file.getPath()); - } - if (oldFile == null || newFile == null || workingFile == null) { - ByteArrayOutputStream bos = getBaseRevisionContents(vcs, file); - data.ORIGINAL = bos.toByteArray(); - data.LAST = bos.toByteArray(); - data.CURRENT = readFile(new File(file.getPath())); - } - else { - data.ORIGINAL = readFile(oldFile); - data.LAST = readFile(newFile); - data.CURRENT = readFile(workingFile); + if (info != null) { + oldFile = info.getConflictOldFile(); + newFile = info.getConflictNewFile(); + workingFile = info.getConflictWrkFile(); + mergeCase = workingFile == null || workingFile.getName().contains("working"); + // for debug + if (workingFile == null) { + LOG + .info("Null working file when merging text conflict for " + file.getPath() + " old file: " + oldFile + " new file: " + newFile); } if (mergeCase) { - final ByteArrayOutputStream contents = getBaseRevisionContents(vcs, file); - if (! Arrays.equals(contents.toByteArray(), data.ORIGINAL)) { - // swap base and server: another order of merge arguments - byte[] original = data.ORIGINAL; - data.ORIGINAL = data.LAST; - data.LAST = original; - } + // this is merge case + oldFile = info.getConflictNewFile(); + newFile = info.getConflictOldFile(); + workingFile = info.getConflictWrkFile(); + } + data.LAST_REVISION_NUMBER = new SvnRevisionNumber(info.getRevision()); + } + else { + throw new VcsException("Could not get info for " + file.getPath()); + } + if (oldFile == null || newFile == null || workingFile == null) { + ByteArrayOutputStream bos = getBaseRevisionContents(vcs, file); + data.ORIGINAL = bos.toByteArray(); + data.LAST = bos.toByteArray(); + data.CURRENT = readFile(new File(file.getPath())); + } + else { + data.ORIGINAL = readFile(oldFile); + data.LAST = readFile(newFile); + data.CURRENT = readFile(workingFile); + } + if (mergeCase) { + final ByteArrayOutputStream contents = getBaseRevisionContents(vcs, file); + if (!Arrays.equals(contents.toByteArray(), data.ORIGINAL)) { + // swap base and server: another order of merge arguments + byte[] original = data.ORIGINAL; + data.ORIGINAL = data.LAST; + data.LAST = original; } } }; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/BaseSvnFileAnnotation.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/BaseSvnFileAnnotation.java index bd489101ca75..8368c3b5f640 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/BaseSvnFileAnnotation.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/BaseSvnFileAnnotation.java @@ -176,11 +176,7 @@ public abstract class BaseSvnFileAnnotation extends FileAnnotation { public List getRevisions() { final List result = new ArrayList<>(myRevisionMap.values()); - Collections.sort(result, new Comparator() { - public int compare(final VcsFileRevision o1, final VcsFileRevision o2) { - return o2.getRevisionNumber().compareTo(o1.getRevisionNumber()); - } - }); + Collections.sort(result, (o1, o2) -> o2.getRevisionNumber().compareTo(o1.getRevisionNumber())); return result; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/SvnAnnotationProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/SvnAnnotationProvider.java index bc59f8d41269..9eb9e4cd1b3b 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/SvnAnnotationProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/annotate/SvnAnnotationProvider.java @@ -35,9 +35,10 @@ import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.*; -import org.jetbrains.idea.svn.checkin.CommitInfo; import org.jetbrains.idea.svn.diff.DiffOptions; -import org.jetbrains.idea.svn.history.*; +import org.jetbrains.idea.svn.history.HistoryClient; +import org.jetbrains.idea.svn.history.SvnChangeList; +import org.jetbrains.idea.svn.history.SvnFileRevision; import org.jetbrains.idea.svn.info.Info; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; @@ -70,8 +71,9 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn throw new VcsException("Can not get current revision for file " + file.getPath()); } final SVNRevision svnRevision = ((SvnRevisionNumber)lastChangedRevision.getRevisionNumber()).getRevision(); - if (! svnRevision.isValid()) { - throw new VcsException("Can not get last changed revision for file: " + file.getPath() + "\nPlease run svn info for this file and file an issue."); + if (!svnRevision.isValid()) { + throw new VcsException( + "Can not get last changed revision for file: " + file.getPath() + "\nPlease run svn info for this file and file an issue."); } return annotate(file, new SvnFileRevision(myVcs, currentRevision, currentRevision, null, null, null, null, null), lastChangedRevision.getRevisionNumber(), true); @@ -89,78 +91,80 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn final FileAnnotation[] annotation = new FileAnnotation[1]; final VcsException[] exception = new VcsException[1]; - Runnable command = new Runnable() { - public void run() { - final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - final File ioFile = new File(file.getPath()).getAbsoluteFile(); - Info info = null; - try { + Runnable command = () -> { + final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + final File ioFile = new File(file.getPath()).getAbsoluteFile(); + Info info = null; + try { - final String contents; - if (loadExternally) { - byte[] data = SvnUtil.getFileContents(myVcs, SvnTarget.fromFile(ioFile), SVNRevision.BASE, SVNRevision.UNDEFINED); - contents = LoadTextUtil.getTextByBinaryPresentation(data, file, false, false).toString(); - } else { - final byte[] bytes = VcsHistoryUtil.loadRevisionContent(revision); - contents = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false).toString(); - } - - final SvnFileAnnotation result = new SvnFileAnnotation(myVcs, file, contents, lastChangedRevision); - - info = myVcs.getInfo(ioFile); - if (info == null) { - exception[0] = new VcsException(new SVNException(SVNErrorMessage.create(SVNErrorCode.UNKNOWN, "File ''{0}'' is not under version control", ioFile))); - return; - } - final String url = info.getURL() == null ? null : info.getURL().toString(); - - SVNRevision endRevision = ((SvnFileRevision) revision).getRevision(); - if (SVNRevision.WORKING.equals(endRevision)) { - endRevision = info.getRevision(); - } - if (progress != null) { - progress.setText(SvnBundle.message("progress.text.computing.annotation", file.getName())); - } - - // ignore mime type=true : IDEA-19562 - final AnnotationConsumer annotateHandler = createAnnotationHandler(progress, result); - - boolean calculateMergeinfo = - myVcs.getSvnConfiguration().isShowMergeSourcesInAnnotate() && SvnUtil.checkRepositoryVersion15(myVcs, url); - final MySteppedLogGetter logGetter = new MySteppedLogGetter( - myVcs, ioFile, progress, - myVcs.getFactory(ioFile).createHistoryClient(), endRevision, result, - url, calculateMergeinfo, file.getCharset()); - - logGetter.go(); - final LinkedList rp = logGetter.getRevisionPoints(); - - // TODO: only 2 elements will be in rp and for loop will be executed only once - probably rewrite with Pair - AnnotateClient annotateClient = myVcs.getFactory(ioFile).createAnnotateClient(); - for (int i = 0; i < rp.size() - 1; i++) { - annotateClient.annotate(SvnTarget.fromFile(ioFile), rp.get(i + 1), rp.get(i), calculateMergeinfo, getLogClientOptions(myVcs), - annotateHandler); - } - - if (rp.get(1).getNumber() > 0) { - result.setFirstRevision(rp.get(1)); - } - annotation[0] = result; + final String contents; + if (loadExternally) { + byte[] data = SvnUtil.getFileContents(myVcs, SvnTarget.fromFile(ioFile), SVNRevision.BASE, SVNRevision.UNDEFINED); + contents = LoadTextUtil.getTextByBinaryPresentation(data, file, false, false).toString(); } - catch (IOException e) { - exception[0] = new VcsException(e); - } catch (VcsException e) { - if (e.getCause() instanceof SVNException) { - handleSvnException(ioFile, info, (SVNException)e.getCause(), file, revision, annotation, exception); - } - else { - exception[0] = e; - } + else { + final byte[] bytes = VcsHistoryUtil.loadRevisionContent(revision); + contents = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false).toString(); + } + + final SvnFileAnnotation result = new SvnFileAnnotation(myVcs, file, contents, lastChangedRevision); + + info = myVcs.getInfo(ioFile); + if (info == null) { + exception[0] = new VcsException( + new SVNException(SVNErrorMessage.create(SVNErrorCode.UNKNOWN, "File ''{0}'' is not under version control", ioFile))); + return; + } + final String url = info.getURL() == null ? null : info.getURL().toString(); + + SVNRevision endRevision = ((SvnFileRevision)revision).getRevision(); + if (SVNRevision.WORKING.equals(endRevision)) { + endRevision = info.getRevision(); + } + if (progress != null) { + progress.setText(SvnBundle.message("progress.text.computing.annotation", file.getName())); + } + + // ignore mime type=true : IDEA-19562 + final AnnotationConsumer annotateHandler = createAnnotationHandler(progress, result); + + boolean calculateMergeinfo = + myVcs.getSvnConfiguration().isShowMergeSourcesInAnnotate() && SvnUtil.checkRepositoryVersion15(myVcs, url); + final MySteppedLogGetter logGetter = new MySteppedLogGetter( + myVcs, ioFile, progress, + myVcs.getFactory(ioFile).createHistoryClient(), endRevision, result, + url, calculateMergeinfo, file.getCharset()); + + logGetter.go(); + final LinkedList rp = logGetter.getRevisionPoints(); + + // TODO: only 2 elements will be in rp and for loop will be executed only once - probably rewrite with Pair + AnnotateClient annotateClient = myVcs.getFactory(ioFile).createAnnotateClient(); + for (int i = 0; i < rp.size() - 1; i++) { + annotateClient.annotate(SvnTarget.fromFile(ioFile), rp.get(i + 1), rp.get(i), calculateMergeinfo, getLogClientOptions(myVcs), + annotateHandler); + } + + if (rp.get(1).getNumber() > 0) { + result.setFirstRevision(rp.get(1)); + } + annotation[0] = result; + } + catch (IOException e) { + exception[0] = new VcsException(e); + } + catch (VcsException e) { + if (e.getCause() instanceof SVNException) { + handleSvnException(ioFile, info, (SVNException)e.getCause(), file, revision, annotation, exception); + } + else { + exception[0] = e; } } }; if (ApplicationManager.getApplication().isDispatchThread()) { - ProgressManager.getInstance().runProcessWithProgressSynchronously(command, SvnBundle.message("action.text.annotate"), false, myVcs.getProject()); + ProgressManager.getInstance() + .runProcessWithProgressSynchronously(command, SvnBundle.message("action.text.annotate"), false, myVcs.getProject()); } else { command.run(); @@ -179,10 +183,10 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn FileAnnotation[] annotation, VcsException[] exception) { // TODO: Check how this scenario could be reproduced by user and what changes needs to be done for command line client if (SVNErrorCode.FS_NOT_FOUND.equals(e.getErrorMessage().getErrorCode())) { - final CommittedChangesProvider provider = myVcs.getCommittedChangesProvider(); + final CommittedChangesProvider provider = myVcs.getCommittedChangesProvider(); try { final Pair pair = provider.getOneList(file, revision.getRevisionNumber()); - if (pair != null && info != null && pair.getSecond() != null && ! Comparing.equal(pair.getSecond().getIOFile(), ioFile)) { + if (pair != null && info != null && pair.getSecond() != null && !Comparing.equal(pair.getSecond().getIOFile(), ioFile)) { annotation[0] = annotateNonExisting(pair, revision, info, file.getCharset(), file); return; } @@ -205,19 +209,21 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn final List parts2 = StringUtil.split(can2.getPath(), File.separator, true); int cnt = 0; while (parts1.size() > cnt && parts2.size() > cnt) { - if (! parts1.get(cnt).equals(parts2.get(cnt))) { + if (!parts1.get(cnt).equals(parts2.get(cnt))) { if (cnt > 0) { return new File(StringUtil.join(parts1.subList(0, cnt), File.separator)); - } else { + } + else { return null; } } - ++ cnt; + ++cnt; } //shorter one if (parts1.size() > parts2.size()) { return file2; - } else { + } + else { return file1; } } @@ -225,28 +231,34 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn private SvnRemoteFileAnnotation annotateNonExisting(Pair pair, VcsFileRevision revision, Info info, - Charset charset, final VirtualFile current) throws VcsException, SVNException, IOException { + Charset charset, final VirtualFile current) + throws VcsException, SVNException, IOException { final File wasFile = pair.getSecond().getIOFile(); final File root = getCommonAncestor(wasFile, info.getFile()); - if (root == null) throw new VcsException("Can not find relative path for " + wasFile.getPath() + "@" + revision.getRevisionNumber().asString()); + if (root == null) { + throw new VcsException("Can not find relative path for " + wasFile.getPath() + "@" + revision.getRevisionNumber().asString()); + } final String relativePath = FileUtil.getRelativePath(root.getPath(), wasFile.getPath(), File.separatorChar); - if (relativePath == null) throw new VcsException("Can not find relative path for " + wasFile.getPath() + "@" + revision.getRevisionNumber().asString()); + if (relativePath == null) { + throw new VcsException("Can not find relative path for " + wasFile.getPath() + "@" + revision.getRevisionNumber().asString()); + } Info wcRootInfo = myVcs.getInfo(root); if (wcRootInfo == null || wcRootInfo.getURL() == null) { - throw new VcsException("Can not find relative path for " + wasFile.getPath() + "@" + revision.getRevisionNumber().asString()); + throw new VcsException("Can not find relative path for " + wasFile.getPath() + "@" + revision.getRevisionNumber().asString()); } SVNURL wasUrl = wcRootInfo.getURL(); - final String[] strings = relativePath.replace('\\','/').split("/"); + final String[] strings = relativePath.replace('\\', '/').split("/"); for (String string : strings) { wasUrl = wasUrl.appendPath(string, true); } final SVNRevision svnRevision = ((SvnRevisionNumber)revision.getRevisionNumber()).getRevision(); byte[] data = SvnUtil.getFileContents(myVcs, SvnTarget.fromURL(wasUrl), svnRevision, svnRevision); - final String contents = LoadTextUtil.getTextByBinaryPresentation(data, charset == null ? CharsetToolkit.UTF8_CHARSET : charset).toString(); + final String contents = + LoadTextUtil.getTextByBinaryPresentation(data, charset == null ? CharsetToolkit.UTF8_CHARSET : charset).toString(); final SvnRemoteFileAnnotation result = new SvnRemoteFileAnnotation(myVcs, contents, revision.getRevisionNumber(), current); final AnnotationConsumer annotateHandler = createAnnotationHandler(ProgressManager.getInstance().getProgressIndicator(), result); @@ -262,23 +274,19 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn @NotNull private static AnnotationConsumer createAnnotationHandler(@Nullable final ProgressIndicator progress, @NotNull final BaseSvnFileAnnotation result) { - return new AnnotationConsumer() { - - @Override - public void consume(int lineNumber, @NotNull CommitInfo info, @Nullable CommitInfo mergeInfo) throws SVNException { - if (progress != null) { - progress.checkCanceled(); - } - - result.setLineInfo(lineNumber, info, mergeInfo != null && info.getRevision() > mergeInfo.getRevision() ? mergeInfo : null); + return (lineNumber, info, mergeInfo) -> { + if (progress != null) { + progress.checkCanceled(); } + + result.setLineInfo(lineNumber, info, mergeInfo != null && info.getRevision() > mergeInfo.getRevision() ? mergeInfo : null); }; } @Override public VcsAnnotation createCacheable(FileAnnotation fileAnnotation) { - if (! (fileAnnotation instanceof SvnFileAnnotation)) return null; - final SvnFileAnnotation svnFileAnnotation = (SvnFileAnnotation) fileAnnotation; + if (!(fileAnnotation instanceof SvnFileAnnotation)) return null; + final SvnFileAnnotation svnFileAnnotation = (SvnFileAnnotation)fileAnnotation; final AnnotationSourceSwitcher annotationSourceSwitcher = svnFileAnnotation.getAnnotationSourceSwitcher(); if (annotationSourceSwitcher != null) { annotationSourceSwitcher.switchTo(AnnotationSource.LOCAL); @@ -288,7 +296,7 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn final VcsUsualLineAnnotationData lineAnnotationData = new VcsUsualLineAnnotationData(size); for (int i = 0; i < size; i++) { final VcsRevisionNumber revisionNumber = svnFileAnnotation.getLineRevisionNumber(i); - lineAnnotationData.put(i, revisionNumber); + lineAnnotationData.put(i, revisionNumber); } final VcsAnnotation vcsAnnotation = new VcsAnnotation(VcsUtil.getFilePath(svnFileAnnotation.getFile()), lineAnnotationData, @@ -304,10 +312,10 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn final VcsRevisionNumber number = svnFileAnnotation.getLineRevisionNumber(i); if (number == null) continue; merged.put(i, number); - addMap.put(number, svnFileAnnotation.getRevision(((SvnRevisionNumber) number).getRevision().getNumber())); + addMap.put(number, svnFileAnnotation.getRevision(((SvnRevisionNumber)number).getRevision().getNumber())); } } - if (! merged.isEmpty()) { + if (!merged.isEmpty()) { vcsAnnotation.addAnnotation(MERGED_KEY, merged); vcsAnnotation.addCachedOtherRevisions(addMap); } @@ -326,7 +334,7 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn new SvnFileAnnotation(myVcs, vcsAnnotation.getFilePath().getVirtualFile(), annotatedContent, revisionNumber); final VcsLineAnnotationData basicAnnotation = vcsAnnotation.getBasicAnnotation(); final VcsLineAnnotationData data = vcsAnnotation.getAdditionalAnnotations().get(MERGED_KEY); - final Map historyAsMap = session.getHistoryAsMap(); + final Map historyAsMap = session.getHistoryAsMap(); final Map cachedOtherRevisions = vcsAnnotation.getCachedOtherRevisions(); for (int i = 0; i < basicAnnotation.getNumLines(); i++) { @@ -337,17 +345,18 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn if (mergedData == null) { annotation.setLineInfo(i, fileRevision.getCommitInfo(), null); - } else { + } + else { final SvnFileRevision mergedRevision = (SvnFileRevision)cachedOtherRevisions.get(mergedData); if (mergedRevision == null) return null; annotation.setLineInfo(i, fileRevision.getCommitInfo(), mergedRevision.getCommitInfo()); } } if (vcsAnnotation.getFirstRevision() != null) { - annotation.setFirstRevision(((SvnRevisionNumber) vcsAnnotation.getFirstRevision()).getRevision()); + annotation.setFirstRevision(((SvnRevisionNumber)vcsAnnotation.getFirstRevision()).getRevision()); } for (VcsFileRevision revision : session.getRevisionList()) { - annotation.setRevision(((SvnRevisionNumber) revision.getRevisionNumber()).getRevision().getNumber(), (SvnFileRevision)revision); + annotation.setRevision(((SvnRevisionNumber)revision.getRevisionNumber()).getRevision().getNumber(), (SvnFileRevision)revision); } return annotation; } @@ -387,16 +396,18 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn boolean longHistory = true; if (maxAnnotateRevisions == -1) { longHistory = false; - } else { + } + else { if (myEndRevision.getNumber() < maxAnnotateRevisions) { longHistory = false; } } - if (! longHistory) { + if (!longHistory) { doLog(myCalculateMergeinfo, null, 0); putDefaultBounds(); - } else { + } + else { doLog(false, null, 0); final List fileRevisionList = myResult.getRevisions(); if (fileRevisionList.size() < maxAnnotateRevisions) { @@ -407,7 +418,7 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn return; } - myRevisionPoints.add(((SvnRevisionNumber) fileRevisionList.get(0).getRevisionNumber()).getRevision()); + myRevisionPoints.add(((SvnRevisionNumber)fileRevisionList.get(0).getRevisionNumber()).getRevision()); final SVNRevision truncateTo = ((SvnRevisionNumber)fileRevisionList.get(maxAnnotateRevisions - 1).getRevisionNumber()).getRevision(); myRevisionPoints.add(truncateTo); @@ -427,19 +438,17 @@ public class SvnAnnotationProvider implements AnnotationProvider, VcsCacheableAn private void doLog(final boolean includeMerged, final SVNRevision truncateTo, final int max) throws VcsException { myClient.doLog(SvnTarget.fromFile(myIoFile), myEndRevision, truncateTo == null ? SVNRevision.create(1L) : truncateTo, false, false, includeMerged, max, null, - new LogEntryConsumer() { - @Override - public void consume(LogEntry logEntry) { - if (SVNRevision.UNDEFINED.getNumber() == logEntry.getRevision()) { - return; - } - - if (myProgress != null) { - myProgress.checkCanceled(); - myProgress.setText2(SvnBundle.message("progress.text2.revision.processed", logEntry.getRevision())); - } - myResult.setRevision(logEntry.getRevision(), new SvnFileRevision(myVcs, SVNRevision.UNDEFINED, logEntry, myUrl, "")); + logEntry -> { + if (SVNRevision.UNDEFINED.getNumber() == logEntry.getRevision()) { + return; } + + if (myProgress != null) { + myProgress.checkCanceled(); + myProgress.setText2(SvnBundle.message("progress.text2.revision.processed", logEntry.getRevision())); + } + myResult + .setRevision(logEntry.getRevision(), new SvnFileRevision(myVcs, SVNRevision.UNDEFINED, logEntry, myUrl, "")); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/AuthenticationService.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/AuthenticationService.java index 84f67da2a3cb..7a739a1315f8 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/AuthenticationService.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/AuthenticationService.java @@ -105,13 +105,8 @@ public class AuthenticationService { if (repositoryUrl != null) { final String realm = repositoryUrl.toDecodedString(); - authentication = requestCredentials(realm, type, new Getter() { - @Override - public SVNAuthentication get() { - return myConfiguration.getInteractiveManager(myVcs).getInnerProvider() - .requestClientAuthentication(type, repositoryUrl, realm, null, null, true); - } - }); + authentication = requestCredentials(realm, type, () -> myConfiguration.getInteractiveManager(myVcs).getInnerProvider() + .requestClientAuthentication(type, repositoryUrl, realm, null, null, true)); } if (authentication == null) { @@ -154,30 +149,25 @@ public class AuthenticationService { public String requestSshCredentials(@NotNull final String realm, @NotNull final SimpleCredentialsDialog.Mode mode, @NotNull final String key) { - return requestCredentials(realm, StringUtil.toLowerCase(mode.toString()), new Getter() { - @Override - public String get() { - final Ref answer = new Ref<>(); + return requestCredentials(realm, StringUtil.toLowerCase(mode.toString()), () -> { + final Ref answer = new Ref<>(); - Runnable command = new Runnable() { - public void run() { - SimpleCredentialsDialog dialog = new SimpleCredentialsDialog(myVcs.getProject()); + Runnable command = () -> { + SimpleCredentialsDialog dialog = new SimpleCredentialsDialog(myVcs.getProject()); - dialog.setup(mode, realm, key, true); - dialog.setTitle(SvnBundle.message("dialog.title.authentication.required")); - dialog.setSaveEnabled(false); - if (dialog.showAndGet()) { - answer.set(dialog.getPassword()); - } - } - }; + dialog.setup(mode, realm, key, true); + dialog.setTitle(SvnBundle.message("dialog.title.authentication.required")); + dialog.setSaveEnabled(false); + if (dialog.showAndGet()) { + answer.set(dialog.getPassword()); + } + }; - // Use ModalityState.any() as currently ssh credentials in terminal mode are requested in the thread that reads output and not in - // the thread that started progress - WaitForProgressToShow.runOrInvokeAndWaitAboveProgress(command, ModalityState.any()); + // Use ModalityState.any() as currently ssh credentials in terminal mode are requested in the thread that reads output and not in + // the thread that started progress + WaitForProgressToShow.runOrInvokeAndWaitAboveProgress(command, ModalityState.any()); - return answer.get(); - } + return answer.get(); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnAuthenticationManager.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnAuthenticationManager.java index 294638d4c359..65b5c99595a7 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnAuthenticationManager.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnAuthenticationManager.java @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.svn.auth; -import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; @@ -63,7 +62,8 @@ import static com.intellij.util.WaitForProgressToShow.runOrInvokeLaterAboveProgr /** * @author alex */ -public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager implements SvnAuthenticationListener, ISVNAuthenticationManagerExt { +public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager + implements SvnAuthenticationListener, ISVNAuthenticationManagerExt { private static final Logger LOG = Logger.getInstance(SvnAuthenticationManager.class); // while Mac storage not working for IDEA, we use this key to check whether to prompt abt plaintext or just store public static final String SVN_SSH = "svn+ssh"; @@ -104,26 +104,22 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im myPersistentAuthenticationProviderProxy.setProject(myProject); } myInteraction = new MySvnAuthenticationInteraction(myProject); - Disposer.register(myProject, new Disposable() { - @Override - public void dispose() { - myVcs = null; - myProject = null; - if (myPersistentAuthenticationProviderProxy != null) { - myPersistentAuthenticationProviderProxy.myProject = null; - ((MyKeyringMasterKeyProvider) myPersistentAuthenticationProviderProxy.myISVNGnomeKeyringPasswordProvider).myProject = null; - myPersistentAuthenticationProviderProxy = null; - } - if (myInteraction instanceof MySvnAuthenticationInteraction) { - ((MySvnAuthenticationInteraction) myInteraction).myProject = null; - } - if (myConfig != null) { - myConfig.clear(); - myConfig = null; - } - myInteraction = null; - + Disposer.register(myProject, () -> { + myVcs = null; + myProject = null; + if (myPersistentAuthenticationProviderProxy != null) { + myPersistentAuthenticationProviderProxy.myProject = null; + ((MyKeyringMasterKeyProvider)myPersistentAuthenticationProviderProxy.myISVNGnomeKeyringPasswordProvider).myProject = null; + myPersistentAuthenticationProviderProxy = null; } + if (myInteraction instanceof MySvnAuthenticationInteraction) { + ((MySvnAuthenticationInteraction)myInteraction).myProject = null; + } + if (myConfig != null) { + myConfig.clear(); + myConfig = null; + } + myInteraction = null; }); // This is not the same instance as DefaultSVNAuthenticationManager.myProviders[1], but currently // DefaultSVNAuthenticationManager.CacheAuthenticationProvider uses only its outer class state - so we utilize necessary logic with @@ -189,7 +185,7 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im SVNAuthentication previousAuth, boolean authMayBeStored) { final SVNAuthentication authentication = myDelegate.requestClientAuthentication(kind, url, realm, errorMessage, previousAuth, authMayBeStored); - if (myProject != null && ! myProject.isDisposed()) { + if (myProject != null && !myProject.isDisposed()) { myProject.getMessageBus().syncPublisher(AUTHENTICATION_PROVIDER_LISTENER) .requestClientAuthentication(kind, url, realm, errorMessage, previousAuth, authMayBeStored, authentication); } @@ -202,7 +198,7 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im Object certificate, boolean resultMayBeStored) { final int result = myDelegate.acceptServerAuthentication(url, realm, certificate, resultMayBeStored); - if (myProject != null && ! myProject.isDisposed()) { + if (myProject != null && !myProject.isDisposed()) { myProject.getMessageBus().syncPublisher(AUTHENTICATION_PROVIDER_LISTENER) .acceptServerAuthentication(url, realm, certificate, resultMayBeStored, result); } @@ -212,14 +208,19 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im public interface ISVNAuthenticationProviderListener { void requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, - SVNAuthentication previousAuth, boolean authMayBeStored, SVNAuthentication authentication); - void acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean resultMayBeStored, @MagicConstant int acceptResult); + SVNAuthentication previousAuth, boolean authMayBeStored, SVNAuthentication authentication); + + void acceptServerAuthentication(SVNURL url, + String realm, + Object certificate, + boolean resultMayBeStored, + @MagicConstant int acceptResult); } @Override public void setAuthenticationProvider(ISVNAuthenticationProvider provider) { ISVNAuthenticationProvider useProvider = provider; - if (! (provider instanceof AuthenticationProviderProxy)) { + if (!(provider instanceof AuthenticationProviderProxy)) { useProvider = new AuthenticationProviderProxy(provider); } myProvider = useProvider; @@ -234,13 +235,13 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im /** * Gets authentication provider without looking into thread local storage for providers. - * + *

* TODO: * Thread local storage is used "for some interaction with SVNKit" and is not always cleared correctly. So some threads contain * "passive provider" in thread local storage - and getProvider() returns this "passive provider". This occurs, for instance when * RemoteRevisionsCache is refreshed in background - after its execution, corresponding thread has "passive provider" in thread local * storage. - * + *

* As a result authentication fails in such cases (at least for command line implementation). To fix this, command line implementation is * updated not to check thread local storage at all. * @@ -305,7 +306,7 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im @Override public void requested(ProviderType type, SVNURL url, String realm, String kind, boolean canceled) { - if (ProviderType.interactive.equals(type) && (! canceled)) { + if (ProviderType.interactive.equals(type) && (!canceled)) { ourJustEntered.set(true); } myListener.getMulticaster().requested(type, url, realm, kind, canceled); @@ -347,7 +348,8 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im } }; ensureListenerCreated(); - myDelegate = new DefaultSVNPersistentAuthenticationProvider(authDir, userName, delegatingOptions, getDefaultOptions(), getHostOptionsProvider()) { + myDelegate = new DefaultSVNPersistentAuthenticationProvider(authDir, userName, delegatingOptions, getDefaultOptions(), + getHostOptionsProvider()) { @Override protected IPasswordStorage[] createPasswordStorages(DefaultSVNOptions options) { final IPasswordStorage[] passwordStorages = super.createPasswordStorages(options); @@ -366,17 +368,18 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im myProject = project; } - public SVNAuthentication requestClientAuthentication(final String kind, final SVNURL url, final String realm, final SVNErrorMessage errorMessage, - final SVNAuthentication previousAuth, final boolean authMayBeStored) { + public SVNAuthentication requestClientAuthentication(final String kind, + final SVNURL url, + final String realm, + final SVNErrorMessage errorMessage, + final SVNAuthentication previousAuth, + final boolean authMayBeStored) { try { - return wrapNativeCall(new ThrowableComputable() { - @Override - public SVNAuthentication compute() throws SVNException { - final SVNAuthentication svnAuthentication = - myDelegate.requestClientAuthentication(kind, url, realm, errorMessage, previousAuth, authMayBeStored); - myListener.getMulticaster().requested(ProviderType.persistent, url, realm, kind, svnAuthentication == null); - return svnAuthentication; - } + return wrapNativeCall(() -> { + final SVNAuthentication svnAuthentication = + myDelegate.requestClientAuthentication(kind, url, realm, errorMessage, previousAuth, authMayBeStored); + myListener.getMulticaster().requested(ProviderType.persistent, url, realm, kind, svnAuthentication == null); + return svnAuthentication; }); } catch (SVNException e) { @@ -391,41 +394,39 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im private void actualSavePermissions(String realm, SVNAuthentication auth) { final String actualKind = auth.getKind(); - File dir = new File(myAuthDir, actualKind); - String fileName = SVNFileUtil.computeChecksum(realm); - File authFile = new File(dir, fileName); + File dir = new File(myAuthDir, actualKind); + String fileName = SVNFileUtil.computeChecksum(realm); + File authFile = new File(dir, fileName); - try { - ((ISVNPersistentAuthenticationProvider) myDelegate).saveAuthentication(auth, actualKind, realm); - } - catch (SVNException e) { - if (myProject != null) { - ApplicationManager.getApplication().invokeLater(new VcsBalloonProblemNotifier(myProject, - "Problem when storing Subversion credentials: " + e.getMessage(), MessageType.ERROR)); - } - } - finally { - // do not make password file readonly - setWriteable(authFile); - } + try { + ((ISVNPersistentAuthenticationProvider)myDelegate).saveAuthentication(auth, actualKind, realm); + } + catch (SVNException e) { + if (myProject != null) { + ApplicationManager.getApplication().invokeLater(new VcsBalloonProblemNotifier(myProject, + "Problem when storing Subversion credentials: " + + e.getMessage(), MessageType.ERROR)); + } + } + finally { + // do not make password file readonly + setWriteable(authFile); + } } public void saveAuthentication(final SVNAuthentication auth, final String kind, final String realm) throws SVNException { try { - wrapNativeCall(new ThrowableComputable() { - @Override - public Void compute() throws SVNException { - final Boolean fromInteractive = ourJustEntered.get(); - ourJustEntered.set(null); - if (! myArtificialSaving && ! Boolean.TRUE.equals(fromInteractive)) { - // not what user entered - return null; - } - myListener.getMulticaster().saveAttemptStarted(ProviderType.persistent, auth.getURL(), realm, auth.getKind()); - ((ISVNPersistentAuthenticationProvider) myDelegate).saveAuthentication(auth, kind, realm); - myListener.getMulticaster().saveAttemptFinished(ProviderType.persistent, auth.getURL(), realm, auth.getKind()); + wrapNativeCall(() -> { + final Boolean fromInteractive = ourJustEntered.get(); + ourJustEntered.set(null); + if (!myArtificialSaving && !Boolean.TRUE.equals(fromInteractive)) { + // not what user entered return null; } + myListener.getMulticaster().saveAttemptStarted(ProviderType.persistent, auth.getURL(), realm, auth.getKind()); + ((ISVNPersistentAuthenticationProvider)myDelegate).saveAuthentication(auth, kind, realm); + myListener.getMulticaster().saveAttemptFinished(ProviderType.persistent, auth.getURL(), realm, auth.getKind()); + return null; }); } catch (SVNException e) { @@ -437,12 +438,9 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im @Override public void saveFingerprints(final String realm, final byte[] fingerprints) { try { - wrapNativeCall(new ThrowableComputable() { - @Override - public Void compute() throws SVNException { - ((ISVNPersistentAuthenticationProvider) myDelegate).saveFingerprints(realm, fingerprints); - return null; - } + wrapNativeCall(() -> { + ((ISVNPersistentAuthenticationProvider)myDelegate).saveFingerprints(realm, fingerprints); + return null; }); } catch (SVNException e) { @@ -454,12 +452,7 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im @Override public byte[] loadFingerprints(final String realm) { try { - return wrapNativeCall(new ThrowableComputable() { - @Override - public byte[] compute() throws SVNException { - return ((ISVNPersistentAuthenticationProvider) myDelegate).loadFingerprints(realm); - } - }); + return wrapNativeCall(() -> ((ISVNPersistentAuthenticationProvider)myDelegate).loadFingerprints(realm)); } catch (SVNException e) { LOG.info(e); @@ -468,8 +461,9 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im } private final static int maxAttempts = 10; + private void setWriteable(final File file) { - if (! file.exists()) return; + if (!file.exists()) return; if (file.getParentFile() == null) { return; } @@ -478,8 +472,8 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im try { final File tempFile = FileUtil.createTempFile(parent, "123", "1", true); FileUtil.delete(tempFile); - if (! file.renameTo(tempFile)) continue; - if (! file.createNewFile()) continue; + if (!file.renameTo(tempFile)) continue; + if (!file.createNewFile()) continue; FileUtil.copy(tempFile, file); FileUtil.delete(tempFile); return; @@ -496,7 +490,8 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im myKeyAlgorithm.put(Thread.currentThread(), keyAlgorithm); try { super.verifyHostKey(hostName, port, keyAlgorithm, hostKey); - } finally { + } + finally { myKeyAlgorithm.remove(Thread.currentThread()); } } @@ -543,7 +538,8 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im final SVNAuthentication proxy = ProxySvnAuthentication.proxy(authentication, authStorageEnabled, myArtificialSaving); super.acknowledgeAuthentication(accepted, kind, realm, errorMessage, proxy); successSaving = true; - } finally { + } + finally { mySavePermissions.remove(); if (myArtificialSaving) { myArtificialSaving = false; @@ -569,7 +565,7 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im } public void acknowledgeForSSL(boolean accepted, SVNAuthentication proxy) { - if (accepted && proxy instanceof SVNSSLAuthentication && (((SVNSSLAuthentication) proxy).getCertificateFile() != null)) { + if (accepted && proxy instanceof SVNSSLAuthentication && (((SVNSSLAuthentication)proxy).getCertificateFile() != null)) { final SVNSSLAuthentication svnsslAuthentication = (SVNSSLAuthentication)proxy; final SVNURL url = svnsslAuthentication.getURL(); @@ -603,7 +599,7 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im // ! use common proxy if it is set try { final List proxies = HttpConfigurable.getInstance().getOnlyBySettingsSelector().select(new URI(url.toString())); - if (proxies != null && ! proxies.isEmpty()) { + if (proxies != null && !proxies.isEmpty()) { for (Proxy proxy : proxies) { if (HttpConfigurable.isRealProxy(proxy) && Proxy.Type.HTTP.equals(proxy.type())) { final SocketAddress address = proxy.address(); @@ -624,15 +620,15 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im String proxyExceptions = getServersPropertyIdea(host, "http-proxy-exceptions"); String proxyExceptionsSeparator = ","; if (proxyExceptions == null) { - proxyExceptions = System.getProperty("http.nonProxyHosts"); - proxyExceptionsSeparator = "|"; + proxyExceptions = System.getProperty("http.nonProxyHosts"); + proxyExceptionsSeparator = "|"; } if (proxyExceptions != null) { - for(StringTokenizer exceptions = new StringTokenizer(proxyExceptions, proxyExceptionsSeparator); exceptions.hasMoreTokens();) { - String exception = exceptions.nextToken().trim(); - if (DefaultSVNOptions.matches(exception, host)) { - return null; - } + for (StringTokenizer exceptions = new StringTokenizer(proxyExceptions, proxyExceptionsSeparator); exceptions.hasMoreTokens(); ) { + String exception = exceptions.nextToken().trim(); + if (DefaultSVNOptions.matches(exception, host)) { + return null; + } } } String proxyPort = getServersPropertyIdea(host, HTTP_PROXY_PORT); @@ -687,41 +683,42 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im } private static class MySimpleProxyManager implements ISVNProxyManager { - protected String myProxyHost; - private final String myProxyPort; - protected String myProxyUser; - protected String myProxyPassword; + protected String myProxyHost; + private final String myProxyPort; + protected String myProxyUser; + protected String myProxyPassword; - public MySimpleProxyManager(String host, String port, String user, String password) { - myProxyHost = host; - myProxyPort = port == null ? "3128" : port; - myProxyUser = user; - myProxyPassword = password; - } + public MySimpleProxyManager(String host, String port, String user, String password) { + myProxyHost = host; + myProxyPort = port == null ? "3128" : port; + myProxyUser = user; + myProxyPassword = password; + } - public String getProxyHost() { - return myProxyHost; - } + public String getProxyHost() { + return myProxyHost; + } - public int getProxyPort() { - try { - return Integer.parseInt(myProxyPort); - } catch (NumberFormatException nfe) { - // - } - return 3128; + public int getProxyPort() { + try { + return Integer.parseInt(myProxyPort); } + catch (NumberFormatException nfe) { + // + } + return 3128; + } - public String getProxyUserName() { - return myProxyUser; - } + public String getProxyUserName() { + return myProxyUser; + } - public String getProxyPassword() { - return myProxyPassword; - } + public String getProxyPassword() { + return myProxyPassword; + } - public void acknowledgeProxyContext(boolean accepted, SVNErrorMessage errorMessage) { - } + public void acknowledgeProxyContext(boolean accepted, SVNErrorMessage errorMessage) { + } } // 30 seconds @@ -786,7 +783,7 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im } } Map globalProps = serversFile.getProperties("global"); - return (String) globalProps.get(name); + return (String)globalProps.get(name); } public static boolean checkHostGroup(final String url, final String patterns, final String exceptions) { @@ -799,15 +796,15 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im } final String host = svnurl.getHost(); - return matches(patterns, host) && (! matches(exceptions, host)); + return matches(patterns, host) && (!matches(exceptions, host)); } private static boolean matches(final String pattern, final String host) { final StringTokenizer tokenizer = new StringTokenizer(pattern, ","); - while(tokenizer.hasMoreTokens()) { + while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (DefaultSVNOptions.matches(token, host)) { - return true; + return true; } } return false; @@ -815,7 +812,7 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im @Nullable public static String getGroupForHost(final String host, final IdeaSVNConfigFile serversFile) { - final Map groups = serversFile.getAllGroups(); + final Map groups = serversFile.getAllGroups(); for (Map.Entry entry : groups.entrySet()) { if (matchesGroupPattern(host, entry.getValue().getPatterns())) return entry.getKey(); } @@ -825,19 +822,19 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im // taken from default manager as is private static String getGroupName(Map groups, String host) { for (Object o : groups.keySet()) { - final String name = (String) o; - final String pattern = (String) groups.get(name); + final String name = (String)o; + final String pattern = (String)groups.get(name); if (matchesGroupPattern(host, pattern)) return name; } - return null; + return null; } private static boolean matchesGroupPattern(String host, String pattern) { - for(StringTokenizer tokens = new StringTokenizer(pattern, ","); tokens.hasMoreTokens();) { - String token = tokens.nextToken(); - if (DefaultSVNOptions.matches(token, host)) { - return true; - } + for (StringTokenizer tokens = new StringTokenizer(pattern, ","); tokens.hasMoreTokens(); ) { + String token = tokens.nextToken(); + if (DefaultSVNOptions.matches(token, host)) { + return true; + } } return false; } @@ -871,24 +868,28 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im @Override public void warnOnAuthStorageDisabled(SVNURL url) { - VcsBalloonProblemNotifier.showOverChangesView(myProject, "Cannot store credentials: forbidden by \"store-auth-creds=no\"", MessageType.ERROR); + VcsBalloonProblemNotifier + .showOverChangesView(myProject, "Cannot store credentials: forbidden by \"store-auth-creds=no\"", MessageType.ERROR); } @Override public void warnOnPasswordStorageDisabled(SVNURL url) { - VcsBalloonProblemNotifier.showOverChangesView(myProject, "Cannot store password: forbidden by \"store-passwords=no\"", MessageType.ERROR); + VcsBalloonProblemNotifier + .showOverChangesView(myProject, "Cannot store password: forbidden by \"store-passwords=no\"", MessageType.ERROR); } @Override public void warnOnSSLPassphraseStorageDisabled(SVNURL url) { - VcsBalloonProblemNotifier.showOverChangesView(myProject, "Cannot store passphrase: forbidden by \"store-ssl-client-cert-pp=no\"", MessageType.ERROR); + VcsBalloonProblemNotifier + .showOverChangesView(myProject, "Cannot store passphrase: forbidden by \"store-ssl-client-cert-pp=no\"", MessageType.ERROR); } @Override public boolean promptForPlaintextPasswordSaving(SVNURL url, String realm) { final int answer = Messages.showYesNoDialog(myProject, String.format("Your password for authentication realm:\n" + - "%s\ncan only be stored to disk unencrypted. Would you like to store it in plaintext?", realm), - "Store the password in plaintext?", Messages.getQuestionIcon()); + "%s\ncan only be stored to disk unencrypted. Would you like to store it in plaintext?", + realm), + "Store the password in plaintext?", Messages.getQuestionIcon()); return answer == Messages.YES; } @@ -900,9 +901,11 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im @Override public boolean promptForSSLPlaintextPassphraseSaving(SVNURL url, String realm, File certificateFile, String certificateName) { final int answer = Messages.showYesNoDialog(myProject, - String.format("Your passphrase for " + certificateName + ":\n%s\ncan only be stored to disk unencrypted. Would you like to store it in plaintext?", - certificateFile.getPath()), - "Store the passphrase in plaintext?", Messages.getQuestionIcon()); + String.format("Your passphrase for " + + certificateName + + ":\n%s\ncan only be stored to disk unencrypted. Would you like to store it in plaintext?", + certificateFile.getPath()), + "Store the passphrase in plaintext?", Messages.getQuestionIcon()); return answer == Messages.YES; } @@ -967,13 +970,8 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im final boolean superValue = super.isStorePlainTextPasswords(realm, auth); final boolean value = mySavePermissions.allowed() || superValue; - if ((! value) && (! mySavePermissions.have())) { - promptAndSaveWhenWeLackEncryption(realm, auth, new Getter() { - @Override - public Boolean get() { - return myInteraction.promptForPlaintextPasswordSaving(myUrl, realm); - } - }); + if ((!value) && (!mySavePermissions.have())) { + promptAndSaveWhenWeLackEncryption(realm, auth, () -> myInteraction.promptForPlaintextPasswordSaving(myUrl, realm)); } return value; } @@ -983,25 +981,24 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im if (USERNAME.equals(auth.getKind())) return true; final boolean value = mySavePermissions.allowed() || super.isStorePlainTextPassphrases(realm, auth); - if ((! value) && (! mySavePermissions.have())) { - promptAndSaveWhenWeLackEncryption(realm, auth, new Getter() { - @Override - public Boolean get() { - File file = null; - String certificateName = null; - if (auth instanceof SVNSSLAuthentication) { - file = ((SVNSSLAuthentication) auth).getCertificateFile(); - certificateName = "client certificate"; - } else if (auth instanceof SVNSSHAuthentication) { - file = ((SVNSSHAuthentication) auth).getPrivateKeyFile(); - certificateName = "private key file"; - } else { - assert false; - } - return myInteraction.promptForSSLPlaintextPassphraseSaving(myUrl, realm, - file, certificateName); - } - }); + if ((!value) && (!mySavePermissions.have())) { + promptAndSaveWhenWeLackEncryption(realm, auth, () -> { + File file = null; + String certificateName = null; + if (auth instanceof SVNSSLAuthentication) { + file = ((SVNSSLAuthentication)auth).getCertificateFile(); + certificateName = "client certificate"; + } + else if (auth instanceof SVNSSHAuthentication) { + file = ((SVNSSHAuthentication)auth).getPrivateKeyFile(); + certificateName = "private key file"; + } + else { + assert false; + } + return myInteraction.promptForSSLPlaintextPassphraseSaving(myUrl, realm, + file, certificateName); + }); } return value; } @@ -1011,10 +1008,11 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im final boolean value; if (hasAuthStorageEnabledOption()) { value = super.isAuthStorageEnabled(); - } else { + } + else { value = isTurned(getConfigFile().getPropertyValue("auth", "store-auth-creds")); } - if (! value) { + if (!value) { myInteraction.warnOnAuthStorageDisabled(myUrl); } return value; @@ -1026,11 +1024,12 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im final boolean value; if (storePasswords != null) { value = isTurned(storePasswords); - } else { + } + else { final String configValue = getConfigFile().getPropertyValue("auth", "store-passwords"); value = isTurned(configValue); } - if (! value) { + if (!value) { myInteraction.warnOnPasswordStorageDisabled(myUrl); } return value; @@ -1039,7 +1038,7 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im @Override public boolean isStoreSSLClientCertificatePassphrases() { final boolean value = super.isStoreSSLClientCertificatePassphrases(); - if (! value) { + if (!value) { myInteraction.warnOnSSLPassphraseStorageDisabled(myUrl); } return value; @@ -1062,16 +1061,13 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im private void promptAndSaveWhenWeLackEncryption(final String realm, final SVNAuthentication auth, final Getter prompt) { final Boolean[] saveOnce = new Boolean[1]; - final Runnable actualSave = new Runnable() { - @Override - public void run() { - mySavePermissions.put(Boolean.TRUE.equals(saveOnce[0])); - try { - myPersistentAuthenticationProviderProxy.actualSavePermissions(realm, auth); - } - finally { - mySavePermissions.remove(); - } + final Runnable actualSave = () -> { + mySavePermissions.put(Boolean.TRUE.equals(saveOnce[0])); + try { + myPersistentAuthenticationProviderProxy.actualSavePermissions(realm, auth); + } + finally { + mySavePermissions.remove(); } }; @@ -1080,7 +1076,8 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im saveOnce[0] = Boolean.TRUE.equals(prompt.get()); ApplicationManager.getApplication().executeOnPooledThread(actualSave); }, getCurrent(), myProject); - } else { + } + else { saveOnce[0] = Boolean.TRUE.equals(prompt.get()); actualSave.run(); } @@ -1152,7 +1149,8 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im LOG.info(sb.toString()); } return t; - } finally { + } + finally { NativeLogReader.clear(); NativeLogReader.endTracking(); } @@ -1170,12 +1168,8 @@ public class SvnAuthenticationManager extends DefaultSVNAuthenticationManager im final String message = keyringName != null ? SvnBundle.message("gnome.keyring.prompt.named", keyringName) : SvnBundle.message("gnome.keyring.prompt.nameless"); final Ref result = Ref.create(); - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - result.set(Messages.showPasswordDialog(myProject, message, SvnBundle.message("subversion.name"), Messages.getQuestionIcon())); - } - }); + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> result + .set(Messages.showPasswordDialog(myProject, message, SvnBundle.message("subversion.name"), Messages.getQuestionIcon()))); return !result.isNull() ? result.get().toCharArray() : null; } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnAuthenticationNotifier.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnAuthenticationNotifier.java index 1ae0c8914325..794c311e67c3 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnAuthenticationNotifier.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnAuthenticationNotifier.java @@ -38,7 +38,6 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.ui.awt.RelativePoint; -import com.intellij.util.Consumer; import com.intellij.util.ThreeState; import com.intellij.util.net.HttpConfigurable; import com.intellij.util.proxy.CommonProxy; @@ -62,7 +61,6 @@ import org.tmatesoft.svn.core.wc2.SvnTarget; import javax.swing.*; import java.awt.*; import java.io.File; -import java.io.FilenameFilter; import java.net.*; import java.util.*; import java.util.List; @@ -112,22 +110,19 @@ public class SvnAuthenticationNotifier extends GenericNotifierImpl resultRef = new Ref<>(); - final Runnable checker = new Runnable() { - @Override - public void run() { - try { - final boolean result = - interactiveValidation(obj.myProject, obj.getUrl(), obj.getRealm(), obj.getKind()); - log("ask result for: " + obj.getUrl() + " is: " + result); - resultRef.set(result); - if (result) { - onStateChangedToSuccess(obj); - } - } - finally { - myVerificationInProgress = false; + final Runnable checker = () -> { + try { + final boolean result = + interactiveValidation(obj.myProject, obj.getUrl(), obj.getRealm(), obj.getKind()); + log("ask result for: " + obj.getUrl() + " is: " + result); + resultRef.set(result); + if (result) { + onStateChangedToSuccess(obj); } } + finally { + myVerificationInProgress = false; + } }; final Application application = ApplicationManager.getApplication(); // also do not show auth if thread does not have progress indicator @@ -173,12 +168,9 @@ public class SvnAuthenticationNotifier extends GenericNotifierImpl { + for (SVNURL key : outdatedRequests) { + removeLazyNotificationByKey(key); } }, ModalityState.NON_MODAL); } @@ -428,35 +420,23 @@ public class SvnAuthenticationNotifier extends GenericNotifierImpl() { - @Override - public void consume(String s) { - configuration - .setConfigurationDirParameters(false, s); - } - }, project, null); - } - } - ); - } - }, ModalityState.NON_MODAL, project.getDisposed()); + ApplicationManager.getApplication().invokeLater(() -> VcsBalloonProblemNotifier + .showOverChangesView(project, "Authentication failed: " + e.getMessage(), MessageType.ERROR, new NamedRunnable( + SvnBundle.message("confirmation.title.clear.authentication.cache")) { + @Override + public void run() { + clearAuthenticationCache(project, null, configuration + .getConfigurationDirectory()); + } + }, new NamedRunnable( + SvnBundle.message("action.title.select.configuration.directory")) { + @Override + public void run() { + SvnConfigurable.selectConfigurationDirectory(configuration.getConfigurationDirectory(), + s -> configuration.setConfigurationDirParameters(false, s), project, null); + } + } + ), ModalityState.NON_MODAL, project.getDisposed()); } public static void clearAuthenticationCache(@NotNull final Project project, final Component component, final String configDirPath) { @@ -481,27 +461,19 @@ public class SvnAuthenticationNotifier extends GenericNotifierImpl { + final ProgressIndicator ind = ProgressManager.getInstance().getProgressIndicator(); + if (ind != null) { + ind.setIndeterminate(true); + ind.setText("Clearing stored credentials in " + authDir.getAbsolutePath()); + } + final File[] files = authDir.listFiles((dir, name) -> ourAuthKinds.contains(name)); - for (File dir : files) { - if (ind != null) { - ind.setText("Deleting " + dir.getAbsolutePath()); - } - FileUtil.delete(dir); + for (File dir : files) { + if (ind != null) { + ind.setText("Deleting " + dir.getAbsolutePath()); } + FileUtil.delete(dir); } }; final Application application = ApplicationManager.getApplication(); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnInteractiveAuthenticationProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnInteractiveAuthenticationProvider.java index 77a23d3bf7bf..e19347fdc039 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnInteractiveAuthenticationProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/auth/SvnInteractiveAuthenticationProvider.java @@ -85,14 +85,12 @@ public class SvnInteractiveAuthenticationProvider implements ISVNAuthenticationP final String userName = previousAuth != null && previousAuth.getUserName() != null ? previousAuth.getUserName() : myManager.getDefaultUsername(kind, url); if (ISVNAuthenticationManager.PASSWORD.equals(kind)) {// || ISVNAuthenticationManager.USERNAME.equals(kind)) { - command = new Runnable() { - public void run() { - SimpleCredentialsDialog dialog = new SimpleCredentialsDialog(myProject); - dialog.setup(realm, userName, authCredsOn); - setTitle(dialog, errorMessage); - if (dialog.showAndGet()) { - result[0] = new SVNPasswordAuthentication(dialog.getUserName(), dialog.getPassword(), dialog.isSaveAllowed(), url, false); - } + command = () -> { + SimpleCredentialsDialog dialog = new SimpleCredentialsDialog(myProject); + dialog.setup(realm, userName, authCredsOn); + setTitle(dialog, errorMessage); + if (dialog.showAndGet()) { + result[0] = new SVNPasswordAuthentication(dialog.getUserName(), dialog.getPassword(), dialog.isSaveAllowed(), url, false); } }; } @@ -100,14 +98,12 @@ public class SvnInteractiveAuthenticationProvider implements ISVNAuthenticationP if (ApplicationManager.getApplication().isUnitTestMode()) { return new SVNUserNameAuthentication(userName, false); } - command = new Runnable() { - public void run() { - UserNameCredentialsDialog dialog = new UserNameCredentialsDialog(myProject); - dialog.setup(realm, userName, authCredsOn); - setTitle(dialog, errorMessage); - if (dialog.showAndGet()) { - result[0] = new SVNUserNameAuthentication(dialog.getUserName(), dialog.isSaveAllowed(), url, false); - } + command = () -> { + UserNameCredentialsDialog dialog = new UserNameCredentialsDialog(myProject); + dialog.setup(realm, userName, authCredsOn); + setTitle(dialog, errorMessage); + if (dialog.showAndGet()) { + result[0] = new SVNUserNameAuthentication(dialog.getUserName(), dialog.isSaveAllowed(), url, false); } }; } @@ -117,47 +113,43 @@ public class SvnInteractiveAuthenticationProvider implements ISVNAuthenticationP final Connector agentConnector = createSshAgentConnector(); final boolean isAgentAvailable = agentConnector != null && agentConnector.isAvailable(); - command = new Runnable() { - public void run() { - SSHCredentialsDialog dialog = new SSHCredentialsDialog(myProject, realm, userName, authCredsOn, url.getPort(), isAgentAvailable); - setTitle(dialog, errorMessage); - if (dialog.showAndGet()) { - int port = dialog.getPortNumber(); - if (dialog.isSshAgentSelected()) { - if (agentConnector != null) { - result[0] = - new SVNSSHAuthentication(dialog.getUserName(), new TrileadAgentProxy(agentConnector), port, url, false); - } - } - else if (dialog.getKeyFile() != null && dialog.getKeyFile().trim().length() > 0) { - String passphrase = dialog.getPassphrase(); - if (passphrase != null && passphrase.length() == 0) { - passphrase = null; - } + command = () -> { + SSHCredentialsDialog dialog = new SSHCredentialsDialog(myProject, realm, userName, authCredsOn, url.getPort(), isAgentAvailable); + setTitle(dialog, errorMessage); + if (dialog.showAndGet()) { + int port = dialog.getPortNumber(); + if (dialog.isSshAgentSelected()) { + if (agentConnector != null) { result[0] = - new SVNSSHAuthentication(dialog.getUserName(), new File(dialog.getKeyFile()), passphrase, port, dialog.isSaveAllowed(), url, - false); + new SVNSSHAuthentication(dialog.getUserName(), new TrileadAgentProxy(agentConnector), port, url, false); } - else { - result[0] = new SVNSSHAuthentication(dialog.getUserName(), dialog.getPassword(), port, dialog.isSaveAllowed(), url, false); + } + else if (dialog.getKeyFile() != null && dialog.getKeyFile().trim().length() > 0) { + String passphrase = dialog.getPassphrase(); + if (passphrase != null && passphrase.length() == 0) { + passphrase = null; } + result[0] = + new SVNSSHAuthentication(dialog.getUserName(), new File(dialog.getKeyFile()), passphrase, port, dialog.isSaveAllowed(), url, + false); + } + else { + result[0] = new SVNSSHAuthentication(dialog.getUserName(), dialog.getPassword(), port, dialog.isSaveAllowed(), url, false); } } }; } else if (ISVNAuthenticationManager.SSL.equals(kind)) { - command = new Runnable() { - public void run() { - final ISVNHostOptions options = myManager.getHostOptionsProvider().getHostOptions(url); - final String file = options.getSSLClientCertFile(); - final SSLCredentialsDialog dialog = new SSLCredentialsDialog(myProject, realm, authCredsOn); - if (!StringUtil.isEmptyOrSpaces(file)) { - dialog.setFile(file); - } - setTitle(dialog, errorMessage); - if (dialog.showAndGet()) { - result[0] = new SVNSSLAuthentication(new File(dialog.getCertificatePath()), String.valueOf(dialog.getCertificatePassword()), - dialog.getSaveAuth(), url, false); - } + command = () -> { + final ISVNHostOptions options = myManager.getHostOptionsProvider().getHostOptions(url); + final String file = options.getSSLClientCertFile(); + final SSLCredentialsDialog dialog = new SSLCredentialsDialog(myProject, realm, authCredsOn); + if (!StringUtil.isEmptyOrSpaces(file)) { + dialog.setFile(file); + } + setTitle(dialog, errorMessage); + if (dialog.showAndGet()) { + result[0] = new SVNSSLAuthentication(new File(dialog.getCertificatePath()), String.valueOf(dialog.getCertificatePassword()), + dialog.getSaveAuth(), url, false); } }; } @@ -197,25 +189,20 @@ public class SvnInteractiveAuthenticationProvider implements ISVNAuthenticationP final int[] result = new int[1]; Runnable command; if (certificate instanceof X509Certificate || certificate instanceof String) { - command = new Runnable() { - public void run() { - ServerSSLDialog dialog = certificate instanceof X509Certificate - ? new ServerSSLDialog(myProject, (X509Certificate)certificate, resultMayBeStored) - : new ServerSSLDialog(myProject, (String)certificate, resultMayBeStored); - dialog.show(); - result[0] = dialog.getResult(); - } + command = () -> { + ServerSSLDialog dialog = certificate instanceof X509Certificate + ? new ServerSSLDialog(myProject, (X509Certificate)certificate, resultMayBeStored) + : new ServerSSLDialog(myProject, (String)certificate, resultMayBeStored); + dialog.show(); + result[0] = dialog.getResult(); }; } else if (certificate instanceof byte[]) { final String sshKeyAlgorithm = myManager.getSSHKeyAlgorithm(); - command = new Runnable() { - @Override - public void run() { - final ServerSSHDialog serverSSHDialog = - new ServerSSHDialog(myProject, resultMayBeStored, url.toDecodedString(), sshKeyAlgorithm, (byte[])certificate); - serverSSHDialog.show(); - result[0] = serverSSHDialog.getResult(); - } + command = () -> { + final ServerSSHDialog serverSSHDialog = + new ServerSSHDialog(myProject, resultMayBeStored, url.toDecodedString(), sshKeyAlgorithm, (byte[])certificate); + serverSSHDialog.show(); + result[0] = serverSSHDialog.getResult(); }; } else { VcsBalloonProblemNotifier.showOverChangesView(myProject, "Subversion: unknown certificate type from " + url.toDecodedString(), diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/BranchConfigurationDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/BranchConfigurationDialog.java index af3baef73661..b3035dd99dda 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/BranchConfigurationDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/BranchConfigurationDialog.java @@ -122,19 +122,16 @@ public class BranchConfigurationDialog extends DialogWrapper { } } }) - .setRemoveAction(new AnActionButtonRunnable() { - @Override - public void run(AnActionButton button) { - int selectedIndex = myBranchLocationsList.getSelectedIndex(); - for (String url : myBranchLocationsList.getSelectedValuesList()) { - int index = myBranchLocationsModel.getConfiguration().getBranchUrls().indexOf(url); - myBranchLocationsModel.getConfiguration().removeBranch(url); - myBranchLocationsModel.fireItemRemoved(index); - } - if (myBranchLocationsModel.getSize() > 0) { - selectedIndex = min(selectedIndex, myBranchLocationsModel.getSize() - 1); - myBranchLocationsList.setSelectedIndex(selectedIndex); - } + .setRemoveAction(button -> { + int selectedIndex = myBranchLocationsList.getSelectedIndex(); + for (String url : myBranchLocationsList.getSelectedValuesList()) { + int index = myBranchLocationsModel.getConfiguration().getBranchUrls().indexOf(url); + myBranchLocationsModel.getConfiguration().removeBranch(url); + myBranchLocationsModel.fireItemRemoved(index); + } + if (myBranchLocationsModel.getSize() > 0) { + selectedIndex = min(selectedIndex, myBranchLocationsModel.getSize() - 1); + myBranchLocationsList.setSelectedIndex(selectedIndex); } }) .disableUpDownActions() diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/BranchesLoader.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/BranchesLoader.java index 7c50109e18ec..0baae8cd34ea 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/BranchesLoader.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/BranchesLoader.java @@ -24,7 +24,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.svn.SvnVcs; import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.browse.BrowseClient; -import org.jetbrains.idea.svn.browse.DirectoryEntry; import org.jetbrains.idea.svn.browse.DirectoryEntryConsumer; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; @@ -93,13 +92,9 @@ public class BranchesLoader implements Runnable { @NotNull private static DirectoryEntryConsumer createConsumer(@NotNull final List result) { - return new DirectoryEntryConsumer() { - - @Override - public void consume(final DirectoryEntry entry) throws SVNException { - if (entry.getDate() != null) { - result.add(new SvnBranchItem(entry.getUrl().toDecodedString(), entry.getDate(), entry.getRevision())); - } + return entry -> { + if (entry.getDate() != null) { + result.add(new SvnBranchItem(entry.getUrl().toDecodedString(), entry.getDate(), entry.getRevision())); } }; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/CreateBranchOrTagDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/CreateBranchOrTagDialog.java index 34128eb31472..0aee2cb7db86 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/CreateBranchOrTagDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/CreateBranchOrTagDialog.java @@ -45,11 +45,8 @@ import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.wc.SVNRevision; import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import java.awt.*; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; @@ -109,12 +106,10 @@ public class CreateBranchOrTagDialog extends DialogWrapper { updateControls(); } }); - myRepositoryField.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - SVNURL url = SelectLocationDialog.selectLocation(project, mySrcURL); - if (url != null) { - myRepositoryField.setText(url.toString()); - } + myRepositoryField.addActionListener(e -> { + SVNURL url = SelectLocationDialog.selectLocation(project, mySrcURL); + if (url != null) { + myRepositoryField.setText(url.toString()); } }); myRepositoryField.getTextField().getDocument().addDocumentListener(new DocumentAdapter() { @@ -122,16 +117,14 @@ public class CreateBranchOrTagDialog extends DialogWrapper { updateToURL(); } }); - myToURLText.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - String url = myToURLText.getText(); - String dstName = SVNPathUtil.tail(mySrcURL); - dstName = SVNEncodingUtil.uriDecode(dstName); - url = SelectLocationDialog.selectCopyDestination(myProject, SVNPathUtil.removeTail(url), - SvnBundle.message("label.copy.select.location.dialog.copy.as"), dstName, false); - if (url != null) { - myToURLText.setText(url); - } + myToURLText.addActionListener(e -> { + String url = myToURLText.getText(); + String dstName = SVNPathUtil.tail(mySrcURL); + dstName = SVNEncodingUtil.uriDecode(dstName); + url = SelectLocationDialog.selectCopyDestination(myProject, SVNPathUtil.removeTail(url), + SvnBundle.message("label.copy.select.location.dialog.copy.as"), dstName, false); + if (url != null) { + myToURLText.setText(url); } }); @@ -149,25 +142,13 @@ public class CreateBranchOrTagDialog extends DialogWrapper { myRevisionPanel.setRoot(mySrcVirtualFile); myRevisionPanel.setProject(myProject); - myRevisionPanel.setUrlProvider(new SvnRevisionPanel.UrlProvider() { - public String getUrl() { - return mySrcURL; - } - }); + myRevisionPanel.setUrlProvider(() -> mySrcURL); updateBranchTagBases(); - myRevisionPanel.addChangeListener(new ChangeListener() { - public void stateChanged(final ChangeEvent e) { - getOKAction().setEnabled(isOKActionEnabled()); - } - }); + myRevisionPanel.addChangeListener(e -> getOKAction().setEnabled(isOKActionEnabled())); init(); - ActionListener listener = new ActionListener() { - public void actionPerformed(ActionEvent e) { - updateControls(); - } - }; + ActionListener listener = e -> updateControls(); myWorkingCopyRadioButton.addActionListener(listener); myRepositoryRadioButton.addActionListener(listener); myBranchOrTagRadioButton.addActionListener(listener); @@ -179,23 +160,15 @@ public class CreateBranchOrTagDialog extends DialogWrapper { } }); updateToURL(); - myProjectButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - myRepositoryField.setText(myWcRootUrl); - } + myProjectButton.addActionListener(e -> myRepositoryField.setText(myWcRootUrl)); + myBranchTagBaseComboBox.addActionListener(e -> { + BranchConfigurationDialog.configureBranches(project, mySrcVirtualFile); + updateBranchTagBases(); + updateControls(); }); - myBranchTagBaseComboBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - BranchConfigurationDialog.configureBranches(project, mySrcVirtualFile); - updateBranchTagBases(); - updateControls(); - } - }); - myBranchTagBaseComboBox.getComboBox().addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - updateToURL(); - updateControls(); - } + myBranchTagBaseComboBox.getComboBox().addActionListener(e -> { + updateToURL(); + updateControls(); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/DefaultBranchConfigInitializer.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/DefaultBranchConfigInitializer.java index 3cddd429b7f6..e4ea80c4f49b 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/DefaultBranchConfigInitializer.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/DefaultBranchConfigInitializer.java @@ -27,7 +27,6 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.SvnUtil; import org.jetbrains.idea.svn.SvnVcs; import org.jetbrains.idea.svn.api.Depth; -import org.jetbrains.idea.svn.browse.DirectoryEntry; import org.jetbrains.idea.svn.browse.DirectoryEntryConsumer; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; @@ -130,20 +129,16 @@ public class DefaultBranchConfigInitializer implements Runnable { @NotNull private static DirectoryEntryConsumer createHandler(@NotNull final SvnBranchConfigurationNew result, @NotNull final SVNURL rootPath) { - return new DirectoryEntryConsumer() { + return entry -> { + if (entry.isDirectory()) { + SVNURL childUrl = rootPath.appendPath(entry.getName(), false); - @Override - public void consume(final DirectoryEntry entry) throws SVNException { - if (entry.isDirectory()) { - SVNURL childUrl = rootPath.appendPath(entry.getName(), false); - - if (StringUtil.endsWithIgnoreCase(entry.getName(), DEFAULT_TRUNK_NAME)) { - result.setTrunkUrl(childUrl.toString()); - } - else { - result.addBranches(childUrl.toString(), - new InfoStorage<>(new ArrayList<>(0), InfoReliability.defaultValues)); - } + if (StringUtil.endsWithIgnoreCase(entry.getName(), DEFAULT_TRUNK_NAME)) { + result.setTrunkUrl(childUrl.toString()); + } + else { + result.addBranches(childUrl.toString(), + new InfoStorage<>(new ArrayList<>(0), InfoReliability.defaultValues)); } } }; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/NewRootBunch.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/NewRootBunch.java index d8a869bb02ca..5347391b125e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/NewRootBunch.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/NewRootBunch.java @@ -17,10 +17,10 @@ package org.jetbrains.idea.svn.branchConfig; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.vcs.ProgressManagerQueue; import com.intellij.openapi.project.Project; -import org.jetbrains.annotations.CalledInBackground; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.vcs.ProgressManagerQueue; +import org.jetbrains.annotations.CalledInBackground; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.SvnVcs; @@ -62,12 +62,7 @@ public class NewRootBunch { } if (reload && override) { - myBranchesLoader.run(new Runnable() { - @Override - public void run() { - reloadBranches(root, previous, config.getValue()); - } - }); + myBranchesLoader.run(() -> reloadBranches(root, previous, config.getValue())); } } } @@ -104,16 +99,11 @@ public class NewRootBunch { public void reloadBranchesAsync(@NotNull final VirtualFile root, @NotNull final String branchLocation, @NotNull final InfoReliability reliability) { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - reloadBranches(root, branchLocation, reliability, true); - } - }); + ApplicationManager.getApplication().executeOnPooledThread(() -> reloadBranches(root, branchLocation, reliability, true)); } public void reloadBranches(@NotNull VirtualFile root, @Nullable SvnBranchConfigurationNew prev, @NotNull SvnBranchConfigurationNew next) { - final Set oldUrls = (prev == null) ? Collections.emptySet() : new HashSet<>(prev.getBranchUrls()); + final Set oldUrls = (prev == null) ? Collections.emptySet() : new HashSet<>(prev.getBranchUrls()); final SvnVcs vcs = SvnVcs.getInstance(myProject); if (!vcs.isVcsBackgroundOperationsAllowed(root)) return; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SelectBranchPopup.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SelectBranchPopup.java index ed0b987f56ba..0ee3fda23d2b 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SelectBranchPopup.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SelectBranchPopup.java @@ -168,25 +168,13 @@ public class SelectBranchPopup { @Override public PopupStep onChosen(final String selectedValue, final boolean finalChoice) { if (CONFIGURE_MESSAGE.equals(selectedValue)) { - return doFinalStep(new Runnable() { - public void run() { - BranchConfigurationDialog.configureBranches(myProject, myVcsRoot); - } - }); + return doFinalStep(() -> BranchConfigurationDialog.configureBranches(myProject, myVcsRoot)); } else if (myTrunkString.equals(selectedValue)) { - return doFinalStep(new Runnable() { - public void run() { - myCallback.branchSelected(myProject, myConfiguration, myConfiguration.getTrunkUrl(), -1); - } - }); + return doFinalStep(() -> myCallback.branchSelected(myProject, myConfiguration, myConfiguration.getTrunkUrl(), -1)); } else if (!myTopLevel || selectedValue.equals(myConfiguration.getTrunkUrl())) { - return doFinalStep(new Runnable() { - public void run() { - myCallback.branchSelected(myProject, myConfiguration, selectedValue, -1); - } - }); + return doFinalStep(() -> myCallback.branchSelected(myProject, myConfiguration, selectedValue, -1)); } else { showBranchPopup(selectedValue); @@ -238,35 +226,18 @@ public class SelectBranchPopup { .setTitle(SVNPathUtil.tail(selectedValue)) .setResizable(true) //.setDimensionServiceKey("Svn.CompareWithBranchPopup") - .setItemChoosenCallback(new Runnable() { - public void run() { - if (REFRESH_MESSAGE.equals(branchList.getSelectedValue())) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - loadBranches(selectedValue, new Runnable() { - @Override - public void run() { - showBranchPopup(selectedValue); - } - }); - } - }); - return; - } - SvnBranchItem item = (SvnBranchItem)branchList.getSelectedValue(); - if (item != null) { - myCallback.branchSelected(myProject, myConfiguration, item.getUrl(), item.getRevision()); - } + .setItemChoosenCallback(() -> { + if (REFRESH_MESSAGE.equals(branchList.getSelectedValue())) { + SwingUtilities.invokeLater(() -> loadBranches(selectedValue, () -> showBranchPopup(selectedValue))); + return; } - }) - .setFilteringEnabled(new NullableFunction() { - @Nullable - @Override - public String fun(Object item) { - return item instanceof SvnBranchItem ? getBranchName((SvnBranchItem)item) : null; + SvnBranchItem item = (SvnBranchItem)branchList.getSelectedValue(); + if (item != null) { + myCallback.branchSelected(myProject, myConfiguration, item.getUrl(), item.getRevision()); } }) + .setFilteringEnabled( + (NullableFunction)item -> item instanceof SvnBranchItem ? getBranchName((SvnBranchItem)item) : null) .createPopup(); showPopupAt(popup); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SvnBranchConfigurationManager.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SvnBranchConfigurationManager.java index 9771c31c0de9..693e366105bc 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SvnBranchConfigurationManager.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SvnBranchConfigurationManager.java @@ -62,18 +62,11 @@ public class SvnBranchConfigurationManager implements PersistentStateComponent ApplicationManager.getApplication().runReadAction(() -> { + if (myProject.isDisposed()) return; + myBranchesLoader.start(); + })); myBunch = new NewRootBunch(project, myBranchesLoader); } @@ -189,22 +182,17 @@ public class SvnBranchConfigurationManager implements PersistentStateComponent> branchPoints) { - ((ProjectLevelVcsManagerImpl) myVcsManager).addInitializationRequest(VcsInitObject.BRANCHES, new Runnable() { - public void run() { - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - public void run() { - try { - for (Pair pair : branchPoints) { - myBunch.reloadBranches(pair.getFirst(), null, pair.getSecond()); - } - } - catch (ProcessCanceledException e) { - // - } + ((ProjectLevelVcsManagerImpl)myVcsManager) + .addInitializationRequest(VcsInitObject.BRANCHES, () -> ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + for (Pair pair : branchPoints) { + myBunch.reloadBranches(pair.getFirst(), null, pair.getSecond()); } - }); - } - }); + } + catch (ProcessCanceledException e) { + // + } + })); } private List getStored(String branchUrl) { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SvnBranchConfigurationNew.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SvnBranchConfigurationNew.java index 6e4e066e6545..b89d28429722 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SvnBranchConfigurationNew.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/branchConfig/SvnBranchConfigurationNew.java @@ -19,7 +19,6 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.ObjectsConvertor; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.containers.Convertor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.SvnUtil; @@ -64,12 +63,7 @@ public class SvnBranchConfigurationNew { public List getBranchUrls() { final ArrayList result = new ArrayList<>(myBranchMap.keySet()); - final List cutList = ObjectsConvertor.convert(result, new Convertor() { - @Override - public String convert(String s) { - return cutEndSlash(s); - } - }); + final List cutList = ObjectsConvertor.convert(result, s -> cutEndSlash(s)); Collections.sort(cutList); return cutList; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/IdeaCommitHandler.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/IdeaCommitHandler.java index 2dc46692cf59..4708b760f9da 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/IdeaCommitHandler.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/IdeaCommitHandler.java @@ -121,12 +121,8 @@ public class IdeaCommitHandler implements CommitEventHandler, ProgressTracker { private void trackDeletedFile(@NotNull ProgressEvent event) { @NonNls final String filePath = "file://" + event.getFile().getAbsolutePath().replace(File.separatorChar, '/'); - VirtualFile virtualFile = ApplicationManager.getApplication().runReadAction(new Computable() { - @Nullable - public VirtualFile compute() { - return VirtualFileManager.getInstance().findFileByUrl(filePath); - } - }); + VirtualFile virtualFile = ApplicationManager.getApplication() + .runReadAction((Computable)() -> VirtualFileManager.getInstance().findFileByUrl(filePath)); if (virtualFile != null) { myDeletedFiles.add(virtualFile); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnCheckinEnvironment.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnCheckinEnvironment.java index 40bc167e2533..6a30cf95eacd 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnCheckinEnvironment.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnCheckinEnvironment.java @@ -22,7 +22,6 @@ import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.MessageType; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vcs.CheckinProjectPanel; import com.intellij.openapi.vcs.FilePath; @@ -135,16 +134,8 @@ public class SvnCheckinEnvironment implements CheckinEnvironment { final Project project = mySvnVcs.getProject(); final String message = SvnBundle.message("status.text.comitted.revision", committedRevisions); if (feedback == null) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - new VcsBalloonProblemNotifier(project, message, MessageType.INFO).run(); - } - }, new Condition() { - @Override - public boolean value(Object o) { - return (! project.isOpen()) || project.isDisposed(); - } - }); + ApplicationManager.getApplication().invokeLater(() -> new VcsBalloonProblemNotifier(project, message, MessageType.INFO).run(), + o -> (!project.isOpen()) || project.isDisposed()); } else { feedback.add("Subversion: " + message); } @@ -207,11 +198,9 @@ public class SvnCheckinEnvironment implements CheckinEnvironment { doCommit(committables, preparedComment, exception, feedback); } else if (ApplicationManager.getApplication().isDispatchThread()) { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - doCommit(committables, preparedComment, exception, feedback); - } - }, SvnBundle.message("progress.title.commit"), false, mySvnVcs.getProject()); + ProgressManager.getInstance().runProcessWithProgressSynchronously( + () -> doCommit(committables, preparedComment, exception, feedback), SvnBundle.message("progress.title.commit"), false, + mySvnVcs.getProject()); } else { doCommit(committables, preparedComment, exception, feedback); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnCheckinHandlerFactory.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnCheckinHandlerFactory.java index 2186eb448296..1dfd2528b52c 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnCheckinHandlerFactory.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnCheckinHandlerFactory.java @@ -115,12 +115,10 @@ public class SvnCheckinHandlerFactory extends VcsCheckinHandlerFactory { } } if (paths.isEmpty()) return; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - AutoSvnUpdater.run(new AutoSvnUpdater(project, paths.toArray(new FilePath[paths.size()])), ActionInfo.UPDATE.getActionName()); - } - }, ModalityState.NON_MODAL); + ApplicationManager.getApplication().invokeLater( + () -> AutoSvnUpdater + .run(new AutoSvnUpdater(project, paths.toArray(new FilePath[paths.size()])), ActionInfo.UPDATE.getActionName()), + ModalityState.NON_MODAL); } } }; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnKitCheckinClient.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnKitCheckinClient.java index 62e69cd5865c..60b15df9bd88 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnKitCheckinClient.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkin/SvnKitCheckinClient.java @@ -20,7 +20,6 @@ import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.svn.api.BaseSvnClient; @@ -83,12 +82,7 @@ public class SvnKitCheckinClient extends BaseSvnClient implements CheckinClient @NotNull private static CommitInfo[] convert(@NotNull SVNCommitInfo[] infos) { - return ContainerUtil.map(infos, new Function() { - @Override - public CommitInfo fun(SVNCommitInfo info) { - return new CommitInfo.Builder(info.getNewRevision(), info.getDate(), info.getAuthor()) - .setError(info.getErrorMessage()).build(); - } - }, new CommitInfo[0]); + return ContainerUtil.map(infos, info -> new CommitInfo.Builder(info.getNewRevision(), info.getDate(), info.getAuthor()) + .setError(info.getErrorMessage()).build(), new CommitInfo[0]); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkout/SvnCheckoutProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkout/SvnCheckoutProvider.java index 70f0e3d6f6cc..998651d75b8a 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkout/SvnCheckoutProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkout/SvnCheckoutProvider.java @@ -80,7 +80,7 @@ public class SvnCheckoutProvider implements CheckoutProvider { public static void doCheckout(@NotNull Project project, @NotNull File target, final String url, final SVNRevision revision, final Depth depth, final boolean ignoreExternals, @Nullable final Listener listener) { - if (! target.exists()) { + if (!target.exists()) { target.mkdirs(); } @@ -102,16 +102,17 @@ public class SvnCheckoutProvider implements CheckoutProvider { } public static void checkout(final Project project, - final File target, - final String url, - final SVNRevision revision, - final Depth depth, - final boolean ignoreExternals, - final Listener listener, final WorkingCopyFormat selectedFormat) { + final File target, + final String url, + final SVNRevision revision, + final Depth depth, + final boolean ignoreExternals, + final Listener listener, final WorkingCopyFormat selectedFormat) { final Ref checkoutSuccessful = new Ref<>(); final Exception[] exception = new Exception[1]; final Task.Backgroundable checkoutBackgroundTask = new Task.Backgroundable(project, - message("message.title.check.out"), true, VcsConfiguration.getInstance(project).getCheckoutOption()) { + message("message.title.check.out"), true, + VcsConfiguration.getInstance(project).getCheckoutOption()) { public void run(@NotNull final ProgressIndicator indicator) { final WorkingCopyFormat format = selectedFormat == null ? UNKNOWN : selectedFormat; @@ -170,7 +171,7 @@ public class SvnCheckoutProvider implements CheckoutProvider { private static void notifyRootManagerIfUnderProject(final Project project, final File directory) { if (project.isDefault()) return; final ProjectLevelVcsManagerEx plVcsManager = ProjectLevelVcsManagerEx.getInstanceEx(project); - final SvnVcs vcs = (SvnVcs) plVcsManager.findVcsByName(SvnVcs.VCS_NAME); + final SvnVcs vcs = (SvnVcs)plVcsManager.findVcsByName(SvnVcs.VCS_NAME); final VirtualFile[] files = vcs.getSvnFileUrlMapping().getNotFilteredRoots(); for (VirtualFile file : files) { @@ -194,20 +195,18 @@ public class SvnCheckoutProvider implements CheckoutProvider { final VcsException[] exception = new VcsException[1]; final SvnVcs vcs = SvnVcs.getInstance(project); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - ProgressTracker handler = new CheckoutEventHandler(vcs, true, progressIndicator); - try { - progressIndicator.setText(message("progress.text.export", target.getAbsolutePath())); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + ProgressTracker handler = new CheckoutEventHandler(vcs, true, progressIndicator); + try { + progressIndicator.setText(message("progress.text.export", target.getAbsolutePath())); - SvnTarget from = SvnTarget.fromURL(url); - ExportClient client = vcs.getFactoryFromSettings().createExportClient(); - client.export(from, target, SVNRevision.HEAD, depth, eolStyle, force, ignoreExternals, handler); - } - catch (VcsException e) { - exception[0] = e; - } + SvnTarget from = SvnTarget.fromURL(url); + ExportClient client = vcs.getFactoryFromSettings().createExportClient(); + client.export(from, target, SVNRevision.HEAD, depth, eolStyle, force, ignoreExternals, handler); + } + catch (VcsException e) { + exception[0] = e; } }, message("message.title.export"), true, project); if (exception[0] != null) { @@ -225,46 +224,36 @@ public class SvnCheckoutProvider implements CheckoutProvider { final SvnVcs vcs = SvnVcs.getInstance(project); final String targetPath = FileUtil.toSystemIndependentName(target.getAbsolutePath()); - ExclusiveBackgroundVcsAction.run(project, new Runnable() { - public void run() { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - final FileIndexFacade facade = PeriodicalTasksCloser.getInstance().safeGetService(project, FileIndexFacade.class); - ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); - try { - progressIndicator.setText(message("progress.text.import", target.getAbsolutePath())); + ExclusiveBackgroundVcsAction.run(project, () -> ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + final FileIndexFacade facade = PeriodicalTasksCloser.getInstance().safeGetService(project, FileIndexFacade.class); + ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); + try { + progressIndicator.setText(message("progress.text.import", target.getAbsolutePath())); - final VirtualFile targetVf = SvnUtil.getVirtualFile(targetPath); - if (targetVf == null) { - errorMessage.set("Can not find file: " + targetPath); - } else { - final boolean isInContent = getApplication().runReadAction(new Computable() { - @Override - public Boolean compute() { - return facade.isInContent(targetVf); - } - }); - CommitEventHandler handler = new IdeaCommitHandler(progressIndicator); - boolean useFileFilter = !project.isDefault() && isInContent; - ISVNCommitHandler commitHandler = - useFileFilter ? new MyFilter(LocalFileSystem.getInstance(), new SvnExcludingIgnoredOperation.Filter(project)) : null; - long revision = vcs.getFactoryFromSettings().createImportClient() - .doImport(target, url, depth, message, includeIgnored, handler, commitHandler); + final VirtualFile targetVf = SvnUtil.getVirtualFile(targetPath); + if (targetVf == null) { + errorMessage.set("Can not find file: " + targetPath); + } + else { + final boolean isInContent = getApplication().runReadAction((Computable)() -> facade.isInContent(targetVf)); + CommitEventHandler handler = new IdeaCommitHandler(progressIndicator); + boolean useFileFilter = !project.isDefault() && isInContent; + ISVNCommitHandler commitHandler = + useFileFilter ? new MyFilter(LocalFileSystem.getInstance(), new SvnExcludingIgnoredOperation.Filter(project)) : null; + long revision = vcs.getFactoryFromSettings().createImportClient() + .doImport(target, url, depth, message, includeIgnored, handler, commitHandler); - if (revision > 0) { - StatusBar.Info.set(message("status.text.comitted.revision", revision), project); - } - } - } - catch (VcsException e) { - errorMessage.set(e.getMessage()); - } + if (revision > 0) { + StatusBar.Info.set(message("status.text.comitted.revision", revision), project); } - }, message("message.title.import"), true, project); + } } - }); - - if (! errorMessage.isNull()) { + catch (VcsException e) { + errorMessage.set(e.getMessage()); + } + }, message("message.title.import"), true, project)); + + if (!errorMessage.isNull()) { showErrorDialog(message("message.text.cannot.import", errorMessage.get()), message("message.title.import")); } } @@ -323,29 +312,23 @@ public class SvnCheckoutProvider implements CheckoutProvider { final ModalityState dialogState = any(); dialog.startLoading(); - getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - final List formats = loadSupportedFormats(); + getApplication().executeOnPooledThread(() -> { + final List formats = loadSupportedFormats(); - getApplication().invokeLater(new Runnable() { - @Override - public void run() { - final String errorMessage = error.get(); + getApplication().invokeLater(() -> { + final String errorMessage = error.get(); - if (errorMessage != null) { - dialog.doCancelAction(); - showErrorDialog(message("message.text.cannot.load.supported.formats", errorMessage), - message("message.title.check.out")); - } - else { - dialog.setSupported(formats); - dialog.setData(getFirstItem(formats, UNKNOWN)); - dialog.stopLoading(); - } - } - }, dialogState); - } + if (errorMessage != null) { + dialog.doCancelAction(); + showErrorDialog(message("message.text.cannot.load.supported.formats", errorMessage), + message("message.title.check.out")); + } + else { + dialog.setSupported(formats); + dialog.setData(getFirstItem(formats, UNKNOWN)); + dialog.stopLoading(); + } + }, dialogState); }); return dialog.showAndGet() ? dialog.getUpgradeMode() : UNKNOWN; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/Command.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/Command.java index 72139267c1fd..57874ea7ae55 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/Command.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/Command.java @@ -1,7 +1,6 @@ package org.jetbrains.idea.svn.commandLine; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -116,12 +115,7 @@ public class Command { @Nullable public List getTargetsPaths() { - return ContainerUtil.isEmpty(myTargets) ? null : ContainerUtil.map(myTargets, new Function() { - @Override - public String fun(File file) { - return CommandUtil.format(file.getAbsolutePath(), null); - } - }); + return ContainerUtil.isEmpty(myTargets) ? null : ContainerUtil.map(myTargets, file -> CommandUtil.format(file.getAbsolutePath(), null)); } @Nullable diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/CommandRuntime.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/CommandRuntime.java index 09fbdec818ed..b13dff6fc93a 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/CommandRuntime.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/CommandRuntime.java @@ -16,7 +16,6 @@ package org.jetbrains.idea.svn.commandLine; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; @@ -202,12 +201,7 @@ public class CommandRuntime { authCases.add(new UsernamePasswordCallback(myAuthenticationService, url)); } - return ContainerUtil.find(authCases, new Condition() { - @Override - public boolean value(AuthCallbackCase authCase) { - return authCase.canHandle(errText); - } - }); + return ContainerUtil.find(authCases, authCase -> authCase.canHandle(errText)); } private void cleanup(@NotNull CommandExecutor executor, @NotNull File workingDirectory) throws SvnBindException { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/ProxyCallback.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/ProxyCallback.java index a3afaf9a5c0c..677cfbc7ea66 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/ProxyCallback.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/ProxyCallback.java @@ -16,7 +16,6 @@ package org.jetbrains.idea.svn.commandLine; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; @@ -75,12 +74,7 @@ public class ProxyCallback extends AuthCallbackCase { // TODO: This is quite messy logic for determining group for host - either ProxyCallback could be unified with ProxyModule // TODO: or group name resolved in ProxyModule could be saved in Command instance. // TODO: This will be done later after corresponding refactorings. - String proxyHostParameter = ContainerUtil.find(command.getParameters(), new Condition() { - @Override - public boolean value(String s) { - return s.contains("http-proxy-port"); - } - }); + String proxyHostParameter = ContainerUtil.find(command.getParameters(), s -> s.contains("http-proxy-port")); if (!StringUtil.isEmpty(proxyHostParameter) && myUrl != null && myProxyAuthentication != null) { String group = getHostGroup(proxyHostParameter); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/SvnBindException.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/SvnBindException.java index f7f14605e509..bddeaf18f609 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/SvnBindException.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/SvnBindException.java @@ -96,12 +96,7 @@ public class SvnBindException extends VcsException { public boolean containsCategory(int category) { final int categoryCode = getCategoryCode(category); - Condition belongsToCategoryCondition = new Condition() { - @Override - public boolean value(Integer code) { - return getCategoryCode(code) == categoryCode; - } - }; + Condition belongsToCategoryCondition = code -> getCategoryCode(code) == categoryCode; return ContainerUtil.exists(errors.keySet(), belongsToCategoryCondition) || ContainerUtil.exists(warnings.keySet(), belongsToCategoryCondition); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/TerminalSshModule.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/TerminalSshModule.java index a6896d68cdd3..4d961ac729ae 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/TerminalSshModule.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/TerminalSshModule.java @@ -90,13 +90,10 @@ public class TerminalSshModule extends BaseTerminalModule { final Project project = myRuntime.getVcs().getProject(); final Ref answer = new Ref<>(); - Runnable command = new Runnable() { - @Override - public void run() { - final ServerSSHDialog dialog = new ServerSSHDialog(project, true, unknownHost, fingerprintAlgorithm, hostFingerprint); - dialog.show(); - answer.set(dialog.getResult()); - } + Runnable command = () -> { + final ServerSSHDialog dialog = new ServerSSHDialog(project, true, unknownHost, fingerprintAlgorithm, hostFingerprint); + dialog.show(); + answer.set(dialog.getResult()); }; // Use ModalityState.any() as currently ssh credentials in terminal mode are requested in the thread that reads output and not in diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/WinTerminalExecutor.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/WinTerminalExecutor.java index 839ae491559a..69167238b90d 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/WinTerminalExecutor.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/WinTerminalExecutor.java @@ -20,7 +20,6 @@ import com.intellij.execution.process.ProcessWrapper; import com.intellij.execution.util.ExecUtil; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -139,12 +138,7 @@ public class WinTerminalExecutor extends TerminalExecutor { @NotNull @Override protected List escapeArguments(@NotNull List arguments) { - return ContainerUtil.map(arguments, new Function() { - @Override - public String fun(String argument) { - return needQuote(argument) && !isQuoted(argument) ? quote(argument) : argument; - } - }); + return ContainerUtil.map(arguments, argument -> needQuote(argument) && !isQuoted(argument) ? quote(argument) : argument); } @NotNull diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/config/ConfigureProxiesOptionsPanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/config/ConfigureProxiesOptionsPanel.java index b14efc89fbd9..f8414986d11e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/config/ConfigureProxiesOptionsPanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/config/ConfigureProxiesOptionsPanel.java @@ -22,11 +22,7 @@ import com.intellij.ui.InsertPathAction; import org.jetbrains.idea.svn.SvnBundle; import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import javax.swing.text.JTextComponent; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.ArrayList; @@ -113,12 +109,10 @@ public class ConfigureProxiesOptionsPanel implements RepositoryUrlsListener { initRepositories(); putPatternsListener(); - myTestConnectionButton.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - final String value = (String) myRepositoriesList.getSelectedValue(); - if ((value != null) && (myTestConnectionPerformer.enabled())) { - myTestConnectionPerformer.execute(value); - } + myTestConnectionButton.addActionListener(e -> { + final String value = (String)myRepositoriesList.getSelectedValue(); + if ((value != null) && (myTestConnectionPerformer.enabled())) { + myTestConnectionPerformer.execute(value); } }); } @@ -146,11 +140,8 @@ public class ConfigureProxiesOptionsPanel implements RepositoryUrlsListener { final ListSelectionModel selectionModel = new DefaultListSelectionModel(); selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); myRepositoriesList.setSelectionModel(selectionModel); - myRepositoriesList.addListSelectionListener(new ListSelectionListener() { - public void valueChanged(final ListSelectionEvent e) { - myTestConnectionButton.setEnabled(myTestConnectionPerformer.enabled() && (myRepositoriesList.getSelectedValue() != null)); - } - }); + myRepositoriesList.addListSelectionListener( + e -> myTestConnectionButton.setEnabled(myTestConnectionPerformer.enabled() && (myRepositoriesList.getSelectedValue() != null))); } private void fillMappings() { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/config/SvnConfigureProxiesComponent.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/config/SvnConfigureProxiesComponent.java index a83379b88526..39ffc92864ad 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/config/SvnConfigureProxiesComponent.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/config/SvnConfigureProxiesComponent.java @@ -21,7 +21,6 @@ import com.intellij.openapi.actionSystem.CommonShortcuts; import com.intellij.openapi.actionSystem.CustomShortcutSet; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.ui.MasterDetailsComponent; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Ref; import com.intellij.util.IconUtil; import com.intellij.util.PlatformIcons; @@ -87,7 +86,7 @@ public class SvnConfigureProxiesComponent extends MasterDetailsComponent { private void addGroup(final ProxyGroup template) { final ProxyGroup group; if (template == null) { - group = new ProxyGroup(getNewName(), "", ContainerUtil.newHashMap()); + group = new ProxyGroup(getNewName(), "", ContainerUtil.newHashMap()); } else { group = new ProxyGroup(getNewName(), template.getPatterns(), template.getProperties()); } @@ -163,17 +162,15 @@ public class SvnConfigureProxiesComponent extends MasterDetailsComponent { }); - result.add(new MyDeleteAction(forAll(new Condition(){ - public boolean value(final Object o) { - if (o instanceof MyNode) { - final MyNode node = (MyNode) o; - if (node.getConfigurable() instanceof GroupConfigurable) { - final ProxyGroup group = ((GroupConfigurable) node.getConfigurable()).getEditableObject(); - return ! group.isDefault(); - } + result.add(new MyDeleteAction(forAll(o -> { + if (o instanceof MyNode) { + final MyNode node = (MyNode)o; + if (node.getConfigurable() instanceof GroupConfigurable) { + final ProxyGroup group = ((GroupConfigurable)node.getConfigurable()).getEditableObject(); + return !group.isDefault(); } - return false; } + return false; })) { public void actionPerformed(final AnActionEvent e) { final TreePath path = myTree.getSelectionPath(); @@ -259,7 +256,7 @@ public class SvnConfigureProxiesComponent extends MasterDetailsComponent { myRoot.removeAllChildren(); DefaultProxyGroup defaultProxyGroup = myManager.getDefaultGroup(); - defaultProxyGroup = (defaultProxyGroup == null) ? new DefaultProxyGroup(Collections.emptyMap()) : defaultProxyGroup; + defaultProxyGroup = (defaultProxyGroup == null) ? new DefaultProxyGroup(Collections.emptyMap()) : defaultProxyGroup; final Map userGroups = myManager.getGroups(); myRoot.add(createNodeForObject(defaultProxyGroup)); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/config/SvnConfigureProxiesDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/config/SvnConfigureProxiesDialog.java index b2bb6633e77f..84d7f71042d0 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/config/SvnConfigureProxiesDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/config/SvnConfigureProxiesDialog.java @@ -65,7 +65,7 @@ public class SvnConfigureProxiesDialog extends DialogWrapper implements Validati myTabbedPane.setSelectedComponent(component); String errorPrefix = myTabbedPane.getTitleAt(myTabbedPane.indexOfComponent(component)) + ": "; - setOKActionEnabled(! forbidSave); + setOKActionEnabled(!forbidSave); setInvalid(errorPrefix + text, myTabbedPane); } @@ -83,7 +83,8 @@ public class SvnConfigureProxiesDialog extends DialogWrapper implements Validati private boolean applyToTab(final SvnConfigureProxiesComponent component) { try { component.apply(); - } catch (ConfigurationException e) { + } + catch (ConfigurationException e) { myTabbedPane.setSelectedComponent(component.createComponent()); setInvalid(e.getMessage(), myTabbedPane); return false; @@ -97,10 +98,10 @@ public class SvnConfigureProxiesDialog extends DialogWrapper implements Validati } private boolean applyImpl() { - if (! applyToTab(myUserTab)) { + if (!applyToTab(myUserTab)) { return false; } - if (! applyToTab(mySystemTab)) { + if (!applyToTab(mySystemTab)) { return false; } return true; @@ -108,7 +109,7 @@ public class SvnConfigureProxiesDialog extends DialogWrapper implements Validati protected void doOKAction() { if (getOKAction().isEnabled()) { - if(! applyImpl()) { + if (!applyImpl()) { return; } myValidator.stop(); @@ -119,29 +120,28 @@ public class SvnConfigureProxiesDialog extends DialogWrapper implements Validati public void execute(final String url) { Messages.showInfoMessage(myProject, SvnBundle.message("dialog.edit.http.proxies.settings.test.connection.settings.will.be.stored.text"), SvnBundle.message("dialog.edit.http.proxies.settings.test.connection.settings.will.be.stored.title")); - if(! applyImpl()) { + if (!applyImpl()) { return; } final Ref excRef = new Ref<>(); final ProgressManager pm = ProgressManager.getInstance(); - pm.runProcessWithProgressSynchronously(new Runnable() { - public void run() { - final ProgressIndicator pi = pm.getProgressIndicator(); - if (pi != null) { - pi.setText("Connecting to " + url); - } - try { - SvnVcs.getInstance(myProject).getInfo(SvnUtil.createUrl(url), SVNRevision.HEAD); - } - catch (SvnBindException e) { - excRef.set(e); - } + pm.runProcessWithProgressSynchronously(() -> { + final ProgressIndicator pi = pm.getProgressIndicator(); + if (pi != null) { + pi.setText("Connecting to " + url); + } + try { + SvnVcs.getInstance(myProject).getInfo(SvnUtil.createUrl(url), SVNRevision.HEAD); + } + catch (SvnBindException e) { + excRef.set(e); } }, "Test connection", true, myProject); - if (! excRef.isNull()) { + if (!excRef.isNull()) { Messages.showErrorDialog(myProject, excRef.get().getMessage(), SvnBundle.message("dialog.edit.http.proxies.settings.test.connection.error.title")); - } else { + } + else { Messages.showInfoMessage(myProject, SvnBundle.message("dialog.edit.http.proxies.settings.test.connection.succes.text"), SvnBundle.message("dialog.edit.http.proxies.settings.test.connection.succes.title")); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/AddRepositoryLocationDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/AddRepositoryLocationDialog.java index 15c28f6ce14b..15b822e06371 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/AddRepositoryLocationDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/AddRepositoryLocationDialog.java @@ -25,9 +25,11 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.commandLine.SvnBindException; import javax.swing.*; -import java.awt.GridBagConstraints; import java.awt.*; -import java.awt.event.*; +import java.awt.event.InputMethodEvent; +import java.awt.event.InputMethodListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; import java.util.List; import static com.intellij.util.containers.ContainerUtil.sorted; @@ -107,11 +109,7 @@ public class AddRepositoryLocationDialog extends DialogWrapper { } }); - myCombo.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - validateMe(); - } - }); + myCombo.addActionListener(e -> validateMe()); validateMe(); JPanel wrapper = new JPanel(new GridBagLayout()); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CheckoutDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CheckoutDialog.java index 8e02d59b94c1..b24c34cfec02 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CheckoutDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CheckoutDialog.java @@ -21,8 +21,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.svn.SvnBundle; import javax.swing.*; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; public class CheckoutDialog extends RepositoryBrowserDialog { private final CheckoutProvider.Listener myListener; @@ -36,11 +34,9 @@ public class CheckoutDialog extends RepositoryBrowserDialog { super.init(); setTitle(SvnBundle.message("checkout.dialog.title")); setOKButtonText(SvnBundle.message("checkout.dialog.button")); - getRepositoryBrowser().addChangeListener(new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - if (getOKAction() != null) { - getOKAction().setEnabled(getRepositoryBrowser().getSelectedURL() != null); - } + getRepositoryBrowser().addChangeListener(e -> { + if (getOKAction() != null) { + getOKAction().setEnabled(getRepositoryBrowser().getSelectedURL() != null); } }); getOKAction().setEnabled(getRepositoryBrowser().getSelectedURL() != null); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CopiesPanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CopiesPanel.java index 6ce0bbd138e4..e09efa34a92c 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CopiesPanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CopiesPanel.java @@ -17,7 +17,6 @@ package org.jetbrains.idea.svn.dialogs; import com.intellij.ide.DataManager; import com.intellij.notification.*; -import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; @@ -40,11 +39,9 @@ import com.intellij.ui.components.labels.LinkLabel; import com.intellij.ui.components.labels.LinkListener; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.Convertor; import com.intellij.util.io.EqualityPolicy; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; -import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.*; @@ -106,64 +103,42 @@ public class CopiesPanel { myVcs = SvnVcs.getInstance(myProject); myCurrentInfoList = null; - final Runnable focus = new Runnable() { - @Override - public void run() { - IdeFocusManager.getInstance(myProject).requestFocus(myRefreshLabel, true); - } - }; - final Runnable refreshView = new Runnable() { - @Override - public void run() { - final List infoList = myVcs.getWcInfosWithErrors(); - final boolean hasErrors = !myVcs.getSvnFileUrlMapping().getErrorRoots().isEmpty(); - final List supportedFormats = getSupportedFormats(); - Runnable runnable = new Runnable() { - @Override - public void run() { - if (myCurrentInfoList != null) { - final List> newList = - ObjectsConvertor.convert(infoList, new Convertor>() { - @Override - public OverrideEqualsWrapper convert(WCInfo o) { - return new OverrideEqualsWrapper<>(InfoEqualityPolicy.getInstance(), o); - } - }, ObjectsConvertor.NOT_NULL); + final Runnable focus = () -> IdeFocusManager.getInstance(myProject).requestFocus(myRefreshLabel, true); + final Runnable refreshView = () -> { + final List infoList = myVcs.getWcInfosWithErrors(); + final boolean hasErrors = !myVcs.getSvnFileUrlMapping().getErrorRoots().isEmpty(); + final List supportedFormats = getSupportedFormats(); + Runnable runnable = () -> { + if (myCurrentInfoList != null) { + final List> newList = + ObjectsConvertor + .convert(infoList, o -> new OverrideEqualsWrapper<>(InfoEqualityPolicy.getInstance(), o), ObjectsConvertor.NOT_NULL); - if (Comparing.haveEqualElements(newList, myCurrentInfoList)) { - myRefreshLabel.setEnabled(true); - return; - } - myCurrentInfoList = newList; - } - Collections.sort(infoList, WCComparator.getInstance()); - updateList(infoList, supportedFormats); + if (Comparing.haveEqualElements(newList, myCurrentInfoList)) { myRefreshLabel.setEnabled(true); - showErrorNotification(hasErrors); - SwingUtilities.invokeLater(focus); + return; } - }; - ApplicationManager.getApplication().invokeLater(runnable, ModalityState.NON_MODAL); - } - }; - final Consumer refreshOnPooled = new Consumer() { - @Override - public void consume(Boolean somethingNew) { - if (Boolean.TRUE.equals(somethingNew)) { - if (ApplicationManager.getApplication().isUnitTestMode()) { - refreshView.run(); - } - else { - ApplicationManager.getApplication().executeOnPooledThread(refreshView); - } - } else { - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - myRefreshLabel.setEnabled(true); - } - }, ModalityState.NON_MODAL); + myCurrentInfoList = newList; } + Collections.sort(infoList, WCComparator.getInstance()); + updateList(infoList, supportedFormats); + myRefreshLabel.setEnabled(true); + showErrorNotification(hasErrors); + SwingUtilities.invokeLater(focus); + }; + ApplicationManager.getApplication().invokeLater(runnable, ModalityState.NON_MODAL); + }; + final Consumer refreshOnPooled = somethingNew -> { + if (Boolean.TRUE.equals(somethingNew)) { + if (ApplicationManager.getApplication().isUnitTestMode()) { + refreshView.run(); + } + else { + ApplicationManager.getApplication().executeOnPooledThread(refreshView); + } + } + else { + ApplicationManager.getApplication().invokeLater(() -> myRefreshLabel.setEnabled(true), ModalityState.NON_MODAL); } }; myConnection.subscribe(SvnVcs.ROOTS_RELOADED, refreshOnPooled); @@ -175,13 +150,10 @@ public class CopiesPanel { final JPanel panel = new JPanel(new BorderLayout()); panel.add(myPanel, BorderLayout.NORTH); holderPanel.add(panel, BorderLayout.WEST); - myRefreshLabel = new MyLinkLabel(myTextHeight, "Refresh", new LinkListener() { - @Override - public void linkSelected(LinkLabel aSource, Object aLinkData) { - if (myRefreshLabel.isEnabled()) { - myVcs.invokeRefreshSvnRoots(); - myRefreshLabel.setEnabled(false); - } + myRefreshLabel = new MyLinkLabel(myTextHeight, "Refresh", (aSource, aLinkData) -> { + if (myRefreshLabel.isEnabled()) { + myVcs.invokeRefreshSvnRoots(); + myRefreshLabel.setEnabled(false); } }); final JScrollPane pane = ScrollPaneFactory.createScrollPane(holderPanel); @@ -361,17 +333,11 @@ public class CopiesPanel { } private void mergeFrom(@NotNull final WCInfo wcInfo, @NotNull final VirtualFile root, @Nullable final Component mergeLabel) { - SelectBranchPopup.showForBranchRoot(myProject, root, new SelectBranchPopup.BranchSelectedCallback() { - @Override - public void branchSelected(Project project, - @NotNull SvnBranchConfigurationNew configuration, - @NotNull String branchUrl, - long revision) { - String workingCopyUrlInSelectedBranch = getCorrespondingUrlInOtherBranch(configuration, wcInfo.getUrl(), branchUrl); - MergeContext mergeContext = new MergeContext(myVcs, workingCopyUrlInSelectedBranch, wcInfo, SVNPathUtil.tail(branchUrl), root); + SelectBranchPopup.showForBranchRoot(myProject, root, (project, configuration, branchUrl, revision) -> { + String workingCopyUrlInSelectedBranch = getCorrespondingUrlInOtherBranch(configuration, wcInfo.getUrl(), branchUrl); + MergeContext mergeContext = new MergeContext(myVcs, workingCopyUrlInSelectedBranch, wcInfo, SVNPathUtil.tail(branchUrl), root); - new QuickMerge(mergeContext, new QuickMergeInteractionImpl(mergeContext)).execute(); - } + new QuickMerge(mergeContext, new QuickMergeInteractionImpl(mergeContext)).execute(); }, "Select branch", mergeLabel); } @@ -453,15 +419,11 @@ public class CopiesPanel { } private static void registerHelp(@NotNull JComponent component) { - DataManager.registerDataProvider(component, new DataProvider() { - @Nullable - @Override - public Object getData(@NonNls String dataId) { - if (PlatformDataKeys.HELP_ID.is(dataId)) { - return "reference.vcs.svn.working.copies.information"; - } - return null; + DataManager.registerDataProvider(component, dataId -> { + if (PlatformDataKeys.HELP_ID.is(dataId)) { + return "reference.vcs.svn.working.copies.information"; } + return null; }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ImportDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ImportDialog.java index 50b22c1f8178..dc36c01f9f80 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ImportDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ImportDialog.java @@ -21,8 +21,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.svn.SvnBundle; import javax.swing.*; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; public class ImportDialog extends RepositoryBrowserDialog { public ImportDialog(Project project) { @@ -33,11 +31,9 @@ public class ImportDialog extends RepositoryBrowserDialog { super.init(); setTitle(SvnBundle.message("import.dialog.title")); setOKButtonText(SvnBundle.message("import.dialog.button")); - getRepositoryBrowser().addChangeListener(new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - if (getOKAction() != null) { - updateOKAction(); - } + getRepositoryBrowser().addChangeListener(e -> { + if (getOKAction() != null) { + updateOKAction(); } }); updateOKAction(); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/PropertiesComponent.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/PropertiesComponent.java index d3f8efebe5a0..671d3dfd9c1f 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/PropertiesComponent.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/PropertiesComponent.java @@ -46,8 +46,6 @@ import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc2.SvnTarget; import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import java.awt.*; @@ -96,19 +94,17 @@ public class PropertiesComponent extends JPanel { myTable.setModel(model); myTable.setShowVerticalLines(true); myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - myTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - public void valueChanged(ListSelectionEvent e) { - int index = myTable.getSelectedRow(); - if (index >= 0) { - Object value = myTable.getValueAt(index, 1); - if (value instanceof String) { - myTextArea.setText(((String) value)); - } else { - myTextArea.setText(""); - } + myTable.getSelectionModel().addListSelectionListener(e -> { + int index = myTable.getSelectedRow(); + if (index >= 0) { + Object value = myTable.getValueAt(index, 1); + if (value instanceof String) { + myTextArea.setText(((String) value)); } else { myTextArea.setText(""); } + } else { + myTextArea.setText(""); } }); myPopupActionGroup = createPopup(); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryBrowserComponent.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryBrowserComponent.java index 55252eca1542..fd8257584660 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryBrowserComponent.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryBrowserComponent.java @@ -31,7 +31,6 @@ import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.EditSourceOnDoubleClickHandler; import com.intellij.util.NotNullFunction; -import com.intellij.util.containers.Convertor; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -99,7 +98,9 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da } } - public void setRepositoryURL(SVNURL url, boolean showFiles, final NotNullFunction defaultExpanderFactory) { + public void setRepositoryURL(SVNURL url, + boolean showFiles, + final NotNullFunction defaultExpanderFactory) { RepositoryTreeModel model = new RepositoryTreeModel(myVCS, showFiles, this); model.setDefaultExpanderFactory(defaultExpanderFactory); @@ -121,7 +122,7 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da } public void expandNode(@NotNull final TreeNode treeNode) { - final TreeNode[] pathToNode = ((RepositoryTreeModel) myRepositoryTree.getModel()).getPathToRoot(treeNode); + final TreeNode[] pathToNode = ((RepositoryTreeModel)myRepositoryTree.getModel()).getPathToRoot(treeNode); if ((pathToNode != null) && (pathToNode.length > 0)) { final TreePath treePath = new TreePath(pathToNode); @@ -130,7 +131,7 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da } public Collection getExpandedSubTree(@NotNull final TreeNode treeNode) { - final TreeNode[] pathToNode = ((RepositoryTreeModel) myRepositoryTree.getModel()).getPathToRoot(treeNode); + final TreeNode[] pathToNode = ((RepositoryTreeModel)myRepositoryTree.getModel()).getPathToRoot(treeNode); final Enumeration expanded = myRepositoryTree.getExpandedDescendants(new TreePath(pathToNode)); @@ -138,30 +139,32 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da if (expanded != null) { while (expanded.hasMoreElements()) { final TreePath treePath = expanded.nextElement(); - result.add((TreeNode) treePath.getLastPathComponent()); + result.add((TreeNode)treePath.getLastPathComponent()); } } return result; } public boolean isExpanded(@NotNull final TreeNode treeNode) { - final TreeNode[] pathToNode = ((RepositoryTreeModel) myRepositoryTree.getModel()).getPathToRoot(treeNode); + final TreeNode[] pathToNode = ((RepositoryTreeModel)myRepositoryTree.getModel()).getPathToRoot(treeNode); return (pathToNode != null) && (pathToNode.length > 0) && myRepositoryTree.isExpanded(new TreePath(pathToNode)); } public void addURL(String url) { try { - ((RepositoryTreeModel) myRepositoryTree.getModel()).addRoot(SVNURL.parseURIEncoded(url)); - } catch (SVNException e) { + ((RepositoryTreeModel)myRepositoryTree.getModel()).addRoot(SVNURL.parseURIEncoded(url)); + } + catch (SVNException e) { // } } public void removeURL(String url) { try { - ((RepositoryTreeModel) myRepositoryTree.getModel()).removeRoot(SVNURL.parseURIEncoded(url)); - } catch (SVNException e) { + ((RepositoryTreeModel)myRepositoryTree.getModel()).removeRoot(SVNURL.parseURIEncoded(url)); + } + catch (SVNException e) { // } } @@ -174,7 +177,7 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da } Object element = selection.getLastPathComponent(); if (element instanceof RepositoryTreeNode) { - RepositoryTreeNode node = (RepositoryTreeNode) element; + RepositoryTreeNode node = (RepositoryTreeNode)element; return node.getSVNDirEntry(); } return null; @@ -194,7 +197,7 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da } Object element = selection.getLastPathComponent(); if (element instanceof RepositoryTreeNode) { - RepositoryTreeNode node = (RepositoryTreeNode) element; + RepositoryTreeNode node = (RepositoryTreeNode)element; return node.getURL(); } return null; @@ -222,15 +225,12 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da ScrollPaneFactory.createScrollPane(myRepositoryTree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); add(scrollPane, BorderLayout.CENTER); myRepositoryTree.setCellRenderer(new SvnRepositoryTreeCellRenderer()); - TreeSpeedSearch search = new TreeSpeedSearch(myRepositoryTree, new Convertor() { - @Override - public String convert(TreePath o) { - Object component = o.getLastPathComponent(); - if (component instanceof RepositoryTreeNode) { - return ((RepositoryTreeNode)component).getURL().toDecodedString(); - } - return null; + TreeSpeedSearch search = new TreeSpeedSearch(myRepositoryTree, o -> { + Object component = o.getLastPathComponent(); + if (component instanceof RepositoryTreeNode) { + return ((RepositoryTreeNode)component).getURL().toDecodedString(); } + return null; }); search.setComparator(new SpeedSearchComparator(false, true)); @@ -241,13 +241,13 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da public RepositoryTreeNode getSelectedNode() { TreePath selection = myRepositoryTree.getSelectionPath(); if (selection != null && selection.getLastPathComponent() instanceof RepositoryTreeNode) { - return (RepositoryTreeNode) selection.getLastPathComponent(); + return (RepositoryTreeNode)selection.getLastPathComponent(); } return null; } public void setSelectedNode(@NotNull final TreeNode node) { - final TreeNode[] pathNodes = ((RepositoryTreeModel) myRepositoryTree.getModel()).getPathToRoot(node); + final TreeNode[] pathNodes = ((RepositoryTreeModel)myRepositoryTree.getModel()).getPathToRoot(node); myRepositoryTree.setSelectionPath(new TreePath(pathNodes)); } @@ -267,10 +267,11 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da if (entry.getName().lastIndexOf('.') > 0 && !manager.getFileTypeByFileName(name).isBinary()) { SVNURL url = node.getURL(); final SvnFileRevision revision = new SvnFileRevision(myVCS, SVNRevision.UNDEFINED, SVNRevision.HEAD, url.toString(), - entry.getAuthor(), entry.getDate(), null, null); + entry.getAuthor(), entry.getDate(), null, null); return new VcsVirtualFile(node.getSVNDirEntry().getName(), revision, VcsFileSystem.getInstance()); - } else { + } + else { return null; } } @@ -295,7 +296,8 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da navigate(project, vcsFile, requestFocus); } } : null; - } else if (CommonDataKeys.PROJECT.is(dataId)) { + } + else if (CommonDataKeys.PROJECT.is(dataId)) { return myVCS.getProject(); } return null; @@ -305,6 +307,6 @@ public class RepositoryBrowserComponent extends JPanel implements Disposable, Da } public void setLazyLoadingExpander(final NotNullFunction expanderFactory) { - ((RepositoryTreeModel) myRepositoryTree.getModel()).setDefaultExpanderFactory(expanderFactory); + ((RepositoryTreeModel)myRepositoryTree.getModel()).setDefaultExpanderFactory(expanderFactory); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryBrowserDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryBrowserDialog.java index d10f0dd167b6..48b1a9167eea 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryBrowserDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryBrowserDialog.java @@ -575,31 +575,24 @@ public class RepositoryBrowserDialog extends DialogWrapper { boolean cancelable; if (dialog.isUnifiedDiff()) { final File targetFile = dialog.getTargetFile(); - command = new Runnable() { - public void run() { - targetFile.getParentFile().mkdirs(); - doUnifiedDiff(targetFile, sURL, tURL); - } + command = () -> { + targetFile.getParentFile().mkdirs(); + doUnifiedDiff(targetFile, sURL, tURL); }; cancelable = false; } else { - command = new Runnable() { - public void run() { - try { - doGraphicalDiff(sURL, tURL); - } - catch (final VcsException ex) { - //noinspection InstanceofCatchParameter - boolean isCancelled = ex instanceof SvnBindException && ((SvnBindException)ex).contains(SVNErrorCode.CANCELLED); + command = () -> { + try { + doGraphicalDiff(sURL, tURL); + } + catch (final VcsException ex) { + //noinspection InstanceofCatchParameter + boolean isCancelled = ex instanceof SvnBindException && ((SvnBindException)ex).contains(SVNErrorCode.CANCELLED); - if (!isCancelled) { - WaitForProgressToShow.runOrInvokeLaterAboveProgress(new Runnable() { - public void run() { - Messages.showErrorDialog(myProject, ex.getMessage(), "Error"); - } - }, null, myProject); - } + if (!isCancelled) { + WaitForProgressToShow + .runOrInvokeLaterAboveProgress(() -> Messages.showErrorDialog(myProject, ex.getMessage(), "Error"), null, myProject); } } }; @@ -800,19 +793,17 @@ public class RepositoryBrowserDialog extends DialogWrapper { private boolean doDelete(final SVNURL url, final String comment) { final Ref exception = new Ref<>(); final Project project = myBrowserComponent.getProject(); - Runnable command = new Runnable() { - public void run() { - ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - if (progress != null) { - progress.setText(SvnBundle.message("progres.text.deleting", url.toString())); - } - SvnVcs vcs = SvnVcs.getInstance(project); - try { - vcs.getFactoryFromSettings().createDeleteClient().delete(url, comment); - } - catch (VcsException e) { - exception.set(e); - } + Runnable command = () -> { + ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + if (progress != null) { + progress.setText(SvnBundle.message("progres.text.deleting", url.toString())); + } + SvnVcs vcs = SvnVcs.getInstance(project); + try { + vcs.getFactoryFromSettings().createDeleteClient().delete(url, comment); + } + catch (VcsException e) { + exception.set(e); } }; ProgressManager.getInstance().runProcessWithProgressSynchronously(command, SvnBundle.message("progress.title.browser.delete"), false, project); @@ -970,20 +961,18 @@ public class RepositoryBrowserDialog extends DialogWrapper { protected static void doMkdir(final SVNURL url, final String comment, final Project project) { final Ref exception = new Ref<>(); - Runnable command = new Runnable() { - public void run() { - ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - if (progress != null) { - progress.setText(SvnBundle.message("progress.text.browser.creating", url.toString())); - } - SvnVcs vcs = SvnVcs.getInstance(project); - SvnTarget target = SvnTarget.fromURL(url); - try { - vcs.getFactoryFromSettings().createBrowseClient().createDirectory(target, comment, false); - } - catch (VcsException e) { - exception.set(e); - } + Runnable command = () -> { + ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + if (progress != null) { + progress.setText(SvnBundle.message("progress.text.browser.creating", url.toString())); + } + SvnVcs vcs = SvnVcs.getInstance(project); + SvnTarget target = SvnTarget.fromURL(url); + try { + vcs.getFactoryFromSettings().createBrowseClient().createDirectory(target, comment, false); + } + catch (VcsException e) { + exception.set(e); } }; ProgressManager.getInstance().runProcessWithProgressSynchronously(command, SvnBundle.message("progress.text.create.remote.folder"), false, project); @@ -994,21 +983,20 @@ public class RepositoryBrowserDialog extends DialogWrapper { private void doCopy(final SVNURL src, final SVNURL dst, final boolean move, final String comment) { final Ref exception = new Ref<>(); - Runnable command = new Runnable() { - public void run() { - ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - if (progress != null) { - progress.setText((move ? SvnBundle.message("progress.text.browser.moving", src) : SvnBundle.message("progress.text.browser.copying", src))); - progress.setText2(SvnBundle.message("progress.text.browser.remote.destination", dst)); - } - SvnVcs vcs = SvnVcs.getInstance(myProject); - try { - vcs.getFactoryFromSettings().createCopyMoveClient().copy(SvnTarget.fromURL(src), SvnTarget.fromURL(dst), SVNRevision.HEAD, true, - move, comment, null); - } - catch (VcsException e) { - exception.set(e); - } + Runnable command = () -> { + ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + if (progress != null) { + progress.setText( + (move ? SvnBundle.message("progress.text.browser.moving", src) : SvnBundle.message("progress.text.browser.copying", src))); + progress.setText2(SvnBundle.message("progress.text.browser.remote.destination", dst)); + } + SvnVcs vcs = SvnVcs.getInstance(myProject); + try { + vcs.getFactoryFromSettings().createCopyMoveClient().copy(SvnTarget.fromURL(src), SvnTarget.fromURL(dst), SVNRevision.HEAD, true, + move, comment, null); + } + catch (VcsException e) { + exception.set(e); } }; String progressTitle = move ? SvnBundle.message("progress.title.browser.move") : SvnBundle.message("progress.title.browser.copy"); @@ -1118,12 +1106,10 @@ public class RepositoryBrowserDialog extends DialogWrapper { private void showDiffEditorResults(final Collection changes, String sourceTitle, String targetTitle) { final String title = SvnBundle.message("repository.browser.compare.title", sourceTitle, targetTitle); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - final ChangeListViewerDialog dlg = new ChangeListViewerDialog(myRepositoryBrowser, myProject, changes, true); - dlg.setTitle(title); - dlg.show(); - } + SwingUtilities.invokeLater(() -> { + final ChangeListViewerDialog dlg = new ChangeListViewerDialog(myRepositoryBrowser, myProject, changes, true); + dlg.setTitle(title); + dlg.show(); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryTreeRootNode.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryTreeRootNode.java index 7d5112b545bc..566a450de68a 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryTreeRootNode.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/RepositoryTreeRootNode.java @@ -21,7 +21,10 @@ import org.tmatesoft.svn.core.SVNURL; import javax.swing.tree.TreeNode; import java.text.Collator; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; public class RepositoryTreeRootNode implements TreeNode, Disposable { private final List myChildren; @@ -36,22 +39,14 @@ public class RepositoryTreeRootNode implements TreeNode, Disposable { Disposer.register(this, rootNode); myChildren.add(rootNode); } - Collections.sort(myChildren, new Comparator() { - public int compare(TreeNode o1, TreeNode o2) { - return Collator.getInstance().compare(o1.toString(), o2.toString()); - } - }); + Collections.sort(myChildren, (o1, o2) -> Collator.getInstance().compare(o1.toString(), o2.toString())); } public void addRoot(SVNURL url) { RepositoryTreeNode rootNode = new RepositoryTreeNode(myModel, this, url, url); Disposer.register(this, rootNode); myChildren.add(rootNode); - Collections.sort(myChildren, new Comparator() { - public int compare(TreeNode o1, TreeNode o2) { - return Collator.getInstance().compare(o1.toString(), o2.toString()); - } - }); + Collections.sort(myChildren, (o1, o2) -> Collator.getInstance().compare(o1.toString(), o2.toString())); myModel.nodesWereInserted(this, new int[]{myChildren.indexOf(rootNode)}); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SSHCredentialsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SSHCredentialsDialog.java index bacf38217bde..8cfff665bde5 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SSHCredentialsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SSHCredentialsDialog.java @@ -27,7 +27,6 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.ui.components.JBRadioButton; -import com.intellij.util.Consumer; import com.intellij.util.SystemProperties; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; @@ -47,7 +46,6 @@ import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.io.File; import java.io.IOException; -import java.util.List; /** * @author alex @@ -441,16 +439,13 @@ public class SSHCredentialsDialog extends DialogWrapper implements ActionListene .withHideIgnored(false) .withShowHiddenFiles(true); - FileChooser.chooseFiles(descriptor, myProject, file, new Consumer>() { - @Override - public void consume(List files) { - if (files.size() == 1) { - path[0] = FileUtil.toSystemDependentName(files.get(0).getPath()); - myKeyFileText.setText(path[0]); - } - checkKeyFile(); - updateOKButton(); + FileChooser.chooseFiles(descriptor, myProject, file, files -> { + if (files.size() == 1) { + path[0] = FileUtil.toSystemDependentName(files.get(0).getPath()); + myKeyFileText.setText(path[0]); } + checkKeyFile(); + updateOKButton(); }); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectCreateExternalTargetDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectCreateExternalTargetDialog.java index 733c311d6bc8..61f49dd874f0 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectCreateExternalTargetDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectCreateExternalTargetDialog.java @@ -27,8 +27,6 @@ import org.jetbrains.annotations.NotNull; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import javax.swing.*; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; import java.awt.*; import java.awt.event.*; import java.util.Set; @@ -65,15 +63,13 @@ public class SelectCreateExternalTargetDialog extends RepositoryBrowserDialog { myFollowRemoteTarget = true; setTitle("Select Target For External"); setOKButtonText("Select"); - getRepositoryBrowser().addChangeListener(new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - if (getOKAction() != null) { - final String selectedURL = getRepositoryBrowser().getSelectedURL(); - if (myFollowRemoteTarget && selectedURL != null) { - myFolderName.setText(SVNPathUtil.tail(selectedURL)); - } - checkEnabled(); + getRepositoryBrowser().addChangeListener(e -> { + if (getOKAction() != null) { + final String selectedURL = getRepositoryBrowser().getSelectedURL(); + if (myFollowRemoteTarget && selectedURL != null) { + myFolderName.setText(SVNPathUtil.tail(selectedURL)); } + checkEnabled(); } }); getOKAction().setEnabled(getRepositoryBrowser().getSelectedURL() != null); @@ -178,12 +174,7 @@ public class SelectCreateExternalTargetDialog extends RepositoryBrowserDialog { }); final JCheckBox checkout = new JCheckBox("Checkout"); - checkout.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - myCheckout = checkout.isSelected(); - } - }); + checkout.addActionListener(e -> myCheckout = checkout.isSelected()); wrapper.add(checkout, gb); return wrapper; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectFilesDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectFilesDialog.java index 9aef992abfde..097bbd1dc057 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectFilesDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectFilesDialog.java @@ -19,7 +19,6 @@ import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.ui.OrderPanel; -import com.intellij.ui.OrderPanelListener; import com.intellij.ui.ScrollPaneFactory; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; @@ -79,11 +78,7 @@ public class SelectFilesDialog extends DialogWrapper implements ActionListener { mySelectAllButton.addActionListener(this); myDeselectAllButton.addActionListener(this); - myFilesList.addListener(new OrderPanelListener() { - public void entryMoved() { - getOKAction().setEnabled(isOKActionEnabled()); - } - }); + myFilesList.addListener(() -> getOKAction().setEnabled(isOKActionEnabled())); } protected String getDimensionServiceKey() { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectLocationDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectLocationDialog.java index 3cfaa958efbc..3dc9e31592fd 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectLocationDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectLocationDialog.java @@ -41,8 +41,6 @@ import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; import java.awt.*; import static com.intellij.openapi.util.Pair.create; @@ -142,16 +140,15 @@ public class SelectLocationDialog extends DialogWrapper { final Ref result = new Ref<>(); final Ref excRef = new Ref<>(); - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - try { - result.set(SvnUtil.getRepositoryRoot(SvnVcs.getInstance(project), url)); - } catch (SvnBindException e) { - excRef.set(e); - } + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + try { + result.set(SvnUtil.getRepositoryRoot(SvnVcs.getInstance(project), url)); + } + catch (SvnBindException e) { + excRef.set(e); } }, "Detecting repository root", true, project); - if (! excRef.isNull()) { + if (!excRef.isNull()) { throw excRef.get(); } return result.get(); @@ -167,11 +164,7 @@ public class SelectLocationDialog extends DialogWrapper { else { myRepositoryBrowser.setRepositoryURL(myURL, myIsShowFiles, new UrlOpeningExpander.Factory(urlString, urlString)); } - myRepositoryBrowser.addChangeListener(new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - getOKAction().setEnabled(isOKActionEnabled()); - } - }); + myRepositoryBrowser.addChangeListener(e -> getOKAction().setEnabled(isOKActionEnabled())); } @Override diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SetKeywordsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SetKeywordsDialog.java index 7c8695bda28d..f05502e58437 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SetKeywordsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SetKeywordsDialog.java @@ -17,9 +17,7 @@ package org.jetbrains.idea.svn.dialogs; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.Function; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; @@ -66,19 +64,9 @@ public class SetKeywordsDialog extends DialogWrapper { @Nullable public String getKeywords() { - List selectedKeywords = ContainerUtil.filter(myKeywordOptions, new Condition() { - @Override - public boolean value(@NotNull JCheckBox keywordOption) { - return keywordOption.isSelected(); - } - }); + List selectedKeywords = ContainerUtil.filter(myKeywordOptions, keywordOption -> keywordOption.isSelected()); - return StringUtil.nullize(StringUtil.join(selectedKeywords, new Function() { - @Override - public String fun(@NotNull JCheckBox keywordOption) { - return keywordOption.getText(); - } - }, " ")); + return StringUtil.nullize(StringUtil.join(selectedKeywords, keywordOption -> keywordOption.getText(), " ")); } @Nullable diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SetPropertyDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SetPropertyDialog.java index 63e57fbade0f..498840e7b528 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SetPropertyDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SetPropertyDialog.java @@ -38,12 +38,9 @@ import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc2.SvnTarget; import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import java.awt.*; import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; import java.io.File; import java.util.Collection; import java.util.TreeSet; @@ -126,13 +123,11 @@ public class SetPropertyDialog extends DialogWrapper { else { myPropertyNameBox.getEditor().setItem(""); } - myPropertyNameBox.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - String name = getPropertyName(); - updatePropertyValue(name); - getOKAction().setEnabled(name != null && !"".equals(name.trim())); - } + myPropertyNameBox.addItemListener(e -> { + if (e.getStateChange() == ItemEvent.SELECTED) { + String name = getPropertyName(); + updatePropertyValue(name); + getOKAction().setEnabled(name != null && !"".equals(name.trim())); } }); Component editor = myPropertyNameBox.getEditor().getEditorComponent(); @@ -188,14 +183,12 @@ public class SetPropertyDialog extends DialogWrapper { myPropertyNameBox.getEditor().setItem(myPropertyName); myPropertyNameBox.getEditor().selectAll(); } - mySetPropertyButton.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent e) { - if (mySetPropertyButton.isSelected()) { - myValueText.setEnabled(true); - } - else { - myValueText.setEnabled(false); - } + mySetPropertyButton.addChangeListener(e -> { + if (mySetPropertyButton.isSelected()) { + myValueText.setEnabled(true); + } + else { + myValueText.setEnabled(false); } }); myRecursiveButton.setEnabled(myIsRecursionAllowed); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ShareDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ShareDialog.java index 865e1eed87bc..92742d37a668 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ShareDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ShareDialog.java @@ -29,10 +29,6 @@ import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; @@ -69,13 +65,11 @@ public class ShareDialog extends RepositoryBrowserDialog { super.init(); setTitle("Select Share Target"); setOKButtonText("Share"); - getRepositoryBrowser().addChangeListener(new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - if (getOKAction() != null) { - final String selectedURL = getRepositoryBrowser().getSelectedURL(); - updateOptionsTexts(selectedURL); - getOKAction().setEnabled(selectedURL != null); - } + getRepositoryBrowser().addChangeListener(e -> { + if (getOKAction() != null) { + final String selectedURL = getRepositoryBrowser().getSelectedURL(); + updateOptionsTexts(selectedURL); + getOKAction().setEnabled(selectedURL != null); } }); getOKAction().setEnabled(getRepositoryBrowser().getSelectedURL() != null); @@ -229,12 +223,7 @@ public class ShareDialog extends RepositoryBrowserDialog { gb.insets.top = 5; panel.add(myTrunk, gb); myCreateStandard = new JCheckBox("Create /tags and /branches"); - myTrunk.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - myCreateStandard.setEnabled(myTrunk.isSelected()); - } - }); + myTrunk.addChangeListener(e -> myCreateStandard.setEnabled(myTrunk.isSelected())); myCreateStandard.setSelected(true); ++ gb.gridy; gb.insets.top = 0; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SshSettingsPanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SshSettingsPanel.java index 4cfbdb312fa5..d3b9381595cd 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SshSettingsPanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SshSettingsPanel.java @@ -35,8 +35,6 @@ import org.jetbrains.idea.svn.commandLine.SshTunnelRuntimeModule; import javax.swing.*; import javax.swing.event.DocumentEvent; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; @@ -75,12 +73,9 @@ public class SshSettingsPanel implements ConfigurableUi { register(myPrivateKeyChoice, SvnConfiguration.SshConnectionType.PRIVATE_KEY); register(mySubversionConfigChoice, SvnConfiguration.SshConnectionType.SUBVERSION_CONFIG); - ItemListener connectionTypeChangedListener = new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - enableOptions(e.getSource()); - } + ItemListener connectionTypeChangedListener = e -> { + if (e.getStateChange() == ItemEvent.SELECTED) { + enableOptions(e.getSource()); } }; myPasswordChoice.addItemListener(connectionTypeChangedListener); @@ -100,15 +95,12 @@ public class SshSettingsPanel implements ConfigurableUi { } }); - myUpdateTunnelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String tunnel = mySshTunnelField.getText(); + myUpdateTunnelButton.addActionListener(e -> { + String tunnel = mySshTunnelField.getText(); - // remove tunnel from config in case it is null or empty - mySvnConfiguration.setSshTunnelSetting(StringUtil.nullize(tunnel)); - setSshTunnelSetting(mySvnConfiguration.getSshTunnelSetting()); - } + // remove tunnel from config in case it is null or empty + mySvnConfiguration.setSshTunnelSetting(StringUtil.nullize(tunnel)); + setSshTunnelSetting(mySvnConfiguration.getSshTunnelSetting()); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/CheckoutOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/CheckoutOptionsDialog.java index 440489611cf2..07decbd9345e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/CheckoutOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/CheckoutOptionsDialog.java @@ -32,16 +32,11 @@ import org.jetbrains.idea.svn.DepthCombo; import org.jetbrains.idea.svn.SvnBundle; import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.revision.SvnSelectRevisionPanel; -import org.jetbrains.idea.svn.update.SvnRevisionPanel; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.wc.SVNRevision; import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.Collections; @@ -68,35 +63,25 @@ public class CheckoutOptionsDialog extends DialogWrapper { fillTargetList(target); validateTargetSelected(); - mySelectTarget.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - // choose directory here/ - FileChooserDescriptor fcd = FileChooserDescriptorFactory.createSingleFolderDescriptor(); - fcd.setShowFileSystemRoots(true); - fcd.setTitle(SvnBundle.message("checkout.directory.chooser.title")); - fcd.setDescription(SvnBundle.message("checkout.directory.chooser.prompt")); - fcd.setHideIgnored(false); - VirtualFile file = FileChooser.chooseFile(fcd, getContentPane(), project, null); - if (file == null) { - return; - } - fillTargetList(new File(file.getPath())); - validateTargetSelected(); - } - }); - myLocalTargetList.addListSelectionListener(new ListSelectionListener() { - public void valueChanged(final ListSelectionEvent e) { - validateTargetSelected(); + mySelectTarget.addActionListener(e -> { + // choose directory here/ + FileChooserDescriptor fcd = FileChooserDescriptorFactory.createSingleFolderDescriptor(); + fcd.setShowFileSystemRoots(true); + fcd.setTitle(SvnBundle.message("checkout.directory.chooser.title")); + fcd.setDescription(SvnBundle.message("checkout.directory.chooser.prompt")); + fcd.setHideIgnored(false); + VirtualFile file = FileChooser.chooseFile(fcd, getContentPane(), project, null); + if (file == null) { + return; } + fillTargetList(new File(file.getPath())); + validateTargetSelected(); }); + myLocalTargetList.addListSelectionListener(e -> validateTargetSelected()); svnSelectRevisionPanel.setRoot(root); svnSelectRevisionPanel.setProject(project); - svnSelectRevisionPanel.setUrlProvider(new SvnRevisionPanel.UrlProvider() { - public String getUrl() { - return urlText; - } - }); + svnSelectRevisionPanel.setUrlProvider(() -> urlText); setTitle(SvnBundle.message("checkout.options.dialog.title")); myDepthLabel.setLabelFor(myDepthCombo); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/CopyOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/CopyOptionsDialog.java index 9c8d0b91dcbd..c5016dcd2fdf 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/CopyOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/CopyOptionsDialog.java @@ -43,12 +43,8 @@ import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import javax.swing.*; import javax.swing.event.DocumentEvent; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreeNode; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; @@ -87,11 +83,7 @@ public class CopyOptionsDialog extends DialogWrapper { myBrowser.setRepositoryURL(root.getURL(), false, new OpeningExpander.Factory(subPath, (RepositoryTreeNode)((node.getParent() instanceof RepositoryTreeNode) ? node.getParent() : null))); - myBrowser.addChangeListener(new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - update(); - } - }); + myBrowser.addChangeListener(e -> update()); myNameField.setText(SVNPathUtil.tail(myURL.getPath())); myNameField.selectAll(); @@ -112,13 +104,11 @@ public class CopyOptionsDialog extends DialogWrapper { myCommitMessage.setText(lastMessage); myCommitMessage.selectAll(); } - myMessagesBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - final Object item = myMessagesBox.getSelectedItem(); - if (item != null) { - myCommitMessage.setText(item.toString()); - myCommitMessage.selectAll(); - } + myMessagesBox.addActionListener(e -> { + final Object item = myMessagesBox.getSelectedItem(); + if (item != null) { + myCommitMessage.setText(item.toString()); + myCommitMessage.selectAll(); } }); Disposer.register(getDisposable(), myBrowser); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java index bad990f698a9..5c7e2ca37570 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java @@ -26,8 +26,6 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; @@ -105,12 +103,9 @@ public class DeleteOptionsDialog extends DialogWrapper { myCommitMessage.setText(lastMessage); myCommitMessage.selectAll(); } - messagesBox.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - myCommitMessage.setText(messagesBox.getSelectedItem().toString()); - myCommitMessage.selectAll(); - } + messagesBox.addActionListener(e -> { + myCommitMessage.setText(messagesBox.getSelectedItem().toString()); + myCommitMessage.selectAll(); }); return panel; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DiffOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DiffOptionsDialog.java index 1df5567910e9..f11bc462316b 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DiffOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DiffOptionsDialog.java @@ -41,8 +41,6 @@ import org.tmatesoft.svn.core.SVNURL; import javax.swing.*; import javax.swing.event.DocumentEvent; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; @@ -71,23 +69,17 @@ public class DiffOptionsDialog extends DialogWrapper implements ActionListener { setTitle(SvnBundle.message("diff.options.title")); mySourceUrlLabel.setText(myURL.toString()); myBrowser.setRepositoryURL(myRootURL, false); - myBrowser.addChangeListener(new TreeSelectionListener() { - public void valueChanged(TreeSelectionEvent e) { - update(); - } - }); + myBrowser.addChangeListener(e -> update()); myUIDiffButton.addActionListener(this); myUnifiedDiffButton.addActionListener(this); init(); - myFileBrowser.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - File f = selectFile("Patch File", "Select file to store unified diff"); - if (f != null) { - if (f.exists() && f.isDirectory()) { - f = new File(f, DEFAULT_PATCH_NAME); - } - myFileBrowser.setText(f.getAbsolutePath()); + myFileBrowser.addActionListener(e -> { + File f = selectFile("Patch File", "Select file to store unified diff"); + if (f != null) { + if (f.exists() && f.isDirectory()) { + f = new File(f, DEFAULT_PATCH_NAME); } + myFileBrowser.setText(f.getAbsolutePath()); } }); myFileBrowser.getTextField().getDocument().addDocumentListener(new DocumentAdapter() { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java index 7a85cd1d3ea2..c7a3accc7b02 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java @@ -179,12 +179,9 @@ public class ImportOptionsDialog extends DialogWrapper implements ActionListener myCommitMessage.setText(lastMessage); myCommitMessage.selectAll(); } - messagesBox.addActionListener(new ActionListener() { - - public void actionPerformed(ActionEvent e) { - myCommitMessage.setText(messagesBox.getSelectedItem().toString()); - myCommitMessage.selectAll(); - } + messagesBox.addActionListener(e -> { + myCommitMessage.setText(messagesBox.getSelectedItem().toString()); + myCommitMessage.selectAll(); }); return panel; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java index 0333d4f555e3..ba63a402c32e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/MkdirOptionsDialog.java @@ -27,8 +27,6 @@ import org.tmatesoft.svn.core.SVNURL; import javax.swing.*; import javax.swing.event.DocumentEvent; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; @@ -79,11 +77,9 @@ public class MkdirOptionsDialog extends DialogWrapper { myCommitMessage.setText(lastMessage); myCommitMessage.selectAll(); } - myMessagesBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - myCommitMessage.setText(myMessagesBox.getSelectedItem().toString()); - myCommitMessage.selectAll(); - } + myMessagesBox.addActionListener(e -> { + myCommitMessage.setText(myMessagesBox.getSelectedItem().toString()); + myCommitMessage.selectAll(); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browserCache/CacheLoader.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browserCache/CacheLoader.java index f8553d5c66c3..18465f6118e9 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browserCache/CacheLoader.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browserCache/CacheLoader.java @@ -37,21 +37,19 @@ public class CacheLoader extends Loader { } public void load(@NotNull final RepositoryTreeNode node, @NotNull final Expander expander) { - SwingUtilities.invokeLater(new Runnable(){ - public void run() { - final String nodeUrl = node.getURL().toString(); + SwingUtilities.invokeLater(() -> { + final String nodeUrl = node.getURL().toString(); - final List cached = myCache.getChildren(nodeUrl); - if (cached != null) { - refreshNode(node, cached, expander); - } - final String error = myCache.getError(nodeUrl); - if (error != null) { - refreshNodeError(node, error); - } - // refresh anyway - myRepositoryLoader.load(node, expander); + final List cached = myCache.getChildren(nodeUrl); + if (cached != null) { + refreshNode(node, cached, expander); } + final String error = myCache.getError(nodeUrl); + if (error != null) { + refreshNodeError(node, error); + } + // refresh anyway + myRepositoryLoader.load(node, expander); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browserCache/RepositoryLoader.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browserCache/RepositoryLoader.java index 5c7e4144286e..ccf824bc9291 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browserCache/RepositoryLoader.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browserCache/RepositoryLoader.java @@ -29,7 +29,6 @@ import org.jetbrains.idea.svn.auth.SvnAuthenticationProvider; import org.jetbrains.idea.svn.browse.DirectoryEntry; import org.jetbrains.idea.svn.browse.DirectoryEntryConsumer; import org.jetbrains.idea.svn.dialogs.RepositoryTreeNode; -import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc2.SvnTarget; @@ -91,12 +90,8 @@ class RepositoryLoader extends Loader { private void startLoadTask(@NotNull final Pair data) { final ModalityState state = ModalityState.current(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - ProgressManager.getInstance().runProcess(new LoadTask(data), new EmptyProgressIndicator(state)); - } - }); + ApplicationManager.getApplication() + .executeOnPooledThread(() -> ProgressManager.getInstance().runProcess(new LoadTask(data), new EmptyProgressIndicator(state))); } @NotNull @@ -118,34 +113,24 @@ class RepositoryLoader extends Loader { final SvnVcs vcs = node.getVcs(); SvnAuthenticationProvider.forceInteractive(); - DirectoryEntryConsumer handler = new DirectoryEntryConsumer() { - - @Override - public void consume(final DirectoryEntry entry) throws SVNException { - entries.add(entry); - } - }; + DirectoryEntryConsumer handler = entry -> entries.add(entry); try { SvnTarget target = SvnTarget.fromURL(node.getURL()); vcs.getFactoryFromSettings().createBrowseClient().list(target, SVNRevision.HEAD, Depth.IMMEDIATES, handler); } catch (final VcsException e) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - setError(myData, e.getMessage()); - startNext(); - } + SwingUtilities.invokeLater(() -> { + setError(myData, e.getMessage()); + startNext(); }); return; } finally { SvnAuthenticationProvider.clearInteractive(); } - SwingUtilities.invokeLater(new Runnable() { - public void run() { - setResults(myData, ContainerUtil.newArrayList(entries)); - startNext(); - } + SwingUtilities.invokeLater(() -> { + setResults(myData, ContainerUtil.newArrayList(entries)); + startNext(); }); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/ElementWithBranchComparer.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/ElementWithBranchComparer.java index 5d29b323e75b..73eeaa007d89 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/ElementWithBranchComparer.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/ElementWithBranchComparer.java @@ -141,23 +141,16 @@ public abstract class ElementWithBranchComparer { } protected void reportGeneralException(final Exception e) { - WaitForProgressToShow.runOrInvokeLaterAboveProgress(new Runnable() { - public void run() { - Messages.showMessageDialog(myProject, e.getMessage(), - SvnBundle.message("compare.with.branch.error.title"), Messages.getErrorIcon()); - } - }, null, myProject); + WaitForProgressToShow.runOrInvokeLaterAboveProgress( + () -> Messages + .showMessageDialog(myProject, e.getMessage(), SvnBundle.message("compare.with.branch.error.title"), Messages.getErrorIcon()), null, + myProject); LOG.info(e); } private void reportNotFound() { - WaitForProgressToShow.runOrInvokeLaterAboveProgress(new Runnable() { - public void run() { - Messages.showMessageDialog(myProject, - SvnBundle - .message("compare.with.branch.location.error", myVirtualFile.getPresentableUrl(), myBranchUrl), - SvnBundle.message("compare.with.branch.error.title"), Messages.getErrorIcon()); - } - }, null, myProject); + WaitForProgressToShow.runOrInvokeLaterAboveProgress(() -> Messages + .showMessageDialog(myProject, SvnBundle.message("compare.with.branch.location.error", myVirtualFile.getPresentableUrl(), myBranchUrl), + SvnBundle.message("compare.with.branch.error.title"), Messages.getErrorIcon()), null, myProject); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/SvnKitDiffClient.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/SvnKitDiffClient.java index ec4c51288cc2..f48b668e061a 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/SvnKitDiffClient.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/diff/SvnKitDiffClient.java @@ -34,8 +34,6 @@ import org.tmatesoft.svn.core.internal.wc.admin.SVNWCAccess; import org.tmatesoft.svn.core.internal.wc17.SVNReporter17; import org.tmatesoft.svn.core.internal.wc17.SVNWCContext; import org.tmatesoft.svn.core.io.ISVNEditor; -import org.tmatesoft.svn.core.io.ISVNReporter; -import org.tmatesoft.svn.core.io.ISVNReporterBaton; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.SVNEvent; @@ -125,11 +123,9 @@ public class SvnKitDiffClient extends BaseSvnClient implements DiffClient { targetRepository = myVcs.getSvnKitManager().createRepository(myTarget2.getURL()); diffEditor = new SvnDiffEditor(sourceRepository, targetRepository, -1, false); final ISVNEditor cancellableEditor = SVNCancellableEditor.newInstance(diffEditor, new SvnKitProgressCanceller(), null); - sourceRepository.diff(myTarget2.getURL(), rev, rev, null, true, true, false, new ISVNReporterBaton() { - public void report(ISVNReporter reporter) throws SVNException { - reporter.setPath("", null, rev, false); - reporter.finishReport(); - } + sourceRepository.diff(myTarget2.getURL(), rev, rev, null, true, true, false, reporter -> { + reporter.setPath("", null, rev, false); + reporter.finishReport(); }, cancellableEditor); return diffEditor.getChangesMap().values(); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/difftool/SvnDiffViewer.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/difftool/SvnDiffViewer.java index 4bc734aa89fe..f81823f067d7 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/difftool/SvnDiffViewer.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/difftool/SvnDiffViewer.java @@ -30,7 +30,6 @@ import com.intellij.ui.components.panels.Wrapper; import com.intellij.util.containers.HashMap; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; -import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.difftool.SvnDiffSettingsHolder.SvnDiffSettings; @@ -97,15 +96,12 @@ public class SvnDiffViewer implements DiffViewer { myPanel = new JPanel(new BorderLayout()); myPanel.add(mySplitter, BorderLayout.CENTER); myPanel.add(myNotificationPanel, BorderLayout.SOUTH); - DataManager.registerDataProvider(myPanel, new DataProvider() { - @Override - public Object getData(@NonNls String dataId) { - DataProvider propertiesDataProvider = DataManagerImpl.getDataProviderEx(myPropertiesViewer.getComponent()); - DataProvider contentDataProvider = DataManagerImpl.getDataProviderEx(myContentViewer.getComponent()); - DataProvider defaultDP = myPropertiesViewerFocused ? propertiesDataProvider : contentDataProvider; - DataProvider fallbackDP = myPropertiesViewerFocused ? contentDataProvider : propertiesDataProvider; - return DiffUtil.getData(defaultDP, fallbackDP, dataId); - } + DataManager.registerDataProvider(myPanel, dataId -> { + DataProvider propertiesDataProvider = DataManagerImpl.getDataProviderEx(myPropertiesViewer.getComponent()); + DataProvider contentDataProvider = DataManagerImpl.getDataProviderEx(myContentViewer.getComponent()); + DataProvider defaultDP = myPropertiesViewerFocused ? propertiesDataProvider : contentDataProvider; + DataProvider fallbackDP = myPropertiesViewerFocused ? contentDataProvider : propertiesDataProvider; + return DiffUtil.getData(defaultDP, fallbackDP, dataId); }); updatePropertiesPanel(); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/difftool/properties/SvnPropertiesDiffViewer.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/difftool/properties/SvnPropertiesDiffViewer.java index eee0b6b2278a..164d92a9053e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/difftool/properties/SvnPropertiesDiffViewer.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/difftool/properties/SvnPropertiesDiffViewer.java @@ -44,8 +44,10 @@ import org.jetbrains.idea.svn.properties.PropertyValue; import javax.swing.*; import java.awt.*; import java.awt.geom.AffineTransform; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Map; public class SvnPropertiesDiffViewer extends TwosideTextDiffViewer { @NotNull private final WrapperRequest myWrapperRequest; @@ -135,13 +137,10 @@ public class SvnPropertiesDiffViewer extends TwosideTextDiffViewer { } } - return new Runnable() { - @Override - public void run() { - for (DiffChange change : myDiffChanges) { - setupHighlighting(change, Side.LEFT); - setupHighlighting(change, Side.RIGHT); - } + return () -> { + for (DiffChange change : myDiffChanges) { + setupHighlighting(change, Side.LEFT); + setupHighlighting(change, Side.RIGHT); } }; } @@ -384,12 +383,7 @@ public class SvnPropertiesDiffViewer extends TwosideTextDiffViewer { records.add(createRecord(name, before.get(name), after.get(name))); } - ContainerUtil.sort(records, new Comparator() { - @Override - public int compare(PropertyRecord o1, PropertyRecord o2) { - return StringUtil.naturalCompare(o1.getName(), o2.getName()); - } - }); + ContainerUtil.sort(records, (o1, o2) -> StringUtil.naturalCompare(o1.getName(), o2.getName())); return records; } @@ -446,13 +440,13 @@ public class SvnPropertiesDiffViewer extends TwosideTextDiffViewer { @NotNull @Override public List getContents() { - return ContainerUtil.list(myContent1, myContent2); + return ContainerUtil.list(myContent1, myContent2); } @NotNull @Override public List getContentTitles() { - return myEmbedded ? ContainerUtil.list(null, null) : myRequest.getContentTitles(); + return myEmbedded ? ContainerUtil.list(null, null) : myRequest.getContentTitles(); } @Nullable diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LatestExistentSearcher.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LatestExistentSearcher.java index 09b617d9c896..3719a89809cc 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LatestExistentSearcher.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LatestExistentSearcher.java @@ -27,7 +27,10 @@ import org.jetbrains.idea.svn.SvnUtil; import org.jetbrains.idea.svn.SvnVcs; import org.jetbrains.idea.svn.commandLine.SvnBindException; import org.jetbrains.idea.svn.info.Info; -import org.tmatesoft.svn.core.*; +import org.tmatesoft.svn.core.SVNErrorCode; +import org.tmatesoft.svn.core.SVNErrorMessage; +import org.tmatesoft.svn.core.SVNException; +import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNURLUtil; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc2.SvnTarget; @@ -94,16 +97,13 @@ public class LatestExistentSearcher { @NotNull private LogEntryConsumer createHandler(@NotNull final Ref latest) { - return new LogEntryConsumer() { - @Override - public void consume(final LogEntry logEntry) throws SVNException { - final Map changedPaths = logEntry.getChangedPaths(); - for (Object o : changedPaths.values()) { - final LogEntryPath path = (LogEntryPath)o; - if ((path.getType() == 'D') && (myRelativeUrl.equals(path.getPath()))) { - latest.set(logEntry.getRevision()); - throw new SVNException(SVNErrorMessage.UNKNOWN_ERROR_MESSAGE); - } + return logEntry -> { + final Map changedPaths = logEntry.getChangedPaths(); + for (Object o : changedPaths.values()) { + final LogEntryPath path = (LogEntryPath)o; + if ((path.getType() == 'D') && (myRelativeUrl.equals(path.getPath()))) { + latest.set(logEntry.getRevision()); + throw new SVNException(SVNErrorMessage.UNKNOWN_ERROR_MESSAGE); } } }; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LiveProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LiveProvider.java index 7814b4f4f5c0..b25cd88161b5 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LiveProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LiveProvider.java @@ -79,15 +79,13 @@ public class LiveProvider implements BunchProvider { final Ref> refToList = new Ref<>(); final Ref exceptionRef = new Ref<>(); - final Runnable loader = new Runnable() { - public void run() { - try { - refToList.set( - myLoader.loadInterval(youngRevision, SVNRevision.create(oldestRevision), desirableSize, includeYoungest, includeOldest)); - } - catch (VcsException e) { - exceptionRef.set(e); - } + final Runnable loader = () -> { + try { + refToList + .set(myLoader.loadInterval(youngRevision, SVNRevision.create(oldestRevision), desirableSize, includeYoungest, includeOldest)); + } + catch (VcsException e) { + exceptionRef.set(e); } }; @@ -95,14 +93,12 @@ public class LiveProvider implements BunchProvider { if (application.isUnitTestMode() || ! application.isDispatchThread()) { loader.run(); } else { - ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { - public void run() { - final ProgressIndicator ind = ProgressManager.getInstance().getProgressIndicator(); - if (ind != null) { - ind.setText(SvnBundle.message("progress.live.provider.loading.revisions.details.text")); - } - loader.run(); + ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> { + final ProgressIndicator ind = ProgressManager.getInstance().getProgressIndicator(); + if (ind != null) { + ind.setText(SvnBundle.message("progress.live.provider.loading.revisions.details.text")); } + loader.run(); }, SvnBundle.message("progress.live.provider.loading.revisions.text"), false, myVcs.getProject()); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LoadedRevisionsCache.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LoadedRevisionsCache.java index 71f8c3e09290..934c41b23256 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LoadedRevisionsCache.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/LoadedRevisionsCache.java @@ -54,11 +54,9 @@ public class LoadedRevisionsCache implements Disposable { @Override public void changesLoaded(final RepositoryLocation location, final List changes) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - myMap.clear(); - setRefreshTime(System.currentTimeMillis()); - } + ApplicationManager.getApplication().invokeLater(() -> { + myMap.clear(); + setRefreshTime(System.currentTimeMillis()); }); } }); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/MergeInfoUpdatesListener.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/MergeInfoUpdatesListener.java index 36fc1206b7bd..496ec1b21a7b 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/MergeInfoUpdatesListener.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/MergeInfoUpdatesListener.java @@ -18,11 +18,8 @@ package org.jetbrains.idea.svn.history; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ZipperUpdater; -import com.intellij.openapi.vcs.VcsListener; import com.intellij.openapi.vcs.changes.committed.CommittedChangesTreeBrowser; import com.intellij.openapi.vcs.changes.committed.VcsConfigurationChangeListener; -import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; -import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; @@ -54,35 +51,19 @@ public class MergeInfoUpdatesListener { myMergeInfoRefreshActions = new ArrayList<>(); myMergeInfoRefreshActions.add(action); - myConnection.subscribe(VcsConfigurationChangeListener.BRANCHES_CHANGED, new VcsConfigurationChangeListener.Notification() { - public void execute(final Project project, final VirtualFile vcsRoot) { - callReloadMergeInfo(); - } - }); - final Consumer reloadConsumer = new Consumer() { - @Override - public void consume(Boolean aBoolean) { - if (Boolean.TRUE.equals(aBoolean)) { - callReloadMergeInfo(); - } - } - }; - final Runnable reloadRunnable = new Runnable() { - @Override - public void run() { + myConnection.subscribe(VcsConfigurationChangeListener.BRANCHES_CHANGED, (project, vcsRoot) -> callReloadMergeInfo()); + final Consumer reloadConsumer = aBoolean -> { + if (Boolean.TRUE.equals(aBoolean)) { callReloadMergeInfo(); } }; + final Runnable reloadRunnable = () -> callReloadMergeInfo(); myConnection.subscribe(SvnVcs.WC_CONVERTED, reloadRunnable); myConnection.subscribe(RootsAndBranches.REFRESH_REQUEST, reloadRunnable); myConnection.subscribe(SvnVcs.ROOTS_RELOADED, reloadConsumer); - myConnection.subscribe(VCS_CONFIGURATION_CHANGED, new VcsListener() { - public void directoryMappingChanged() { - callReloadMergeInfo(); - } - }); + myConnection.subscribe(VCS_CONFIGURATION_CHANGED, () -> callReloadMergeInfo()); myConnection.subscribe(CommittedChangesTreeBrowser.ITEMS_RELOADED, new CommittedChangesTreeBrowser.CommittedChangesReloadListener() { public void itemsReloaded() { @@ -92,44 +73,25 @@ public class MergeInfoUpdatesListener { } }); - myConnection.subscribe(SvnMergeInfoCache.SVN_MERGE_INFO_CACHE, new SvnMergeInfoCache.SvnMergeInfoCacheListener() { - public void copyRevisionUpdated() { - doForEachInitialized(new Consumer() { - public void consume(final RootsAndBranches rootsAndBranches) { - rootsAndBranches.fireRepaint(); - } - }); - } - }); + myConnection + .subscribe(SvnMergeInfoCache.SVN_MERGE_INFO_CACHE, () -> doForEachInitialized(rootsAndBranches -> rootsAndBranches.fireRepaint())); - myConnection.subscribe(Merger.COMMITTED_CHANGES_MERGED_STATE, new Merger.CommittedChangesMergedStateChanged() { - public void event(final List list) { - doForEachInitialized(new Consumer() { - public void consume(RootsAndBranches rootsAndBranches) { - rootsAndBranches.refreshByLists(list); - } - }); - } - }); + myConnection.subscribe(Merger.COMMITTED_CHANGES_MERGED_STATE, + list -> doForEachInitialized(rootsAndBranches -> rootsAndBranches.refreshByLists(list))); } else { myMergeInfoRefreshActions.add(action); } } private void doForEachInitialized(final Consumer consumer) { - myUpdater.queue(new Runnable() { - public void run() { - for (final RootsAndBranches action : myMergeInfoRefreshActions) { - if (action.strategyInitialized()) { - if (ApplicationManager.getApplication().isDispatchThread()) { - consumer.consume(action); - } else { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - consumer.consume(action); - } - }); - } + myUpdater.queue(() -> { + for (final RootsAndBranches action : myMergeInfoRefreshActions) { + if (action.strategyInitialized()) { + if (ApplicationManager.getApplication().isDispatchThread()) { + consumer.consume(action); + } + else { + ApplicationManager.getApplication().invokeLater(() -> consumer.consume(action)); } } } @@ -137,11 +99,9 @@ public class MergeInfoUpdatesListener { } private void callReloadMergeInfo() { - doForEachInitialized(new Consumer() { - public void consume(final RootsAndBranches rootsAndBranches) { - rootsAndBranches.reloadPanels(); - rootsAndBranches.refresh(); - } + doForEachInitialized(rootsAndBranches -> { + rootsAndBranches.reloadPanels(); + rootsAndBranches.refresh(); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/RootsAndBranches.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/RootsAndBranches.java index 63384c821ee4..f10a11599e83 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/RootsAndBranches.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/RootsAndBranches.java @@ -28,7 +28,6 @@ import com.intellij.openapi.vcs.RepositoryLocation; import com.intellij.openapi.vcs.changes.committed.*; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; import com.intellij.ui.ScrollPaneFactory; -import com.intellij.util.NotNullFunction; import com.intellij.util.messages.Topic; import com.intellij.util.ui.JBUI; import icons.SvnIcons; @@ -121,7 +120,7 @@ public class RootsAndBranches implements CommittedChangeListDecorator { new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTH, GridBagConstraints.NONE, JBUI.insets(1), 0, 0); gb.insets = JBUI.insets(20, 1, 1, 1); myPanel.add(new JLabel("Loading..."), gb); - + myPanel.setPreferredSize(JBUI.size(200, 60)); myManager.install(this); @@ -148,16 +147,14 @@ public class RootsAndBranches implements CommittedChangeListDecorator { final WCInfoWithBranches wcInfo = entry.getValue().getWcInfo(); states.put(Couple.of(localPath, wcInfo.getUrl().toString()), entry.getValue().getInfo()); } - createPanels(myLocation, new Runnable() { - public void run() { - for (Map.Entry entry : myMergePanels.entrySet()) { - final String localPath = entry.getKey(); - final WCInfoWithBranches wcInfo = entry.getValue().getWcInfo(); - final Couple key = Couple.of(localPath, wcInfo.getUrl().toString()); - final SvnMergeInfoRootPanelManual.InfoHolder infoHolder = states.get(key); - if (infoHolder != null) { - entry.getValue().initSelection(infoHolder); - } + createPanels(myLocation, () -> { + for (Map.Entry entry : myMergePanels.entrySet()) { + final String localPath = entry.getKey(); + final WCInfoWithBranches wcInfo = entry.getValue().getWcInfo(); + final Couple key = Couple.of(localPath, wcInfo.getUrl().toString()); + final SvnMergeInfoRootPanelManual.InfoHolder infoHolder = states.get(key); + if (infoHolder != null) { + entry.getValue().initSelection(infoHolder); } } }); @@ -185,7 +182,7 @@ public class RootsAndBranches implements CommittedChangeListDecorator { final ListMergeStatus status = getStatus(list, false); return (status == null) ? ListMergeStatus.ALIEN.getIcon() : status.getIcon(); } - + private void createPanels(final RepositoryLocation location, final Runnable afterRefresh) { final Task.Backgroundable backgroundable = new Task.Backgroundable(myProject, "Subversion: loading working copies data..", false) { public void run(@NotNull final ProgressIndicator indicator) { @@ -193,40 +190,43 @@ public class RootsAndBranches implements CommittedChangeListDecorator { final Map panels = new HashMap<>(); final Map holders = new HashMap<>(); final List roots = myDataLoader.loadRoots(); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (myDisposed) return; - final JPanel mainPanel = prepareData(panels, holders, roots); + SwingUtilities.invokeLater(() -> { + if (myDisposed) return; + final JPanel mainPanel = prepareData(panels, holders, roots); - myMergePanels.clear(); - myHolders.clear(); - myMergePanels.putAll(panels); - myHolders.putAll(holders); - - if (myPanelWrapper != null) { - myPanelWrapper.removeAll(); - if (myMergePanels.isEmpty()) { - final JPanel emptyPanel = new JPanel(new GridBagLayout()); - final GridBagConstraints gb = - new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0); - final JLabel label = new JLabel("No Subversion 1.5 working copies\nof 1.5 repositories in the project"); - label.setUI(new MultiLineLabelUI()); - emptyPanel.add(label, gb); - gb.fill = GridBagConstraints.HORIZONTAL; - myPanelWrapper.add(emptyPanel, gb); - } else { - for (MergeInfoHolder holder : myHolders.values()) { - holder.updateMixedRevisionsForPanel(); - } - myPanelWrapper.add(mainPanel, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); + myMergePanels.clear(); + myHolders.clear(); + myMergePanels.putAll(panels); + myHolders.putAll(holders); + + if (myPanelWrapper != null) { + myPanelWrapper.removeAll(); + if (myMergePanels.isEmpty()) { + final JPanel emptyPanel = new JPanel(new GridBagLayout()); + final GridBagConstraints gb = + new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, + 0); + final JLabel label = new JLabel("No Subversion 1.5 working copies\nof 1.5 repositories in the project"); + label.setUI(new MultiLineLabelUI()); + emptyPanel.add(label, gb); + gb.fill = GridBagConstraints.HORIZONTAL; + myPanelWrapper.add(emptyPanel, gb); + } + else { + for (MergeInfoHolder holder : myHolders.values()) { + holder.updateMixedRevisionsForPanel(); } - myPanelWrapper.repaint(); - } else { - myPanel = mainPanel; - } - if (afterRefresh != null) { - afterRefresh.run(); + myPanelWrapper.add(mainPanel, + new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, + new Insets(0, 0, 0, 0), 0, 0)); } + myPanelWrapper.repaint(); + } + else { + myPanel = mainPanel; + } + if (afterRefresh != null) { + afterRefresh.run(); } }); } @@ -235,8 +235,8 @@ public class RootsAndBranches implements CommittedChangeListDecorator { } public void refreshByLists(final List committedChangeLists) { - if (! committedChangeLists.isEmpty()) { - final SvnChangeList svnList = (SvnChangeList) committedChangeLists.get(0); + if (!committedChangeLists.isEmpty()) { + final SvnChangeList svnList = (SvnChangeList)committedChangeLists.get(0); final String wcPath = svnList.getWcPath(); if (wcPath != null) { final MergeInfoHolder holder = getHolder(wcPath); @@ -255,52 +255,47 @@ public class RootsAndBranches implements CommittedChangeListDecorator { private JPanel prepareData(final Map panels, final Map holders, List roots) { - final JPanel mainPanel = new JPanel(new GridBagLayout()); - boolean onlyOneRoot = roots.size() == 1; - final GridBagConstraints gb = new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, - new Insets(0,0,0,0), 0, 0); - mainPanel.add(myToolbarComponent, gb); - ++ gb.gridy; + final JPanel mainPanel = new JPanel(new GridBagLayout()); + boolean onlyOneRoot = roots.size() == 1; + final GridBagConstraints gb = new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(0, 0, 0, 0), 0, 0); + mainPanel.add(myToolbarComponent, gb); + ++gb.gridy; - for (final WCInfoWithBranches root : roots) { - if (root == null) { - continue; + for (final WCInfoWithBranches root : roots) { + if (root == null) { + continue; + } + final SvnMergeInfoRootPanelManual panel = new SvnMergeInfoRootPanelManual(myProject, wcInfoWithBranches -> { + final WCInfoWithBranches newInfo = + myDataLoader.reloadInfo(wcInfoWithBranches); + if (newInfo == null) { + // reload all items + myProject.getMessageBus() + .syncPublisher(SvnVcs.WC_CONVERTED).run(); + // do not reload right now + return wcInfoWithBranches; } - final SvnMergeInfoRootPanelManual panel = new SvnMergeInfoRootPanelManual(myProject, - new NotNullFunction() { - @NotNull - public WCInfoWithBranches fun(@NotNull WCInfoWithBranches wcInfoWithBranches) { - final WCInfoWithBranches newInfo = - myDataLoader.reloadInfo(wcInfoWithBranches); - if (newInfo == null) { - // reload all items - myProject.getMessageBus().syncPublisher(SvnVcs.WC_CONVERTED).run(); - // do not reload right now - return wcInfoWithBranches; - } - return newInfo; - } - }, new Runnable() { - public void run() { - final MergeInfoHolder holder = getHolder(root.getPath()); - if (holder != null) { - holder.refresh(false); - } - } - }, onlyOneRoot, root); - panels.put(root.getPath(), panel); - holders.put(root.getPath(), createHolder(panel)); + return newInfo; + }, () -> { + final MergeInfoHolder holder = getHolder(root.getPath()); + if (holder != null) { + holder.refresh(false); + } + }, onlyOneRoot, root); + panels.put(root.getPath(), panel); + holders.put(root.getPath(), createHolder(panel)); - final JPanel contentPanel = panel.getContentPanel(); - mainPanel.add(contentPanel, gb); - ++ gb.gridy; + final JPanel contentPanel = panel.getContentPanel(); + mainPanel.add(contentPanel, gb); + ++gb.gridy; + } + if (panels.size() == 1) { + for (SvnMergeInfoRootPanelManual panel : panels.values()) { + panel.setOnlyOneRoot(true); } - if (panels.size() == 1) { - for (SvnMergeInfoRootPanelManual panel : panels.values()) { - panel.setOnlyOneRoot(true); - } - } - return mainPanel; + } + return mainPanel; } private DefaultActionGroup createActions() { @@ -355,14 +350,14 @@ public class RootsAndBranches implements CommittedChangeListDecorator { } } - if (! refreshers.isEmpty()) { + if (!refreshers.isEmpty()) { myManager.reportLoadedLists(new CommittedChangeListsListener() { public void onBeforeStartReport() { } public boolean report(final CommittedChangeList list) { if (list instanceof SvnChangeList) { - final SvnChangeList svnList = (SvnChangeList) list; + final SvnChangeList svnList = (SvnChangeList)list; final String wcPath = svnList.getWcPath(); if (wcPath != null) { final CommittedChangeListsListener refresher = refreshers.get(ensureEndsWithSeparator(wcPath)); @@ -428,7 +423,8 @@ public class RootsAndBranches implements CommittedChangeListDecorator { public void setSelected(final AnActionEvent e, final boolean state) { if (state) { turnFromHereHighlighting(); - } else { + } + else { turnOff(); } } @@ -485,7 +481,7 @@ public class RootsAndBranches implements CommittedChangeListDecorator { return false; } for (CommittedChangeList list : listsList) { - if (! mergeEnabled(list, forMerge)) { + if (!mergeEnabled(list, forMerge)) { return false; } } @@ -496,7 +492,8 @@ public class RootsAndBranches implements CommittedChangeListDecorator { final ListMergeStatus mergeStatus = getStatus(list, true); if ((mergeStatus == null) || (ListMergeStatus.ALIEN.equals(mergeStatus))) { return false; - } else if (ListMergeStatus.REFRESHING.equals(mergeStatus)) { + } + else if (ListMergeStatus.REFRESHING.equals(mergeStatus)) { return true; } if (forMerge) { @@ -535,7 +532,7 @@ public class RootsAndBranches implements CommittedChangeListDecorator { presentation.setDescription(myDescription); presentation.setEnabled(presentation.isEnabled() && mergeEnabled(checker.getSelectedLists(), myMarkAsMerged)); } - + @Nullable protected String getSelectedBranchUrl(SelectedCommittedStuffChecker checker) { final SvnMergeInfoRootPanelManual data = getPanelData(checker.getSelectedLists()); @@ -617,10 +614,10 @@ public class RootsAndBranches implements CommittedChangeListDecorator { private SvnMergeInfoRootPanelManual getPanelData(final List listsList) { for (CommittedChangeList list : listsList) { - if (! (list instanceof SvnChangeList)) { + if (!(list instanceof SvnChangeList)) { return null; } - final SvnChangeList svnList = (SvnChangeList) list; + final SvnChangeList svnList = (SvnChangeList)list; final String wcPath = svnList.getWcPath(); if (wcPath == null) { continue; @@ -632,11 +629,11 @@ public class RootsAndBranches implements CommittedChangeListDecorator { @Nullable public ListMergeStatus getStatus(final CommittedChangeList list, final boolean ignoreEnabled) { - if (! (list instanceof SvnChangeList)) { + if (!(list instanceof SvnChangeList)) { return null; } - final SvnChangeList svnList = (SvnChangeList) list; + final SvnChangeList svnList = (SvnChangeList)list; final String wcPath = svnList.getWcPath(); MergeInfoHolder holder = null; if (wcPath == null) { @@ -647,7 +644,8 @@ public class RootsAndBranches implements CommittedChangeListDecorator { holder = getHolder(entry.getKey()); } } - } else { + } + else { holder = getHolder(wcPath); } if (holder != null) { @@ -679,7 +677,7 @@ public class RootsAndBranches implements CommittedChangeListDecorator { } public JComponent getFilterUI() { - if (! myInitialized) { + if (!myInitialized) { createPanels(myLocation, null); } myInitialized = true; @@ -710,7 +708,7 @@ public class RootsAndBranches implements CommittedChangeListDecorator { @NotNull public List filterChangeLists(final List changeLists) { - if ((! myFilterAlien.isSelected(null)) && (! myFilterNotMerged.isSelected(null)) && (! myFilterMerged.isSelected(null))) { + if ((!myFilterAlien.isSelected(null)) && (!myFilterNotMerged.isSelected(null)) && (!myFilterMerged.isSelected(null))) { return changeLists; } @@ -719,17 +717,20 @@ public class RootsAndBranches implements CommittedChangeListDecorator { final ListMergeStatus status = getStatus(list, true); if (ListMergeStatus.REFRESHING.equals(status)) { result.add(list); - } else if ((status == null) || ListMergeStatus.ALIEN.equals(status)) { - if (! myFilterAlien.isSelected(null)) { + } + else if ((status == null) || ListMergeStatus.ALIEN.equals(status)) { + if (!myFilterAlien.isSelected(null)) { result.add(list); } - } else if (ListMergeStatus.MERGED.equals(status) || ListMergeStatus.COMMON.equals(status)) { - if (! myFilterMerged.isSelected(null)) { + } + else if (ListMergeStatus.MERGED.equals(status) || ListMergeStatus.COMMON.equals(status)) { + if (!myFilterMerged.isSelected(null)) { result.add(list); } - } else { + } + else { // not merged - if (! myFilterNotMerged.isSelected(null)) { + if (!myFilterNotMerged.isSelected(null)) { result.add(list); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SingleCommittedListProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SingleCommittedListProvider.java index 79b75a89f04a..816e4fd97380 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SingleCommittedListProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SingleCommittedListProvider.java @@ -128,20 +128,17 @@ public class SingleCommittedListProvider { final SvnCopyPathTracker pathTracker = new SvnCopyPathTracker(repositoryUrl.toDecodedString(), repositoryRelativeUrl); SvnTarget target = SvnTarget.fromURL(url); - myVcs.getFactory(target).createHistoryClient().doLog(target, SVNRevision.HEAD, revisionBefore, false, true, false, 0, null, - new LogEntryConsumer() { - @Override - public void consume(LogEntry logEntry) { - checkDisposed(); - // date could be null for lists where there are paths that user has no rights to observe - if (logEntry.getDate() != null) { - pathTracker.accept(logEntry); - if (logEntry.getRevision() == revisionBefore.getNumber()) { - changeList[0] = createChangeList(logEntry); - } - } + myVcs.getFactory(target).createHistoryClient() + .doLog(target, SVNRevision.HEAD, revisionBefore, false, true, false, 0, null, logEntry -> { + checkDisposed(); + // date could be null for lists where there are paths that user has no rights to observe + if (logEntry.getDate() != null) { + pathTracker.accept(logEntry); + if (logEntry.getRevision() == revisionBefore.getNumber()) { + changeList[0] = createChangeList(logEntry); } } + } ); FilePath path = pathTracker.getFilePath(myVcs); @@ -160,14 +157,11 @@ public class SingleCommittedListProvider { } private boolean searchForUrl(@NotNull SVNURL url) throws VcsException { - LogEntryConsumer handler = new LogEntryConsumer() { - @Override - public void consume(LogEntry logEntry) { - checkDisposed(); - // date could be null for lists where there are paths that user has no rights to observe - if (logEntry.getDate() != null) { - changeList[0] = createChangeList(logEntry); - } + LogEntryConsumer handler = logEntry -> { + checkDisposed(); + // date could be null for lists where there are paths that user has no rights to observe + if (logEntry.getDate() != null) { + changeList[0] = createChangeList(logEntry); } }; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnChangeList.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnChangeList.java index e5b19530af97..1636becad1f2 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnChangeList.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnChangeList.java @@ -42,8 +42,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.*; import org.jetbrains.idea.svn.api.Depth; -import org.jetbrains.idea.svn.browse.DirectoryEntry; -import org.jetbrains.idea.svn.browse.DirectoryEntryConsumer; import org.jetbrains.idea.svn.commandLine.SvnBindException; import org.jetbrains.idea.svn.info.Info; import org.tmatesoft.svn.core.SVNException; @@ -359,14 +357,11 @@ public class SvnChangeList implements CommittedChangeList, VcsRevisionNumberAwar public SvnRepositoryContentRevision createRevisionLazily(final String path, final boolean isBeforeRevision) { final boolean knownAsDirectory = myKnownAsDirectories.contains(path); - final FilePath localPath = getLocalPath(path, new NotNullFunction() { - @NotNull - public Boolean fun(final File file) { - if (knownAsDirectory) return Boolean.TRUE; - // list will be next - myWithoutDirStatus.add(new Pair<>(myList.size(), isBeforeRevision)); - return Boolean.FALSE; - } + final FilePath localPath = getLocalPath(path, file -> { + if (knownAsDirectory) return Boolean.TRUE; + // list will be next + myWithoutDirStatus.add(new Pair<>(myList.size(), isBeforeRevision)); + return Boolean.FALSE; }); long revision = getRevision(isBeforeRevision); return localPath == null @@ -489,16 +484,12 @@ public class SvnChangeList implements CommittedChangeList, VcsRevisionNumberAwar SVNRevision revisionNumber = SVNRevision.create(getRevision(isBefore)); SvnTarget target = SvnTarget.fromURL(fullPath, revisionNumber); - myVcs.getFactory(target).createBrowseClient().list(target, revisionNumber, Depth.INFINITY, new DirectoryEntryConsumer() { + myVcs.getFactory(target).createBrowseClient().list(target, revisionNumber, Depth.INFINITY, entry -> { + final String childPath = path + '/' + entry.getRelativePath(); - @Override - public void consume(final DirectoryEntry entry) throws SVNException { - final String childPath = path + '/' + entry.getRelativePath(); - - if (!duplicates.contains(Pair.create(isBefore, childPath))) { - final ContentRevision contentRevision = createRevision(childPath, isBefore, entry.isDirectory()); - result.add(new Change(isBefore ? contentRevision : null, isBefore ? null : contentRevision)); - } + if (!duplicates.contains(Pair.create(isBefore, childPath))) { + final ContentRevision contentRevision1 = createRevision(childPath, isBefore, entry.isDirectory()); + result.add(new Change(isBefore ? contentRevision1 : null, isBefore ? null : contentRevision1)); } }); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnCommittedChangesProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnCommittedChangesProvider.java index b1a34fd32dd3..6ab3f9abc952 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnCommittedChangesProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnCommittedChangesProvider.java @@ -44,8 +44,6 @@ import org.jetbrains.idea.svn.SvnVcs; import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.branchConfig.ConfigureBranchesAction; import org.jetbrains.idea.svn.commandLine.SvnBindException; -import org.jetbrains.idea.svn.status.Status; -import org.jetbrains.idea.svn.status.StatusConsumer; import org.jetbrains.idea.svn.status.StatusType; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; @@ -375,17 +373,14 @@ public class SvnCommittedChangesProvider implements CachingCommittedChangesProvi File rootFile = root.getIOFile(); myVcs.getFactory(rootFile).createStatusClient() - .doStatus(rootFile, SVNRevision.UNDEFINED, Depth.INFINITY, true, false, false, false, new StatusConsumer() { - @Override - public void consume(Status status) throws SVNException { - File file = status.getFile(); - boolean changedOnServer = isNotNone(status.getRemoteContentsStatus()) || - isNotNone(status.getRemoteNodeStatus()) || - isNotNone(status.getRemotePropertiesStatus()); + .doStatus(rootFile, SVNRevision.UNDEFINED, Depth.INFINITY, true, false, false, false, status -> { + File file = status.getFile(); + boolean changedOnServer = isNotNone(status.getRemoteContentsStatus()) || + isNotNone(status.getRemoteNodeStatus()) || + isNotNone(status.getRemotePropertiesStatus()); - if (file != null && changedOnServer) { - result.add(VcsUtil.getFilePath(file)); - } + if (file != null && changedOnServer) { + result.add(VcsUtil.getFilePath(file)); } }, null); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnEditCommitMessageFromFileHistoryAction.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnEditCommitMessageFromFileHistoryAction.java index f5007e8ced1f..9fbe49b63570 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnEditCommitMessageFromFileHistoryAction.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnEditCommitMessageFromFileHistoryAction.java @@ -29,8 +29,6 @@ import com.intellij.util.Consumer; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.idea.svn.SvnVcs; -import java.util.List; - /** * Created with IntelliJ IDEA. * User: Irina.Chernushina @@ -54,28 +52,24 @@ public class SvnEditCommitMessageFromFileHistoryAction extends AnAction { final SvnFileRevision svnFileRevision = (SvnFileRevision) revision; final Consumer listener = VcsDataKeys.REMOTE_HISTORY_CHANGED_LISTENER.getData(e.getDataContext()); SvnEditCommitMessageAction.askAndEditRevision(svnFileRevision.getRevision().getNumber(), svnFileRevision.getCommitMessage(), - (SvnRepositoryLocation) svnFileRevision.getChangedRepositoryPath(), project, new Consumer() { - @Override - public void consume(final String newMessage) { - svnFileRevision.setCommitMessage(newMessage); - if (listener != null) { - listener.consume(newMessage); - } - ProjectLevelVcsManager.getInstance(project).getVcsHistoryCache().editCached(VcsUtil.getFilePath(revisionVirtualFile), vcsKey, - new Consumer>() { - @Override - public void consume(List revisions) { - for (VcsFileRevision fileRevision : revisions) { - if (! (fileRevision instanceof SvnFileRevision)) continue; - if (((SvnFileRevision) fileRevision).getRevision().getNumber() == svnFileRevision.getRevision().getNumber()) { - ((SvnFileRevision) fileRevision).setCommitMessage(newMessage); - break; - } - } - } - }); - } - }, true); + (SvnRepositoryLocation)svnFileRevision.getChangedRepositoryPath(), project, + newMessage -> { + svnFileRevision.setCommitMessage(newMessage); + if (listener != null) { + listener.consume(newMessage); + } + ProjectLevelVcsManager.getInstance(project).getVcsHistoryCache() + .editCached(VcsUtil.getFilePath(revisionVirtualFile), vcsKey, revisions -> { + for (VcsFileRevision fileRevision : revisions) { + if (!(fileRevision instanceof SvnFileRevision)) continue; + if (((SvnFileRevision)fileRevision).getRevision().getNumber() == + svnFileRevision.getRevision().getNumber()) { + ((SvnFileRevision)fileRevision).setCommitMessage(newMessage); + break; + } + } + }); + }, true); } @Override diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnFileRevision.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnFileRevision.java index 1e0f7412bfa8..b2f754e7dcb8 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnFileRevision.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnFileRevision.java @@ -19,7 +19,6 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.util.Throwable2Computable; import com.intellij.openapi.vcs.RepositoryLocation; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.history.VcsFileRevision; @@ -174,12 +173,7 @@ public class SvnFileRevision implements VcsFileRevision { else { result = ContentRevisionCache.getOrLoadAsBytes(myVCS.getProject(), VcsUtil.getFilePathOnNonLocal(myURL, false), getRevisionNumber(), myVCS.getKeyInstanceMethod(), ContentRevisionCache.UniqueType.REMOTE_CONTENT, - new Throwable2Computable() { - @Override - public byte[] compute() throws VcsException, IOException { - return loadContent(); - } - }); + () -> loadContent()); } return result; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnHistoryProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnHistoryProvider.java index e6a4abe482d6..9e39393be2ec 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnHistoryProvider.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnHistoryProvider.java @@ -19,7 +19,6 @@ import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; @@ -126,13 +125,10 @@ public class SvnHistoryProvider field.setEditable(false); field.setOpaque(false); field.setWrapStyleWord(true); - listener = new Consumer() { - @Override - public void consume(VcsFileRevision vcsFileRevision) { - field.setText(mergeSourceColumn.getText(vcsFileRevision)); - field.setCaretPosition(0); - field.repaint(); - } + listener = vcsFileRevision -> { + field.setText(mergeSourceColumn.getText(vcsFileRevision)); + field.setCaretPosition(0); + field.repaint(); }; final MergeSourceDetailsAction sourceAction = new MergeSourceDetailsAction(); @@ -247,7 +243,7 @@ public class SvnHistoryProvider } final SvnHistorySession historySession = - new SvnHistorySession(myVcs, Collections.emptyList(), committedPath, showMergeSources && Boolean.TRUE.equals(logLoader.mySupport15), null, false, + new SvnHistorySession(myVcs, Collections.emptyList(), committedPath, showMergeSources && Boolean.TRUE.equals(logLoader.mySupport15), null, false, ! path.isNonLocal()); final Ref sessionReported = new Ref<>(); @@ -255,15 +251,12 @@ public class SvnHistoryProvider if (indicator != null) { indicator.setText(SvnBundle.message("progress.text2.collecting.history", path.getName())); } - final Consumer consumer = new Consumer() { - @Override - public void consume(VcsFileRevision vcsFileRevision) { - if (!Boolean.TRUE.equals(sessionReported.get())) { - partner.reportCreatedEmptySession(historySession); - sessionReported.set(true); - } - partner.acceptRevision(vcsFileRevision); + final Consumer consumer = vcsFileRevision -> { + if (!Boolean.TRUE.equals(sessionReported.get())) { + partner.reportCreatedEmptySession(historySession); + sessionReported.set(true); } + partner.acceptRevision(vcsFileRevision); }; logLoader.setConsumer(consumer); @@ -372,12 +365,7 @@ public class SvnHistoryProvider } private static ThrowableConsumer createConsumerAdapter(final Consumer consumer) { - return new ThrowableConsumer() { - @Override - public void consume(VcsFileRevision revision) throws SVNException { - consumer.consume(revision); - } - }; + return revision -> consumer.consume(revision); } private static class RepositoryLoader extends LogLoader { @@ -459,13 +447,7 @@ public class SvnHistoryProvider } final RepositoryLogEntryHandler repositoryLogEntryHandler = - new RepositoryLogEntryHandler(myVcs, myUrl, SVNRevision.UNDEFINED, relativeUrl, - new ThrowableConsumer() { - @Override - public void consume(VcsFileRevision revision) throws SVNException { - myConsumer.consume(revision); - } - }, rootURL); + new RepositoryLogEntryHandler(myVcs, myUrl, SVNRevision.UNDEFINED, relativeUrl, revision -> myConsumer.consume(revision), rootURL); repositoryLogEntryHandler.setThrowCancelOnMeetPathCreation(true); SvnTarget target = SvnTarget.fromURL(rootURL, myFrom); @@ -536,56 +518,53 @@ public class SvnHistoryProvider myPegRevision = pegRevision; myUrl = url; myRepositoryRoot = repoRootURL; - myTracker = new SvnMergeSourceTracker(new ThrowableConsumer, SVNException>() { - @Override - public void consume(final Pair svnLogEntryIntegerPair) throws SVNException { - final LogEntry logEntry = svnLogEntryIntegerPair.getFirst(); + myTracker = new SvnMergeSourceTracker(svnLogEntryIntegerPair -> { + final LogEntry logEntry = svnLogEntryIntegerPair.getFirst(); - if (myIndicator != null) { - if (myIndicator.isCanceled()) { - SVNErrorManager.cancel(SvnBundle.message("exception.text.update.operation.cancelled"), SVNLogType.DEFAULT); - } - myIndicator.setText2(SvnBundle.message("progress.text2.revision.processed", logEntry.getRevision())); + if (myIndicator != null) { + if (myIndicator.isCanceled()) { + SVNErrorManager.cancel(SvnBundle.message("exception.text.update.operation.cancelled"), SVNLogType.DEFAULT); } - LogEntryPath entryPath = null; - String copyPath = null; - final int mergeLevel = svnLogEntryIntegerPair.getSecond(); + myIndicator.setText2(SvnBundle.message("progress.text2.revision.processed", logEntry.getRevision())); + } + LogEntryPath entryPath = null; + String copyPath = null; + final int mergeLevel = svnLogEntryIntegerPair.getSecond(); - if (! myLastPathCorrector.isRoot()) { - myLastPathCorrector.consume(logEntry); - entryPath = myLastPathCorrector.getDirectlyMentioned(); - copyPath = null; - if (entryPath != null) { - copyPath = entryPath.getCopyPath(); - } else { - // if there are no path with exact match, check whether parent or child paths had changed - // "entry path" is allowed to be null now; if it is null, last path would be taken for revision construction - - // Separate LogEntry is issued for each "merge source" revision. These "merge source" revisions are treated as child - // revisions of some other revision - this way we construct merge hierarchy. - // mergeLevel >= 0 indicates that we are currently processing some "merge source" revision. This "merge source" revision - // contains changes from some other branch - so checkForChildChanges() and checkForParentChanges() return "false". - // Because of this case we apply these methods only for non-"merge source" revisions - this means mergeLevel < 0. - // TODO: Do not apply path filtering even for log entries on the first level => just output of 'svn log' should be returned. - // TODO: Looks like there is no cases when we issue 'svn log' for some parent paths or some other cases where we need such - // TODO: filtering. Check user feedback on this. -// if (mergeLevel < 0 && !checkForChildChanges(logEntry) && !checkForParentChanges(logEntry)) return; - } - } - - final SvnFileRevision revision = createRevision(logEntry, copyPath, entryPath); - if (mergeLevel >= 0) { - addToListByLevel((SvnFileRevision)myPrevious, revision, mergeLevel); + if (!myLastPathCorrector.isRoot()) { + myLastPathCorrector.consume(logEntry); + entryPath = myLastPathCorrector.getDirectlyMentioned(); + copyPath = null; + if (entryPath != null) { + copyPath = entryPath.getCopyPath(); } else { - myResult.consume(revision); - myPrevious = revision; - } - if (myThrowCancelOnMeetPathCreation && myUrl.equals(revision.getURL()) && entryPath != null && entryPath.getType() == 'A') { - throw new SVNCancelException(); + // if there are no path with exact match, check whether parent or child paths had changed + // "entry path" is allowed to be null now; if it is null, last path would be taken for revision construction + + // Separate LogEntry is issued for each "merge source" revision. These "merge source" revisions are treated as child + // revisions of some other revision - this way we construct merge hierarchy. + // mergeLevel >= 0 indicates that we are currently processing some "merge source" revision. This "merge source" revision + // contains changes from some other branch - so checkForChildChanges() and checkForParentChanges() return "false". + // Because of this case we apply these methods only for non-"merge source" revisions - this means mergeLevel < 0. + // TODO: Do not apply path filtering even for log entries on the first level => just output of 'svn log' should be returned. + // TODO: Looks like there is no cases when we issue 'svn log' for some parent paths or some other cases where we need such + // TODO: filtering. Check user feedback on this. +// if (mergeLevel < 0 && !checkForChildChanges(logEntry) && !checkForParentChanges(logEntry)) return; } } + final SvnFileRevision revision = createRevision(logEntry, copyPath, entryPath); + if (mergeLevel >= 0) { + addToListByLevel((SvnFileRevision)myPrevious, revision, mergeLevel); + } + else { + myResult.consume(revision); + myPrevious = revision; + } + if (myThrowCancelOnMeetPathCreation && myUrl.equals(revision.getURL()) && entryPath != null && entryPath.getType() == 'A') { + throw new SVNCancelException(); + } }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnKitHistoryClient.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnKitHistoryClient.java index 341cd557f93a..1405ebd3e9ff 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnKitHistoryClient.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnKitHistoryClient.java @@ -8,7 +8,6 @@ import org.jetbrains.idea.svn.api.BaseSvnClient; import org.jetbrains.idea.svn.commandLine.SvnBindException; import org.tmatesoft.svn.core.ISVNLogEntryHandler; import org.tmatesoft.svn.core.SVNException; -import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.wc.SVNLogClient; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc2.SvnTarget; @@ -52,12 +51,7 @@ public class SvnKitHistoryClient extends BaseSvnClient implements HistoryClient ISVNLogEntryHandler result = null; if (handler != null) { - result = new ISVNLogEntryHandler() { - @Override - public void handleLogEntry(SVNLogEntry logEntry) throws SVNException { - handler.consume(LogEntry.create(logEntry)); - } - }; + result = logEntry -> handler.consume(LogEntry.create(logEntry)); } return result; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnLogUtil.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnLogUtil.java index c428e46e4460..21fe654a076f 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnLogUtil.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnLogUtil.java @@ -61,23 +61,20 @@ public class SvnLogUtil implements SvnLogLoader { final SVNRevision toIncluding, final boolean includingYoungest, final boolean includeOldest, final List result) { - return new LogEntryConsumer() { - @Override - public void consume(LogEntry logEntry) { - if (myProject.isDisposed()) throw new ProcessCanceledException(); - final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); - if (progress != null) { - progress.setText2(SvnBundle.message("progress.text2.processing.revision", logEntry.getRevision())); - progress.checkCanceled(); - } - if ((!includingYoungest) && (logEntry.getRevision() == fromIncluding.getNumber())) { - return; - } - if ((!includeOldest) && (logEntry.getRevision() == toIncluding.getNumber())) { - return; - } - result.add(new SvnChangeList(myVcs, myLocation, logEntry, myRepositoryRoot.toString())); + return logEntry -> { + if (myProject.isDisposed()) throw new ProcessCanceledException(); + final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator(); + if (progress != null) { + progress.setText2(SvnBundle.message("progress.text2.processing.revision", logEntry.getRevision())); + progress.checkCanceled(); } + if ((!includingYoungest) && (logEntry.getRevision() == fromIncluding.getNumber())) { + return; + } + if ((!includeOldest) && (logEntry.getRevision() == toIncluding.getNumber())) { + return; + } + result.add(new SvnChangeList(myVcs, myLocation, logEntry, myRepositoryRoot.toString())); }; } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnMergeInfoRootPanelManual.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnMergeInfoRootPanelManual.java index a93b3820050d..5047c138343a 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnMergeInfoRootPanelManual.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnMergeInfoRootPanelManual.java @@ -30,7 +30,6 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.SvnBundle; import org.jetbrains.idea.svn.SvnUtil; import org.jetbrains.idea.svn.branchConfig.SelectBranchPopup; -import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationNew; import org.jetbrains.idea.svn.branchConfig.SvnBranchMapperManager; import org.jetbrains.idea.svn.dialogs.WCInfoWithBranches; import org.jetbrains.idea.svn.integrate.IntegratedSelectedOptionsDialog; @@ -39,8 +38,6 @@ import org.tmatesoft.svn.core.SVNURL; import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.Map; import java.util.Set; @@ -80,39 +77,29 @@ public class SvnMergeInfoRootPanelManual { } private void initWithData() { - myInclude.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - myListener.run(); - } - }); + myInclude.addActionListener(e -> myListener.run()); myUrlText.setText(myInfo.getUrl().toString()); - myFixedSelectLocal.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - if (mySelectedBranch != null) { - Pair info = - IntegratedSelectedOptionsDialog.selectWorkingCopy(myProject, myInfo.getUrl(), mySelectedBranch.getUrl(), false, null, null); - if (info != null) { - calculateBranchPathByBranch(mySelectedBranch.getUrl(), info.getFirst().getLocalPath()); - } - - myListener.run(); + myFixedSelectLocal.addActionListener(e -> { + if (mySelectedBranch != null) { + Pair info = + IntegratedSelectedOptionsDialog.selectWorkingCopy(myProject, myInfo.getUrl(), mySelectedBranch.getUrl(), false, null, null); + if (info != null) { + calculateBranchPathByBranch(mySelectedBranch.getUrl(), info.getFirst().getLocalPath()); } + + myListener.run(); } }); myBranchField.getTextField().setEditable(false); - myBranchField.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - final VirtualFile vf = SvnUtil.getVirtualFile(myInfo.getPath()); - if (vf != null) { - SelectBranchPopup.show(myProject, vf, new SelectBranchPopup.BranchSelectedCallback() { - public void branchSelected(final Project project, final SvnBranchConfigurationNew configuration, final String url, final long revision) { - refreshSelectedBranch(new WCInfoWithBranches.Branch(url)); - calculateBranchPathByBranch(mySelectedBranch.getUrl(), null); - myListener.run(); - } - }, SvnBundle.message("select.branch.popup.general.title")); - } + myBranchField.addActionListener(e -> { + final VirtualFile vf = SvnUtil.getVirtualFile(myInfo.getPath()); + if (vf != null) { + SelectBranchPopup.show(myProject, vf, (project, configuration, url, revision) -> { + refreshSelectedBranch(new WCInfoWithBranches.Branch(url)); + calculateBranchPathByBranch(mySelectedBranch.getUrl(), null); + myListener.run(); + }, SvnBundle.message("select.branch.popup.general.title")); } }); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnRevisionsNavigationMediator.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnRevisionsNavigationMediator.java index a05e1baddc80..b015aa0cf174 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnRevisionsNavigationMediator.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnRevisionsNavigationMediator.java @@ -41,7 +41,7 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio private final InternallyCachedProvider myInternallyCached; private final VisuallyCachedProvider myVisuallyCached; - + private final List> myChunks; private boolean myCanNotGoBack; private int myCurrentIdx; @@ -58,15 +58,12 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio final VcsException[] exception = new VcsException[1]; final Ref infoRef = new Ref<>(); - Runnable process = new Runnable() { - @Override - public void run() { - try { - infoRef.set(vcs.getInfo(location.toSvnUrl(), SVNRevision.HEAD)); - } - catch (SvnBindException e) { - exception[0] = e; - } + Runnable process = () -> { + try { + infoRef.set(vcs.getInfo(location.toSvnUrl(), SVNRevision.HEAD)); + } + catch (SvnBindException e) { + exception[0] = e; } }; underProgress(exception, process); @@ -77,8 +74,10 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio } final Iterator visualIterator = project.isDefault() ? null : - CommittedChangesCache.getInstance(project).getBackBunchedIterator(vcs, vcsRoot, location, CHUNK_SIZE); - final Iterator internalIterator = project.isDefault() ? null : LoadedRevisionsCache.getInstance(project).iterator(location.getURL()); + CommittedChangesCache.getInstance(project) + .getBackBunchedIterator(vcs, vcsRoot, location, CHUNK_SIZE); + final Iterator internalIterator = + project.isDefault() ? null : LoadedRevisionsCache.getInstance(project).iterator(location.getURL()); myInternallyCached = (internalIterator == null) ? null : new InternallyCachedProvider(internalIterator, myProject); myVisuallyCached = (visualIterator == null) ? null : new VisuallyCachedProvider(visualIterator, myProject, location); @@ -90,16 +89,13 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio myCurrentIdx = -1; - underProgress(exception, new Runnable() { - @Override - public void run() { - // init first screen - try { - goBack(); - } - catch (VcsException e) { - exception[0] = e; - } + underProgress(exception, () -> { + // init first screen + try { + goBack(); + } + catch (VcsException e) { + exception[0] = e; } }); } @@ -111,13 +107,13 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio if (exception[0] != null) { throw exception[0]; } - if (! succeeded) { + if (!succeeded) { throw new ProcessCanceledException(); } } public boolean canGoBack() { - return ((myCurrentIdx + 1) < myChunks.size()) || (! myCanNotGoBack); + return ((myCurrentIdx + 1) < myChunks.size()) || (!myCanNotGoBack); } public boolean canGoForward() { @@ -126,7 +122,7 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio public void goBack() throws VcsException { if ((myCurrentIdx + 1) < myChunks.size()) { - ++ myCurrentIdx; + ++myCurrentIdx; return; } @@ -134,29 +130,29 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio final List fragments = myChunkFactory.goBack(CHUNK_SIZE, canNotGoBackRef); myCanNotGoBack = canNotGoBackRef.get().booleanValue(); - if (! fragments.isEmpty()) { + if (!fragments.isEmpty()) { // load - ++ myCurrentIdx; + ++myCurrentIdx; myChunks.add(fragments); } } public void goForward() { - -- myCurrentIdx; + --myCurrentIdx; } public List getCurrent() { debugPrinting(); - return (List) ((myChunks.isEmpty()) ? Collections.>emptyList() : - fragmentsToLists(myChunks.get(myCurrentIdx))); + return (List)((myChunks.isEmpty()) ? Collections.>emptyList() : + fragmentsToLists(myChunks.get(myCurrentIdx))); } private void debugPrinting() { LOG.debug("== showing screen (" + myCurrentIdx + "): =="); - if (! myChunks.isEmpty()) { + if (!myChunks.isEmpty()) { for (Fragment fragment : myChunks.get(myCurrentIdx)) { LOG.debug(fragment.getOrigin().toString() + " from: " + fragment.getList().get(0).getNumber() + - " to: " + fragment.getList().get(fragment.getList().size() - 1).getNumber()); + " to: " + fragment.getList().get(fragment.getList().size() - 1).getNumber()); } } LOG.debug("== end of screen =="); @@ -175,9 +171,11 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio myVisuallyCached.doCacheUpdate(myChunks); // keep also in internal cache InternallyCachedProvider.initCache(myChunks, myProject); - } else if (myInternallyCached != null) { + } + else if (myInternallyCached != null) { myInternallyCached.doCacheUpdate(myChunks); - } else { + } + else { InternallyCachedProvider.initCache(myChunks, myProject); } } @@ -209,13 +207,13 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio @Override protected void addToLoaded(final ChangesBunch loaded) { - myHolesDetected |= (! loaded.isConsistentWithPrevious()); + myHolesDetected |= (!loaded.isConsistentWithPrevious()); super.addToLoaded(loaded); } public static void initCache(final List> fragmentListList, final Project project) { final List lists = getAllBeforeVisuallyCached(fragmentListList); - if (! lists.isEmpty()) { + if (!lists.isEmpty()) { LoadedRevisionsCache.getInstance(project).put(lists, false, null); } } @@ -233,7 +231,7 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio final Fragment fragment = fragmentList.get(j); liveMet |= Origin.LIVE.equals(fragment.getOrigin()); if (Origin.INTERNAL.equals(fragment.getOrigin())) { - bindAddress = ((LoadedRevisionsCache.Bunch) fragment.getOriginBunch()).getNext(); + bindAddress = ((LoadedRevisionsCache.Bunch)fragment.getOriginBunch()).getNext(); // latest element if ((i == (fragmentsListList.size() - 1)) && (j == (fragmentList.size() - 1))) { lists.addAll(fragment.getOriginBunch().getList()); @@ -244,15 +242,16 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio lists.addAll(fragment.getList()); } } - if (! liveMet) { + if (!liveMet) { return; } - } else { + } + else { // until _first_internally for (List fragmentList : fragmentsListList) { for (Fragment fragment : fragmentList) { if (Origin.INTERNAL.equals(fragment.getOrigin())) { - bindAddress = (LoadedRevisionsCache.Bunch) fragment.getOriginBunch(); + bindAddress = (LoadedRevisionsCache.Bunch)fragment.getOriginBunch(); consistent = true; break; } @@ -261,7 +260,7 @@ public class SvnRevisionsNavigationMediator implements CommittedChangesNavigatio } } - if (! lists.isEmpty()) { + if (!lists.isEmpty()) { LoadedRevisionsCache.getInstance(myProject).put(lists, consistent, bindAddress); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/WcInfoLoader.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/WcInfoLoader.java index 4a1195270c5f..aba8d9826873 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/history/WcInfoLoader.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/history/WcInfoLoader.java @@ -33,7 +33,6 @@ import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import java.io.File; import java.util.Collections; -import java.util.Comparator; import java.util.List; public class WcInfoLoader { @@ -107,11 +106,7 @@ public class WcInfoLoader { } } - Collections.sort(branches, new Comparator() { - public int compare(final WCInfoWithBranches.Branch o1, final WCInfoWithBranches.Branch o2) { - return Comparing.compare(o1.getUrl(), o2.getUrl()); - } - }); + Collections.sort(branches, (o1, o2) -> Comparing.compare(o1.getUrl(), o2.getUrl())); return new WCInfoWithBranches(info, branches, rootUrlInfo.getRoot(), workingCopyBranch.get()); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/info/CmdInfoClient.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/info/CmdInfoClient.java index 67c0947988b8..9399180cdf96 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/info/CmdInfoClient.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/info/CmdInfoClient.java @@ -21,7 +21,6 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -104,15 +103,12 @@ public class CmdInfoClient extends BaseSvnClient implements InfoClient { return; } - final SvnInfoHandler infoHandler = new SvnInfoHandler(base, new Consumer() { - @Override - public void consume(Info info) { - try { - handler.consume(info); - } - catch (SVNException e) { - throw new SvnExceptionWrapper(e); - } + final SvnInfoHandler infoHandler = new SvnInfoHandler(base, info -> { + try { + handler.consume(info); + } + catch (SVNException e) { + throw new SvnExceptionWrapper(e); } }); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/info/SvnInfoHandler.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/info/SvnInfoHandler.java index 513090c14dcb..0e91170b4808 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/info/SvnInfoHandler.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/info/SvnInfoHandler.java @@ -144,204 +144,39 @@ public class SvnInfoHandler extends DefaultHandler { } private void fillElements() { - myElementsMap.put("copy-from-url", new Getter() { - @Override - public ElementHandlerBase get() { - return new CopyFromUrl(); - } - }); - myElementsMap.put("copy-from-rev", new Getter() { - @Override - public ElementHandlerBase get() { - return new CopyFromRev(); - } - }); - myElementsMap.put("changelist", new Getter() { - @Override - public ElementHandlerBase get() { - return new ChangeList(); - } - }); - myElementsMap.put("author", new Getter() { - @Override - public ElementHandlerBase get() { - return new Author(); - } - }); - myElementsMap.put("checksum", new Getter() { - @Override - public ElementHandlerBase get() { - return new Checksum(); - } - }); - myElementsMap.put("commit", new Getter() { - @Override - public ElementHandlerBase get() { - return new Commit(); - } - }); - myElementsMap.put("conflict", new Getter() { - @Override - public ElementHandlerBase get() { - return new Conflict(); - } - }); - myElementsMap.put("cur-base-file", new Getter() { - @Override - public ElementHandlerBase get() { - return new CurBase(); - } - }); - myElementsMap.put("date", new Getter() { - @Override - public ElementHandlerBase get() { - return new Date(); - } - }); - myElementsMap.put("depth", new Getter() { - @Override - public ElementHandlerBase get() { - return new Depth(); - } - }); - myElementsMap.put("entry", new Getter() { - @Override - public ElementHandlerBase get() { - return new Entry(myBase); - } - }); - myElementsMap.put("info", new Getter() { - @Override - public ElementHandlerBase get() { - return new Info(); - } - }); - myElementsMap.put("prev-base-file", new Getter() { - @Override - public ElementHandlerBase get() { - return new PrevBase(); - } - }); - myElementsMap.put("prev-wc-file", new Getter() { - @Override - public ElementHandlerBase get() { - return new PrevWc(); - } - }); - myElementsMap.put("prop-file", new Getter() { - @Override - public ElementHandlerBase get() { - return new PropFile(); - } - }); - myElementsMap.put("repository", new Getter() { - @Override - public ElementHandlerBase get() { - return new Repository(); - } - }); - myElementsMap.put("root", new Getter() { - @Override - public ElementHandlerBase get() { - return new Root(); - } - }); - myElementsMap.put("schedule", new Getter() { - @Override - public ElementHandlerBase get() { - return new Schedule(); - } - }); - myElementsMap.put("text-updated", new Getter() { - @Override - public ElementHandlerBase get() { - return new TextUpdated(); - } - }); - myElementsMap.put("tree-conflict", new Getter() { - @Override - public ElementHandlerBase get() { - return new TreeConflict(); - } - }); - myElementsMap.put("url", new Getter() { - @Override - public ElementHandlerBase get() { - return new Url(); - } - }); - myElementsMap.put("relative-url", new Getter() { - @Override - public ElementHandlerBase get() { - return new RelativeUrl(); - } - }); - myElementsMap.put("lock", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockElement(); - } - }); - myElementsMap.put("token", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockToken(); - } - }); - myElementsMap.put("owner", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockOwner(); - } - }); - myElementsMap.put("comment", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockComment(); - } - }); - myElementsMap.put("created", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockCreated(); - } - }); - myElementsMap.put("uuid", new Getter() { - @Override - public ElementHandlerBase get() { - return new Uuid(); - } - }); - myElementsMap.put("version", new Getter() { - @Override - public ElementHandlerBase get() { - return new Version(); - } - }); - myElementsMap.put("wc-info", new Getter() { - @Override - public ElementHandlerBase get() { - return new WcInfo(); - } - }); - myElementsMap.put("moved-to", new Getter() { - @Override - public ElementHandlerBase get() { - return new MovedPath(); - } - }); - myElementsMap.put("moved-from", new Getter() { - @Override - public ElementHandlerBase get() { - return new MovedPath(); - } - }); - myElementsMap.put("wcroot-abspath", new Getter() { - @Override - public ElementHandlerBase get() { - return new WcRoot(); - } - }); + myElementsMap.put("copy-from-url", () -> new CopyFromUrl()); + myElementsMap.put("copy-from-rev", () -> new CopyFromRev()); + myElementsMap.put("changelist", () -> new ChangeList()); + myElementsMap.put("author", () -> new Author()); + myElementsMap.put("checksum", () -> new Checksum()); + myElementsMap.put("commit", () -> new Commit()); + myElementsMap.put("conflict", () -> new Conflict()); + myElementsMap.put("cur-base-file", () -> new CurBase()); + myElementsMap.put("date", () -> new Date()); + myElementsMap.put("depth", () -> new Depth()); + myElementsMap.put("entry", () -> new Entry(myBase)); + myElementsMap.put("info", () -> new Info()); + myElementsMap.put("prev-base-file", () -> new PrevBase()); + myElementsMap.put("prev-wc-file", () -> new PrevWc()); + myElementsMap.put("prop-file", () -> new PropFile()); + myElementsMap.put("repository", () -> new Repository()); + myElementsMap.put("root", () -> new Root()); + myElementsMap.put("schedule", () -> new Schedule()); + myElementsMap.put("text-updated", () -> new TextUpdated()); + myElementsMap.put("tree-conflict", () -> new TreeConflict()); + myElementsMap.put("url", () -> new Url()); + myElementsMap.put("relative-url", () -> new RelativeUrl()); + myElementsMap.put("lock", () -> new LockElement()); + myElementsMap.put("token", () -> new LockToken()); + myElementsMap.put("owner", () -> new LockOwner()); + myElementsMap.put("comment", () -> new LockComment()); + myElementsMap.put("created", () -> new LockCreated()); + myElementsMap.put("uuid", () -> new Uuid()); + myElementsMap.put("version", () -> new Version()); + myElementsMap.put("wc-info", () -> new WcInfo()); + myElementsMap.put("moved-to", () -> new MovedPath()); + myElementsMap.put("moved-from", () -> new MovedPath()); + myElementsMap.put("wcroot-abspath", () -> new WcRoot()); } public Map getResultsMap() { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/IntegratedSelectedOptionsDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/IntegratedSelectedOptionsDialog.java index 760e074e511a..290affc5c36b 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/IntegratedSelectedOptionsDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/IntegratedSelectedOptionsDialog.java @@ -40,8 +40,6 @@ import org.jetbrains.idea.svn.info.Info; import org.tmatesoft.svn.core.SVNURL; import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import java.io.File; import java.util.*; @@ -77,11 +75,8 @@ public class IntegratedSelectedOptionsDialog extends DialogWrapper { init(); myWorkingCopiesList.setModel(new DefaultListModel()); - myWorkingCopiesList.addListSelectionListener(new ListSelectionListener() { - public void valueChanged(final ListSelectionEvent e) { - setOKActionEnabled((! myMustSelectBeforeOk) || (myWorkingCopiesList.getSelectedIndex() != -1)); - } - }); + myWorkingCopiesList + .addListSelectionListener(e -> setOKActionEnabled((!myMustSelectBeforeOk) || (myWorkingCopiesList.getSelectedIndex() != -1))); setOKActionEnabled((! myMustSelectBeforeOk) || (myWorkingCopiesList.getSelectedIndex() != -1)); final List workingCopyInfoList = new ArrayList<>(); @@ -212,12 +207,9 @@ public class IntegratedSelectedOptionsDialog extends DialogWrapper { } private boolean underProject(final File file) { - return ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public Boolean compute() { - final VirtualFile vf = SvnUtil.getVirtualFile(file.getAbsolutePath()); - return (vf == null) || PeriodicalTasksCloser.getInstance().safeGetService(myProject, FileIndexFacade.class).isInContent(vf); - } + return ApplicationManager.getApplication().runReadAction((Computable)() -> { + final VirtualFile vf = SvnUtil.getVirtualFile(file.getAbsolutePath()); + return (vf == null) || PeriodicalTasksCloser.getInstance().safeGetService(myProject, FileIndexFacade.class).isInContent(vf); }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/Merger.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/Merger.java index 0a77112f976c..ddb3be33b23b 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/Merger.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/Merger.java @@ -181,7 +181,7 @@ public class Merger implements IMerger { @Nullable public String getSkipped() { - return getSkippedMessage(myMergeChunk != null ? myMergeChunk.chunkAndAfterLists() : ContainerUtil.emptyList()); + return getSkippedMessage(myMergeChunk != null ? myMergeChunk.chunkAndAfterLists() : ContainerUtil.emptyList()); } @Nullable @@ -221,7 +221,7 @@ public class Merger implements IMerger { List processed = myMergeChunk != null ? ContainerUtil.newArrayList(myMergeChunk.chunkAndBeforeLists()) - : ContainerUtil.emptyList(); + : ContainerUtil.emptyList(); myProject.getMessageBus().syncPublisher(COMMITTED_CHANGES_MERGED_STATE).event(processed); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MoreAction.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MoreAction.java index 40b2b2924180..d3c118e7d157 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MoreAction.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/MoreAction.java @@ -23,8 +23,6 @@ import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; /** * @author irengrig @@ -47,12 +45,7 @@ public abstract class MoreAction extends AnAction implements CustomComponentAct myPanel.setLayout(layout); myLoadMoreBtn = new JButton(name); myLoadMoreBtn.setMargin(JBUI.insets(2)); - myLoadMoreBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - MoreAction.this.actionPerformed(null); - } - }); + myLoadMoreBtn.addActionListener(e -> MoreAction.this.actionPerformed(null)); myPanel.add(myLoadMoreBtn); myLabel = new JLabel("Loading..."); myLabel.setForeground(UIUtil.getInactiveTextColor()); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeWayOptionsPanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeWayOptionsPanel.java index 04abb25c9fcf..0703d7a51b19 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeWayOptionsPanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/QuickMergeWayOptionsPanel.java @@ -21,7 +21,6 @@ import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import javax.swing.*; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** @@ -59,12 +58,9 @@ public class QuickMergeWayOptionsPanel { } private ActionListener setCodeAndClose(@NotNull QuickMergeContentsVariants variant) { - return new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - myVariant = variant; - close(); - } + return e -> { + myVariant = variant; + close(); }; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ResolveWorker.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ResolveWorker.java index d162f4373362..dc4e712bec41 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ResolveWorker.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ResolveWorker.java @@ -46,21 +46,18 @@ public class ResolveWorker { } private void refreshChangeListsFindConflicts(final UpdatedFiles updatedFiles) { - UpdateFilesHelper.iterateFileGroupFiles(updatedFiles, - new UpdateFilesHelper.Callback() { - public void onFile(final String filePath, final String groupId) { - final VirtualFile vf = SvnUtil.getVirtualFile(filePath); - if (vf != null) { - // refresh base directory so that conflict files should be detected - // file itself is already refreshed - vf.getParent().refresh(false, false); - myDirtyScopeManager.fileDirty(vf); - } - if (FileGroup.MERGED_WITH_CONFLICT_ID.equals(groupId)) { - myConflictedVirtualFiles.add(vf); - } - } - }); + UpdateFilesHelper.iterateFileGroupFiles(updatedFiles, (filePath, groupId) -> { + final VirtualFile vf = SvnUtil.getVirtualFile(filePath); + if (vf != null) { + // refresh base directory so that conflict files should be detected + // file itself is already refreshed + vf.getParent().refresh(false, false); + myDirtyScopeManager.fileDirty(vf); + } + if (FileGroup.MERGED_WITH_CONFLICT_ID.equals(groupId)) { + myConflictedVirtualFiles.add(vf); + } + }); } public boolean needsInteraction(final UpdatedFiles updatedFiles) { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/SvnIntegrateChangesTask.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/SvnIntegrateChangesTask.java index 3e7d40024601..dfcf5c0fabf7 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/SvnIntegrateChangesTask.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/SvnIntegrateChangesTask.java @@ -32,8 +32,6 @@ import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx; import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier; import com.intellij.openapi.vcs.update.*; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Consumer; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; @@ -138,12 +136,7 @@ public class SvnIntegrateChangesTask extends Task.Backgroundable { @NotNull private static VcsException createException(boolean isWarning, @NotNull String... messages) { - Collection notEmptyMessages = ContainerUtil.mapNotNull(messages, new Function() { - @Override - public String fun(@Nullable String message) { - return StringUtil.nullize(message, true); - } - }); + Collection notEmptyMessages = ContainerUtil.mapNotNull(messages, message -> StringUtil.nullize(message, true)); return new VcsException(notEmptyMessages).setIsWarning(isWarning); } @@ -249,11 +242,7 @@ public class SvnIntegrateChangesTask extends Task.Backgroundable { } private void stepToNextChangeList() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - ProgressManager.getInstance().run(SvnIntegrateChangesTask.this); - } - }); + ApplicationManager.getApplication().invokeLater(() -> ProgressManager.getInstance().run(SvnIntegrateChangesTask.this)); } /** @@ -275,8 +264,8 @@ public class SvnIntegrateChangesTask extends Task.Backgroundable { // for changes to be detected, we need switch to background change list manager update thread and back to dispatch thread // so callback is used; ok to be called after VCS update markup closed: no remote operations final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); - changeListManager.invokeAfterUpdate(new Runnable() { - public void run() { + changeListManager.invokeAfterUpdate( + () -> { Collection changes = new ArrayList<>(); for (FilePath file : files) { ContainerUtil.addIfNotNull(changes, changeListManager.getChange(file)); @@ -284,24 +273,16 @@ public class SvnIntegrateChangesTask extends Task.Backgroundable { CommitChangeListDialog.commitChanges(myProject, changes, null, null, myMerger.getComment()); prepareAndShowResults(); - } - }, InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE, myTitle, - new Consumer() { - public void consume(final VcsDirtyScopeManager vcsDirtyScopeManager) { - vcsDirtyScopeManager.filePathsDirty(files, null); - } - }, null); + }, InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE, myTitle, vcsDirtyScopeManager -> vcsDirtyScopeManager.filePathsDirty(files, null), + null); } @NotNull private Collection gatherChangedPaths() { final Collection result = new ArrayList<>(); - UpdateFilesHelper.iterateFileGroupFiles(myAccumulatedFiles.getUpdatedFiles(), new UpdateFilesHelper.Callback() { - public void onFile(final String filePath, final String groupId) { - result.add(VcsUtil.getFilePath(new File(filePath))); - } - }); + UpdateFilesHelper.iterateFileGroupFiles(myAccumulatedFiles.getUpdatedFiles(), + (filePath, groupId) -> result.add(VcsUtil.getFilePath(new File(filePath)))); ContainerUtil.addIfNotNull(result, myMergeTarget); return result; @@ -313,11 +294,8 @@ public class SvnIntegrateChangesTask extends Task.Backgroundable { if (myMergeTarget != null) { dirtyScope.addDir(myMergeTarget); } else { - UpdateFilesHelper.iterateFileGroupFiles(myAccumulatedFiles.getUpdatedFiles(), new UpdateFilesHelper.Callback() { - public void onFile(final String filePath, final String groupId) { - dirtyScope.addFile(VcsUtil.getFilePath(new File(filePath))); - } - }); + UpdateFilesHelper.iterateFileGroupFiles(myAccumulatedFiles.getUpdatedFiles(), + (filePath, groupId) -> dirtyScope.addFile(VcsUtil.getFilePath(new File(filePath)))); } showAlienCommit(dirtyScope); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ToBeMergedDialog.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ToBeMergedDialog.java index ff20dc25dbc8..8404f057d24a 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ToBeMergedDialog.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/ToBeMergedDialog.java @@ -231,20 +231,17 @@ public class ToBeMergedDialog extends DialogWrapper { } private void initUI() { - final ListSelectionListener selectionListener = new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - List changeLists = myRevisionsList.getSelectedObjects(); + final ListSelectionListener selectionListener = e -> { + List changeLists = myRevisionsList.getSelectedObjects(); - myAlreadyMerged.clear(); - for (SvnChangeList changeList : changeLists) { - myAlreadyMerged.addAll(getAlreadyMergedPaths(changeList)); - } - myRepositoryChangesBrowser.setChangesToDisplay(collectChanges(changeLists, false)); - - mySplitter.doLayout(); - myRepositoryChangesBrowser.repaint(); + myAlreadyMerged.clear(); + for (SvnChangeList changeList : changeLists) { + myAlreadyMerged.addAll(getAlreadyMergedPaths(changeList)); } + myRepositoryChangesBrowser.setChangesToDisplay(collectChanges(changeLists, false)); + + mySplitter.doLayout(); + myRepositoryChangesBrowser.repaint(); }; final MyListCellRenderer listCellRenderer = new MyListCellRenderer(); myRevisionsList = new TableView() { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/BranchInfo.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/BranchInfo.java index b0881cf73582..5e4da658822e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/BranchInfo.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/BranchInfo.java @@ -17,7 +17,6 @@ package org.jetbrains.idea.svn.mergeinfo; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Factory; import com.intellij.openapi.vcs.VcsException; import com.intellij.util.containers.ContainerUtil; @@ -111,12 +110,8 @@ public class BranchInfo { result = SvnMergeInfoCache.MergeCheckResult.COMMON; } else { - result = ContainerUtil.getOrCreate(myAlreadyCalculatedMap, list.getNumber(), new Factory() { - @Override - public SvnMergeInfoCache.MergeCheckResult create() { - return checkAlive(list, branchPath); - } - }); + result = ContainerUtil.getOrCreate(myAlreadyCalculatedMap, list.getNumber(), + (Factory)() -> checkAlive(list, branchPath)); } return result; } @@ -327,29 +322,20 @@ public class BranchInfo { final boolean self) throws SvnBindException { SvnMergeInfoCache.MergeCheckResult result; Map mergedPathsMap = parseMergeInfo(value); - String mergedPathAffectingTrunkUrl = ContainerUtil.find(mergedPathsMap.keySet(), new Condition() { - @Override - public boolean value(String path) { - return trunkRelativeUrl.startsWith(path); - } - }); + String mergedPathAffectingTrunkUrl = ContainerUtil.find(mergedPathsMap.keySet(), path -> trunkRelativeUrl.startsWith(path)); if (mergedPathAffectingTrunkUrl != null) { SVNMergeRangeList mergeRangeList = mergedPathsMap.get(mergedPathAffectingTrunkUrl); fillMergedRevisions(pathWithRevisionNumber, mergeRangeList); - boolean isAskedRevisionMerged = ContainerUtil.or(mergeRangeList.getRanges(), new Condition() { - @Override - public boolean value(@NotNull SVNMergeRange range) { - return isInRange(range, revisionAsked) && (range.isInheritable() || self); - } - }); + boolean isAskedRevisionMerged = + ContainerUtil.or(mergeRangeList.getRanges(), range -> isInRange(range, revisionAsked) && (range.isInheritable() || self)); result = SvnMergeInfoCache.MergeCheckResult.getInstance(isAskedRevisionMerged); } else { - myPathMergedMap.put(pathWithRevisionNumber, Collections.emptySet()); + myPathMergedMap.put(pathWithRevisionNumber, Collections.emptySet()); result = SvnMergeInfoCache.MergeCheckResult.NOT_MERGED; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/MergeInfoHolder.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/MergeInfoHolder.java index a69c15be2893..b8b0d0ec0242 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/MergeInfoHolder.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/mergeinfo/MergeInfoHolder.java @@ -121,26 +121,22 @@ public class MergeInfoHolder { myMergeInfoCache.getState(myRefreshedRoot, (SvnChangeList)list, myRefreshedBranch, myBranchPath); // todo make batches - by 10 final long number = list.getNumber(); - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - final MergeInfoCached cachedState = myCachedMap.get(createKey(myRefreshedRoot, myRefreshedBranch)); - if (cachedState != null) { - cachedState.getMap().put(number, checkState); - } - myManager.repaintTree(); + ApplicationManager.getApplication().invokeLater(() -> { + final MergeInfoCached cachedState = myCachedMap.get(createKey(myRefreshedRoot, myRefreshedBranch)); + if (cachedState != null) { + cachedState.getMap().put(number, checkState); } + myManager.repaintTree(); }); } return true; } public void onAfterEndReport() { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - myCachedMap.remove(createKey(myRefreshedRoot, myRefreshedBranch)); - updateMixedRevisionsForPanel(); - myManager.repaintTree(); - } + ApplicationManager.getApplication().invokeLater(() -> { + myCachedMap.remove(createKey(myRefreshedRoot, myRefreshedBranch)); + updateMixedRevisionsForPanel(); + myManager.repaintTree(); }); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/properties/SvnKitPropertyClient.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/properties/SvnKitPropertyClient.java index 23fedd3c7ac8..e064ea7fbb95 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/properties/SvnKitPropertyClient.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/properties/SvnKitPropertyClient.java @@ -97,12 +97,7 @@ public class SvnKitPropertyClient extends BaseSvnClient implements PropertyClien public void setProperties(@NotNull File file, @NotNull PropertiesMap properties) throws VcsException { final SVNProperties propertiesToSet = toSvnProperties(properties); try { - createClient().doSetProperty(file, new ISVNPropertyValueProvider() { - @Override - public SVNProperties providePropertyValues(File path, SVNProperties properties) throws SVNException { - return propertiesToSet; - } - }, true, SVNDepth.EMPTY, null, null); + createClient().doSetProperty(file, (path, properties1) -> propertiesToSet, true, SVNDepth.EMPTY, null, null); } catch (SVNException e) { throw new SvnBindException(e); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/ChangesAfterPathComparator.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/ChangesAfterPathComparator.java index a0249595e788..866bcf774e0e 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/ChangesAfterPathComparator.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/ChangesAfterPathComparator.java @@ -19,7 +19,6 @@ import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ContentRevision; -import org.jetbrains.annotations.NotNull; import java.util.Comparator; @@ -31,12 +30,8 @@ import java.util.Comparator; */ public class ChangesAfterPathComparator implements Comparator { private final static ChangesAfterPathComparator ourInstance = new ChangesAfterPathComparator(); - private final static Comparator ourComparator = new Comparator() { - @Override - public int compare(@NotNull ContentRevision o1, @NotNull ContentRevision o2) { - return FileUtil.compareFiles(o1.getFile().getIOFile(), o2.getFile().getIOFile()); - } - }; + private final static Comparator ourComparator = + (o1, o2) -> FileUtil.compareFiles(o1.getFile().getIOFile(), o2.getFile().getIOFile()); public static ChangesAfterPathComparator getInstance() { return ourInstance; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/Reverter.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/Reverter.java index fde3a9dbbf9c..eb5b5b48a449 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/Reverter.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/Reverter.java @@ -18,7 +18,6 @@ package org.jetbrains.idea.svn.rollback; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.rollback.RollbackProgressListener; -import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; @@ -39,7 +38,10 @@ import org.tmatesoft.svn.core.wc2.SvnTarget; import java.io.File; import java.io.IOException; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; /** * @author Konstantin Kolosovsky. @@ -109,12 +111,7 @@ public class Reverter { } public void moveGroup() { - Collections.sort(myFromToModified, new Comparator() { - @Override - public int compare(CopiedAsideInfo o1, CopiedAsideInfo o2) { - return FileUtil.compareFiles(o1.getTo(), o2.getTo()); - } - }); + Collections.sort(myFromToModified, (o1, o2) -> FileUtil.compareFiles(o1.getTo(), o2.getTo())); for (CopiedAsideInfo info : myFromToModified) { if (info.getParentImmediateReverted().exists()) { // parent successfully renamed/moved @@ -135,26 +132,23 @@ public class Reverter { } } else { - FileUtil.processFilesRecursively(root, new Processor() { - @Override - public boolean process(File file) { - if (file.isDirectory()) return true; - String relativePath = FileUtil.getRelativePath(root.getPath(), file.getPath(), File.separatorChar); - File newFile = new File(target, relativePath); - newFile.getParentFile().mkdirs(); - try { - if (target.exists()) { - FileUtil.copy(file, newFile); - } - else { - FileUtil.rename(file, newFile); - } + FileUtil.processFilesRecursively(root, file -> { + if (file.isDirectory()) return true; + String relativePath = FileUtil.getRelativePath(root.getPath(), file.getPath(), File.separatorChar); + File newFile = new File(target, relativePath); + newFile.getParentFile().mkdirs(); + try { + if (target.exists()) { + FileUtil.copy(file, newFile); } - catch (IOException e) { - myExceptions.add(new VcsException(e)); + else { + FileUtil.rename(file, newFile); } - return true; } + catch (IOException e) { + myExceptions.add(new VcsException(e)); + } + return true; }); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/SuperfluousRemover.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/SuperfluousRemover.java index cb0230630f1f..b2d96e0cfe67 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/SuperfluousRemover.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/rollback/SuperfluousRemover.java @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.svn.rollback; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vfs.VfsUtilCore; @@ -52,20 +51,11 @@ public class SuperfluousRemover { } public void check(@NotNull final File file) { - boolean parentAlreadyRegistered = ContainerUtil.or(myParentPaths, new Condition() { - @Override - public boolean value(@NotNull File parentCandidate) { - return VfsUtilCore.isAncestor(parentCandidate, file, true); - } - }); + boolean parentAlreadyRegistered = + ContainerUtil.or(myParentPaths, parentCandidate -> VfsUtilCore.isAncestor(parentCandidate, file, true)); if (!parentAlreadyRegistered) { - ContainerUtil.retainAll(myParentPaths, new Condition() { - @Override - public boolean value(@NotNull File childCandidate) { - return !VfsUtilCore.isAncestor(file, childCandidate, true); - } - }); + ContainerUtil.retainAll(myParentPaths, childCandidate -> !VfsUtilCore.isAncestor(file, childCandidate, true)); myParentPaths.add(file); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/statistics/SvnWorkingCopyFormatUsagesCollector.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/statistics/SvnWorkingCopyFormatUsagesCollector.java index 9dc7f3df16da..72dc4938b128 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/statistics/SvnWorkingCopyFormatUsagesCollector.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/statistics/SvnWorkingCopyFormatUsagesCollector.java @@ -19,8 +19,6 @@ import com.intellij.internal.statistic.AbstractApplicationUsagesCollector; import com.intellij.internal.statistic.beans.GroupDescriptor; import com.intellij.internal.statistic.beans.UsageDescriptor; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Condition; -import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.svn.NestedCopyType; @@ -48,18 +46,9 @@ public class SvnWorkingCopyFormatUsagesCollector extends AbstractApplicationUsag // do not track roots with errors (SvnFileUrlMapping.getErrorRoots()) as they are "not usable" until errors are resolved // skip externals and switched directories as they will have the same format - List roots = ContainerUtil.filter(vcs.getSvnFileUrlMapping().getAllWcInfos(), new Condition() { - @Override - public boolean value(RootUrlInfo info) { - return info.getType() == null || NestedCopyType.inner.equals(info.getType()); - } - }); + List roots = ContainerUtil + .filter(vcs.getSvnFileUrlMapping().getAllWcInfos(), info -> info.getType() == null || NestedCopyType.inner.equals(info.getType())); - return ContainerUtil.map2Set(roots, new Function() { - @Override - public UsageDescriptor fun(RootUrlInfo info) { - return new UsageDescriptor(info.getFormat().toString(), 1); - } - }); + return ContainerUtil.map2Set(roots, info -> new UsageDescriptor(info.getFormat().toString(), 1)); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/CmdStatusClient.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/CmdStatusClient.java index 6c8e8e0199d6..75e349bdb341 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/CmdStatusClient.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/CmdStatusClient.java @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.svn.status; -import com.intellij.openapi.util.Getter; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; @@ -104,12 +103,7 @@ public class CmdStatusClient extends BaseSvnClient implements StatusClient { status.setFile(path); status.setPath(path.getAbsolutePath()); status.setContentsStatus(StatusType.STATUS_NORMAL); - status.setInfoGetter(new Getter() { - @Override - public Info get() { - return createInfoGetter(null).convert(path); - } - }); + status.setInfoGetter(() -> createInfoGetter(null).convert(path)); try { handler.consume(status); } @@ -160,15 +154,12 @@ public class CmdStatusClient extends BaseSvnClient implements StatusClient { } private Convertor createInfoGetter(final SVNRevision revision) { - return new Convertor() { - @Override - public Info convert(File o) { - try { - return myFactory.createInfoClient().doInfo(o, revision); - } - catch (SvnBindException e) { - throw new SvnExceptionWrapper(e); - } + return o -> { + try { + return myFactory.createInfoClient().doInfo(o, revision); + } + catch (SvnBindException e) { + throw new SvnExceptionWrapper(e); } }; } @@ -232,12 +223,7 @@ public class CmdStatusClient extends BaseSvnClient implements StatusClient { @Override public Status doStatus(@NotNull File path, boolean remote) throws SvnBindException { final Status[] svnStatus = new Status[1]; - doStatus(path, SVNRevision.UNDEFINED, Depth.EMPTY, remote, false, false, false, new StatusConsumer() { - @Override - public void consume(Status status) throws SVNException { - svnStatus[0] = status; - } - }, null); + doStatus(path, SVNRevision.UNDEFINED, Depth.EMPTY, remote, false, false, false, status -> svnStatus[0] = status, null); return svnStatus[0]; } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/PortableStatus.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/PortableStatus.java index d0285b2bc643..f3e83590789c 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/PortableStatus.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/PortableStatus.java @@ -108,21 +108,11 @@ public class PortableStatus extends Status { remotePropertiesStatus, isLocked, isCopied, isSwitched, null, remoteLock, localLock, changelistName, null); myConflicted = isConflicted; - myInfoGetter = infoGetter == null ? new Getter() { - @Override - public Info get() { - return null; - } - } : infoGetter; + myInfoGetter = infoGetter == null ? () -> null : infoGetter; } public PortableStatus() { - myInfoGetter = new Getter() { - @Override - public Info get() { - return null; - } - }; + myInfoGetter = () -> null; setCommittedRevision(SVNRevision.UNDEFINED); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/Status.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/Status.java index a6ab12b6ac07..260600853513 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/Status.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/Status.java @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.svn.status; -import com.intellij.openapi.util.Condition; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -167,12 +166,7 @@ public class Status { } public boolean is(@NotNull StatusType... types) { - return ContainerUtil.or(types, new Condition() { - @Override - public boolean value(StatusType type) { - return is(type); - } - }); + return ContainerUtil.or(types, type -> is(type)); } public boolean isProperty(@NotNull StatusType type) { @@ -180,12 +174,7 @@ public class Status { } public boolean isProperty(@NotNull StatusType... types) { - return ContainerUtil.or(types, new Condition() { - @Override - public boolean value(StatusType type) { - return isProperty(type); - } - }); + return ContainerUtil.or(types, type -> isProperty(type)); } public boolean isLocked() { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/SvnKitStatusClient.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/SvnKitStatusClient.java index 955c1456722b..d696aea8d32a 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/SvnKitStatusClient.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/SvnKitStatusClient.java @@ -22,7 +22,9 @@ import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.api.ProgressTracker; import org.jetbrains.idea.svn.commandLine.SvnBindException; import org.tmatesoft.svn.core.SVNException; -import org.tmatesoft.svn.core.wc.*; +import org.tmatesoft.svn.core.wc.ISVNStatusFileProvider; +import org.tmatesoft.svn.core.wc.SVNRevision; +import org.tmatesoft.svn.core.wc.SVNStatusClient; import java.io.File; import java.util.Collection; @@ -59,13 +61,8 @@ public class SvnKitStatusClient extends BaseSvnClient implements StatusClient { @NotNull final StatusConsumer handler, @Nullable Collection changeLists) throws SvnBindException { try { - return getStatusClient() - .doStatus(path, revision, toDepth(depth), remote, reportAll, includeIgnored, collectParentExternals, new ISVNStatusHandler() { - @Override - public void handleStatus(SVNStatus status) throws SVNException { - handler.consume(Status.create(status)); - } - }, changeLists); + return getStatusClient().doStatus(path, revision, toDepth(depth), remote, reportAll, includeIgnored, collectParentExternals, + status -> handler.consume(Status.create(status)), changeLists); } catch (SVNException e) { throw new SvnBindException(e); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/SvnStatusHandler.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/SvnStatusHandler.java index 3fbd18d3c2b0..655b7c83c34c 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/status/SvnStatusHandler.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/status/SvnStatusHandler.java @@ -89,7 +89,8 @@ public class SvnStatusHandler extends DefaultHandler { public void endLock() { if (myInRemoteStatus) { myPending.setRemoteLock(myLockBuilder.build()); - } else { + } + else { myPending.setLocalLock(myLockBuilder.build()); } myLockBuilder = null; @@ -117,7 +118,8 @@ public class SvnStatusHandler extends DefaultHandler { dataCallback.switchChangeList(newList); } }; - } else { + } + else { myDataCallback = new DataCallback() { @Override public void startLock() { @@ -128,7 +130,8 @@ public class SvnStatusHandler extends DefaultHandler { public void endLock() { if (myInRemoteStatus) { myPending.setRemoteLock(myLockBuilder.build()); - } else { + } + else { myPending.setLocalLock(myLockBuilder.build()); } myLockBuilder = null; @@ -149,7 +152,8 @@ public class SvnStatusHandler extends DefaultHandler { myAnythingReported = true; if (myChangelistName == null) { myDefaultListStatuses.add(myPending); - } else { + } + else { myCurrentListChanges.putValue(myChangelistName, myPending); } newPending(infoGetter); @@ -172,12 +176,7 @@ public class SvnStatusHandler extends DefaultHandler { private void newPending(final Convertor infoGetter) { final PortableStatus status = new PortableStatus(); myPending = status; - status.setInfoGetter(new Getter() { - @Override - public Info get() { - return infoGetter.convert(status.getFile()); - } - }); + status.setInfoGetter(() -> infoGetter.convert(status.getFile())); } public PortableStatus getPending() { @@ -193,98 +192,23 @@ public class SvnStatusHandler extends DefaultHandler { } private void fillElements() { - myElementsMap.put("repos-status", new Getter() { - @Override - public ElementHandlerBase get() { - return new ReposStatus(); - } - }); - myElementsMap.put("lock", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockElement(); - } - }); + myElementsMap.put("repos-status", () -> new ReposStatus()); + myElementsMap.put("lock", () -> new LockElement()); - myElementsMap.put("token", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockToken(); - } - }); - myElementsMap.put("owner", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockOwner(); - } - }); - myElementsMap.put("comment", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockComment(); - } - }); - myElementsMap.put("created", new Getter() { - @Override - public ElementHandlerBase get() { - return new LockCreatedDate(); - } - }); -// -- - myElementsMap.put("status", new Getter() { - @Override - public ElementHandlerBase get() { - return new Status(); - } - }); - myElementsMap.put("author", new Getter() { - @Override - public ElementHandlerBase get() { - return new Author(); - } - }); - myElementsMap.put("changelist", new Getter() { - @Override - public ElementHandlerBase get() { - return new Changelist(); - } - }); - myElementsMap.put("commit", new Getter() { - @Override - public ElementHandlerBase get() { - return new Commit(); - } - }); - myElementsMap.put("date", new Getter() { - @Override - public ElementHandlerBase get() { - return new Date(); - } - }); - myElementsMap.put("entry", new Getter() { - @Override - public ElementHandlerBase get() { - return new Entry(myBase); - } - }); - myElementsMap.put("target", new Getter() { - @Override - public ElementHandlerBase get() { - return new Target(); - } - }); - myElementsMap.put("against", new Getter() { - @Override - public ElementHandlerBase get() { - return new Against(); - } - }); - myElementsMap.put("wc-status", new Getter() { - @Override - public ElementHandlerBase get() { - return new WcStatus(); - } - }); + myElementsMap.put("token", () -> new LockToken()); + myElementsMap.put("owner", () -> new LockOwner()); + myElementsMap.put("comment", () -> new LockComment()); + myElementsMap.put("created", () -> new LockCreatedDate()); + // -- + myElementsMap.put("status", () -> new Status()); + myElementsMap.put("author", () -> new Author()); + myElementsMap.put("changelist", () -> new Changelist()); + myElementsMap.put("commit", () -> new Commit()); + myElementsMap.put("date", () -> new Date()); + myElementsMap.put("entry", () -> new Entry(myBase)); + myElementsMap.put("target", () -> new Target()); + myElementsMap.put("against", () -> new Against()); + myElementsMap.put("wc-status", () -> new WcStatus()); } @Override @@ -294,7 +218,7 @@ public class SvnStatusHandler extends DefaultHandler { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - assertSAX(! myParseStack.isEmpty()); + assertSAX(!myParseStack.isEmpty()); ElementHandlerBase current = myParseStack.get(myParseStack.size() - 1); if (mySb.length() > 0) { current.characters(mySb.toString().trim(), myPending, myLockBuilder); @@ -311,11 +235,12 @@ public class SvnStatusHandler extends DefaultHandler { newChild.preEffect(myDataCallback); myParseStack.add(newChild); return; - } else { + } + else { // go up current.postEffect(myDataCallback); myParseStack.remove(myParseStack.size() - 1); - assertSAX(! myParseStack.isEmpty()); + assertSAX(!myParseStack.isEmpty()); current = myParseStack.get(myParseStack.size() - 1); } } @@ -323,14 +248,14 @@ public class SvnStatusHandler extends DefaultHandler { @Override public void characters(char[] ch, int start, int length) throws SAXException { - assertSAX(! myParseStack.isEmpty()); + assertSAX(!myParseStack.isEmpty()); mySb.append(ch, start, length); } @Override public void endDocument() throws SAXException { - assertSAX(! myParseStack.isEmpty()); - for (int i = myParseStack.size() - 1; i >= 0; -- i) { + assertSAX(!myParseStack.isEmpty()); + for (int i = myParseStack.size() - 1; i >= 0; --i) { ElementHandlerBase current = myParseStack.get(i); current.postEffect(myDataCallback); } @@ -338,7 +263,7 @@ public class SvnStatusHandler extends DefaultHandler { } private static void assertSAX(final boolean shouldBeTrue) throws SAXException { - if (! shouldBeTrue) { + if (!shouldBeTrue) { throw new SAXException("can not parse output"); } } @@ -680,11 +605,12 @@ public class SvnStatusHandler extends DefaultHandler { } final String revision = attributes.getValue("revision"); - if (! StringUtil.isEmptyOrSpaces(revision)) { + if (!StringUtil.isEmptyOrSpaces(revision)) { try { final long number = Long.parseLong(revision); status.setRevision(SVNRevision.create(number)); - } catch (NumberFormatException e) { + } + catch (NumberFormatException e) { throw new SAXException(e); } } @@ -720,7 +646,8 @@ public class SvnStatusHandler extends DefaultHandler { final boolean exists = file.exists(); if (exists) { status.setKind(exists, NodeKind.from(file.isDirectory())); - } else { + } + else { // this is a hack. This is done so because of strange svn native client output: /* c:\TestProjects\sortedProjects\Subversion\local\withExt82420\mod4>svn st --xml @@ -755,8 +682,8 @@ and no "mod4" under */ final StatusType ns = status.getNodeStatus(); - if (myBase.getName().equals(path) && ! StatusType.MISSING.equals(ns) && - ! StatusType.STATUS_DELETED.equals(ns) ) { + if (myBase.getName().equals(path) && !StatusType.MISSING.equals(ns) && + !StatusType.STATUS_DELETED.equals(ns)) { status.setKind(true, NodeKind.DIR); status.setFile(myBase); status.setPath(""); @@ -783,7 +710,7 @@ and no "mod4" under private static class Changelist extends ElementHandlerBase { private String myName; - + private Changelist() { super(new String[]{}, new String[]{"entry"}); } @@ -791,7 +718,7 @@ and no "mod4" under @Override protected void updateStatus(Attributes attributes, PortableStatus status, Lock.Builder lock) throws SAXException { final String name = attributes.getValue("name"); - assertSAX(! StringUtil.isEmptyOrSpaces(name)); + assertSAX(!StringUtil.isEmptyOrSpaces(name)); myName = name; } @@ -885,7 +812,9 @@ and no "mod4" under } protected abstract void updateStatus(Attributes attributes, PortableStatus status, Lock.Builder lock) throws SAXException; + public abstract void postEffect(final DataCallback callback); + public abstract void preEffect(final DataCallback callback); public boolean startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { @@ -902,15 +831,21 @@ and no "mod4" under public interface ExternalDataCallback { void switchPath(); + void switchChangeList(final String newList); } private interface DataCallback extends ExternalDataCallback { void startRemoteStatus(); + void endRemoteStatus(); + void startLock(); + void endLock(); + void switchPath(); + void switchChangeList(final String newList); } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/ApplicationLevelNumberConnectionsGuardImpl.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/ApplicationLevelNumberConnectionsGuardImpl.java index c1338d33d491..a1b4e47a4032 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/ApplicationLevelNumberConnectionsGuardImpl.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/ApplicationLevelNumberConnectionsGuardImpl.java @@ -59,16 +59,13 @@ public class ApplicationLevelNumberConnectionsGuardImpl implements Disposable, A myService = Executors.newSingleThreadScheduledExecutor(ConcurrencyUtil.newNamedThreadFactory("SVN connection")); myLock = new Object(); myDisposed = false; - myRecheck = new Runnable() { - @Override - public void run() { - HashSet pools = new HashSet<>(); - synchronized (myLock) { - pools.addAll(mySet); - } - for (CachingSvnRepositoryPool pool : pools) { - pool.check(); - } + myRecheck = () -> { + HashSet pools = new HashSet<>(); + synchronized (myLock) { + pools.addAll(mySet); + } + for (CachingSvnRepositoryPool pool : pools) { + pool.check(); } }; myCurrentlyActiveConnections = 0; diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/CachingSvnRepositoryPool.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/CachingSvnRepositoryPool.java index 3be33e83eeb3..c1d4ff04dbeb 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/CachingSvnRepositoryPool.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/svnkit/lowLevel/CachingSvnRepositoryPool.java @@ -197,12 +197,9 @@ public class CachingSvnRepositoryPool implements SvnRepositoryPool { myWait.notifyAll(); myGuard.connectionDestroyed(listForClose.size()); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - for (SVNRepository repository : listForClose) { - repository.closeSession(); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + for (SVNRepository repository : listForClose) { + repository.closeSession(); } }); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/SvnTreeConflictResolver.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/SvnTreeConflictResolver.java index 8f1f4b14c42e..c767690ed6bd 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/SvnTreeConflictResolver.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/SvnTreeConflictResolver.java @@ -30,9 +30,7 @@ import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.commandLine.SvnBindException; import org.jetbrains.idea.svn.status.Status; import org.jetbrains.idea.svn.status.StatusClient; -import org.jetbrains.idea.svn.status.StatusConsumer; import org.jetbrains.idea.svn.status.StatusType; -import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.SVNRevision; import java.io.File; @@ -120,7 +118,7 @@ public class SvnTreeConflictResolver { updateFile(ioFile, SVNRevision.HEAD); FileUtil.delete(ioFile); } else { - Set usedToBeAdded = myPath.isDirectory() ? getDescendantsWithAddedStatus(ioFile) : ContainerUtil.newHashSet(); + Set usedToBeAdded = myPath.isDirectory() ? getDescendantsWithAddedStatus(ioFile) : ContainerUtil.newHashSet(); revert(ioFile); for (File wasAdded : usedToBeAdded) { @@ -135,15 +133,11 @@ public class SvnTreeConflictResolver { final Set result = ContainerUtil.newHashSet(); StatusClient statusClient = myVcs.getFactory(ioFile).createStatusClient(); - statusClient.doStatus(ioFile, SVNRevision.UNDEFINED, Depth.INFINITY, false, false, false, false, - new StatusConsumer() { - @Override - public void consume(Status status) throws SVNException { - if (status != null && StatusType.STATUS_ADDED.equals(status.getNodeStatus())) { - result.add(status.getFile()); - } - } - }, null); + statusClient.doStatus(ioFile, SVNRevision.UNDEFINED, Depth.INFINITY, false, false, false, false, status -> { + if (status != null && StatusType.STATUS_ADDED.equals(status.getNodeStatus())) { + result.add(status.getFile()); + } + }, null); return result; } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/TreeConflictRefreshablePanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/TreeConflictRefreshablePanel.java index c8422792cb50..f6a37e34f64d 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/TreeConflictRefreshablePanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/TreeConflictRefreshablePanel.java @@ -88,7 +88,7 @@ public class TreeConflictRefreshablePanel implements Disposable { Change change) { myVcs = SvnVcs.getInstance(project); assert change instanceof ConflictedSvnChange; - myChange = (ConflictedSvnChange) change; + myChange = (ConflictedSvnChange)change; myPath = ChangesUtil.getFilePath(myChange); myRightRevisionsList = new TLongArrayList(); @@ -102,23 +102,23 @@ public class TreeConflictRefreshablePanel implements Disposable { if (d1.isTextConflict() != d2.isTextConflict()) return false; if (d1.isTreeConflict() != d2.isTreeConflict()) return false; - if (! d1.getOperation().equals(d2.getOperation())) return false; - if (! d1.getConflictAction().equals(d2.getConflictAction())) return false; - if (! Comparing.equal(d1.getConflictReason(), d2.getConflictReason())) return false; - if (! Comparing.equal(d1.getPath(), d2.getPath())) return false; - if (! Comparing.equal(d1.getNodeKind(), d2.getNodeKind())) return false; - if (! compareConflictVersion(d1.getSourceLeftVersion(), d2.getSourceLeftVersion())) return false; - if (! compareConflictVersion(d1.getSourceRightVersion(), d2.getSourceRightVersion())) return false; + if (!d1.getOperation().equals(d2.getOperation())) return false; + if (!d1.getConflictAction().equals(d2.getConflictAction())) return false; + if (!Comparing.equal(d1.getConflictReason(), d2.getConflictReason())) return false; + if (!Comparing.equal(d1.getPath(), d2.getPath())) return false; + if (!Comparing.equal(d1.getNodeKind(), d2.getNodeKind())) return false; + if (!compareConflictVersion(d1.getSourceLeftVersion(), d2.getSourceLeftVersion())) return false; + if (!compareConflictVersion(d1.getSourceRightVersion(), d2.getSourceRightVersion())) return false; return true; } private static boolean compareConflictVersion(ConflictVersion v1, ConflictVersion v2) { if (v1 == null && v2 == null) return true; if (v1 == null || v2 == null) return false; - if (! v1.getKind().equals(v2.getKind())) return false; - if (! v1.getPath().equals(v2.getPath())) return false; + if (!v1.getKind().equals(v2.getKind())) return false; + if (!v1.getPath().equals(v2.getPath())) return false; if (v1.getPegRevision() != v2.getPegRevision()) return false; - if (! Comparing.equal(v1.getRepositoryRoot(), v2.getRepositoryRoot())) return false; + if (!Comparing.equal(v1.getRepositoryRoot(), v2.getRepositoryRoot())) return false; return true; } @@ -174,7 +174,7 @@ public class TreeConflictRefreshablePanel implements Disposable { private static boolean isDifferentURLs(TreeConflictDescription description) { return description.getSourceLeftVersion() != null && description.getSourceRightVersion() != null && - ! Comparing.equal(description.getSourceLeftVersion().getPath(), description.getSourceRightVersion().getPath()); + !Comparing.equal(description.getSourceLeftVersion().getPath(), description.getSourceRightVersion().getPath()); } @NotNull @@ -224,7 +224,7 @@ public class TreeConflictRefreshablePanel implements Disposable { name.setFont(name.getFont().deriveFont(Font.BOLD)); gb.insets.top = 5; main.add(name, gb); - ++ gb.gridy; + ++gb.gridy; gb.insets.top = 10; appendDescription(myChange.getBeforeDescription(), main, gb, data.getBefore(), myPath.isDirectory()); appendDescription(myChange.getAfterDescription(), main, gb, data.getAfter(), myPath.isDirectory()); @@ -240,7 +240,7 @@ public class TreeConflictRefreshablePanel implements Disposable { JLabel descriptionLbl = new JLabel(description.toPresentableString()); descriptionLbl.setForeground(JBColor.RED); main.add(descriptionLbl, gb); - ++ gb.gridy; + ++gb.gridy; //buttons gb.insets.top = 0; addResolveButtons(description, main, gb); @@ -269,7 +269,7 @@ public class TreeConflictRefreshablePanel implements Disposable { gb.insets.left = -4; main.add(wrapper, gb); gb.insets.left = 1; - ++ gb.gridy; + ++gb.gridy; } private ActionListener createRight(final TreeConflictDescription description) { @@ -295,7 +295,8 @@ public class TreeConflictRefreshablePanel implements Disposable { public void onSuccess() { super.onSuccess(); if (executedOk()) { - VcsBalloonProblemNotifier.showOverChangesView(myProject, "Theirs accepted for " + filePath(paths.myMainPath), MessageType.INFO); + VcsBalloonProblemNotifier + .showOverChangesView(myProject, "Theirs accepted for " + filePath(paths.myMainPath), MessageType.INFO); } } }); @@ -310,11 +311,13 @@ public class TreeConflictRefreshablePanel implements Disposable { if (ConflictAction.ADD.equals(description.getConflictAction())) { mainPath = myChange.getAfterRevision().getFile(); additionalPath = myChange.getBeforeRevision().getFile(); - } else { + } + else { mainPath = myChange.getBeforeRevision().getFile(); additionalPath = myChange.getAfterRevision().getFile(); } - } else { + } + else { mainPath = myChange.getBeforeRevision() != null ? myChange.getBeforeRevision().getFile() : myChange.getAfterRevision().getFile(); } return new Paths(mainPath, additionalPath); @@ -353,7 +356,8 @@ public class TreeConflictRefreshablePanel implements Disposable { public void onSuccess() { super.onSuccess(); if (executedOk()) { - VcsBalloonProblemNotifier.showOverChangesView(myProject, "Yours accepted for " + filePath(paths.myMainPath), MessageType.INFO); + VcsBalloonProblemNotifier + .showOverChangesView(myProject, "Yours accepted for " + filePath(paths.myMainPath), MessageType.INFO); } } }); @@ -377,12 +381,7 @@ public class TreeConflictRefreshablePanel implements Disposable { } private ActionListener createMergeTheirsForFile(final TreeConflictDescription description) { - return new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - new MergeFromTheirsResolver(myVcs, description, myChange, myCommittedRevision).execute(); - } - }; + return e -> new MergeFromTheirsResolver(myVcs, description, myChange, myCommittedRevision).execute(); } @NotNull @@ -408,11 +407,11 @@ public class TreeConflictRefreshablePanel implements Disposable { ConflictSidePresentation before, ConflictVersion leftVersion, final String name, boolean directory) { final String leftPresentation = leftVersion == null ? name + ": (" + (directory ? "directory" : "file") + - (myChange.getBeforeRevision() == null ? ") added" : ") unversioned") : + (myChange.getBeforeRevision() == null ? ") added" : ") unversioned") : name + ": " + FileUtil.toSystemIndependentName(ConflictVersion.toPresentableString(leftVersion)); gb.insets.top = 10; main.add(new JLabel(leftPresentation), gb); - ++ gb.gridy; + ++gb.gridy; gb.insets.top = 0; if (before != null) { @@ -421,7 +420,7 @@ public class TreeConflictRefreshablePanel implements Disposable { //gb.fill = GridBagConstraints.HORIZONTAL; main.add(panel, gb); //gb.fill = GridBagConstraints.NONE; - ++ gb.gridy; + ++gb.gridy; } } } @@ -495,7 +494,7 @@ public class TreeConflictRefreshablePanel implements Disposable { mySessionAdapter = new VcsAppendableHistoryPartnerAdapter(); /*mySessionAdapter.reportCreatedEmptySession(new SvnHistorySession(myVcs, Collections.emptyList(), myPath, SvnUtil.checkRepositoryVersion15(myVcs, version.getPath()), null, true));*/ - myProvider = (SvnHistoryProvider) myVcs.getVcsHistoryProvider(); + myProvider = (SvnHistoryProvider)myVcs.getVcsHistoryProvider(); } public void setListToReportLoaded(TLongArrayList listToReportLoaded) { @@ -515,7 +514,7 @@ public class TreeConflictRefreshablePanel implements Disposable { if (myListToReportLoaded != null && session != null) { List list = session.getRevisionList(); for (VcsFileRevision revision : list) { - myListToReportLoaded.add(((SvnRevisionNumber) revision.getRevisionNumber()).getRevision().getNumber()); + myListToReportLoaded.add(((SvnRevisionNumber)revision.getRevisionNumber()).getRevision().getNumber()); } } } @@ -536,9 +535,9 @@ public class TreeConflictRefreshablePanel implements Disposable { return EmptyConflictSide.getInstance().createPanel(); } VcsFileRevision last = null; - if (! list.isEmpty() && myPeg == null && list.size() == LIMIT || + if (!list.isEmpty() && myPeg == null && list.size() == LIMIT || myPeg != null && myPeg.getNumber() > 0 && - myPeg.equals(((SvnRevisionNumber) list.get(list.size() - 1).getRevisionNumber()).getRevision())) { + myPeg.equals(((SvnRevisionNumber)list.get(list.size() - 1).getRevisionNumber()).getRevision())) { last = list.remove(list.size() - 1); } myFileHistoryPanel = new FileHistoryPanelImpl(myVcs, myPath, session, myProvider, null, new FileHistoryRefresherI() { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/AbstractSvnUpdateIntegrateEnvironment.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/AbstractSvnUpdateIntegrateEnvironment.java index 60da28927a11..bb170715c095 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/AbstractSvnUpdateIntegrateEnvironment.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/AbstractSvnUpdateIntegrateEnvironment.java @@ -80,12 +80,8 @@ public abstract class AbstractSvnUpdateIntegrateEnvironment implements UpdateEnv AbstractUpdateIntegrateCrawler crawler = createCrawler(eventHandler, totalUpdate, exceptions, updatedFiles); Collection updatedRoots = new HashSet<>(); - Arrays.sort(contentRoots, new Comparator() { - public int compare(FilePath o1, FilePath o2) { - return SystemInfo.isFileSystemCaseSensitive ? o1.getPath().replace("/", "\\").compareTo(o2.getPath().replace("/", "\\")) : - o1.getPath().replace("/", "\\").compareToIgnoreCase(o2.getPath().replace("/", "\\")); - } - }); + Arrays.sort(contentRoots, (o1, o2) -> SystemInfo.isFileSystemCaseSensitive ? o1.getPath().replace("/", "\\") + .compareTo(o2.getPath().replace("/", "\\")) : o1.getPath().replace("/", "\\").compareToIgnoreCase(o2.getPath().replace("/", "\\"))); for (FilePath contentRoot : contentRoots) { if (progressIndicator != null) { progressIndicator.checkCanceled(); @@ -96,13 +92,10 @@ public abstract class AbstractSvnUpdateIntegrateEnvironment implements UpdateEnv updatedRoots.addAll(SvnUtil.crawlWCRoots(myVcs, ioRoot, crawler, progressIndicator)); } if (updatedRoots.isEmpty()) { - WaitForProgressToShow.runOrInvokeLaterAboveProgress(new Runnable() { - public void run() { - Messages.showErrorDialog(myVcs.getProject(), SvnBundle.message("message.text.update.no.directories.found"), - SvnBundle.message("messate.text.update.error")); - } - }, null, myVcs.getProject()); - return new UpdateSessionAdapter(Collections.emptyList(), true); + WaitForProgressToShow.runOrInvokeLaterAboveProgress(() -> Messages + .showErrorDialog(myVcs.getProject(), SvnBundle.message("message.text.update.no.directories.found"), + SvnBundle.message("messate.text.update.error")), null, myVcs.getProject()); + return new UpdateSessionAdapter(Collections.emptyList(), true); } return new MyUpdateSessionAdapter(contentRoots, updatedFiles, exceptions); @@ -194,11 +187,7 @@ public abstract class AbstractSvnUpdateIntegrateEnvironment implements UpdateEnv } if (! parents.isEmpty()) { - RefreshQueue.getInstance().refresh(true, true, new Runnable() { - public void run() { - myDirtyScopeManager.filesDirty(null, parents); - } - }, parents); + RefreshQueue.getInstance().refresh(true, true, () -> myDirtyScopeManager.filesDirty(null, parents), parents); } } } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/MultipleRootEditorWithSplitter.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/MultipleRootEditorWithSplitter.java index 7107bdef1025..996c08c607b2 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/MultipleRootEditorWithSplitter.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/MultipleRootEditorWithSplitter.java @@ -30,8 +30,6 @@ import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import java.awt.*; import java.io.File; import java.util.Map; @@ -99,14 +97,12 @@ public class MultipleRootEditorWithSplitter extends JPanel { } }); - myList.addListSelectionListener(new ListSelectionListener() { - public void valueChanged(ListSelectionEvent e) { - final FilePath root = ((FilePath)myList.getSelectedValue()); - if (root != null) { - layout.show(myConfigureRootPanel, root.getPath()); - } else { - layout.show(myConfigureRootPanel, EMPTY); - } + myList.addListSelectionListener(e -> { + final FilePath root = ((FilePath)myList.getSelectedValue()); + if (root != null) { + layout.show(myConfigureRootPanel, root.getPath()); + } else { + layout.show(myConfigureRootPanel, EMPTY); } }); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnIntegrateRootOptionsPanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnIntegrateRootOptionsPanel.java index 9294ca0726ed..1c2fb9ba854f 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnIntegrateRootOptionsPanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnIntegrateRootOptionsPanel.java @@ -26,8 +26,6 @@ import org.jetbrains.idea.svn.dialogs.SelectLocationDialog; import org.tmatesoft.svn.core.SVNURL; import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; public class SvnIntegrateRootOptionsPanel implements SvnPanel{ private TextFieldWithBrowseButton myMergeText1; @@ -51,16 +49,8 @@ public class SvnIntegrateRootOptionsPanel implements SvnPanel{ myMergeText2.setEditable(true); - myMergeText1.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - chooseUrl(myMergeText1, vcs); - } - }); - myMergeText2.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - chooseUrl2(vcs); - } - }); + myMergeText1.addActionListener(e -> chooseUrl(myMergeText1, vcs)); + myMergeText2.addActionListener(e -> chooseUrl2(vcs)); myRevision1.setProject(vcs.getProject()); myRevision2.setProject(vcs.getProject()); @@ -68,17 +58,9 @@ public class SvnIntegrateRootOptionsPanel implements SvnPanel{ myRevision1.setRoot(myRoot.getVirtualFile()); myRevision2.setRoot(myRoot.getVirtualFile()); - myRevision1.setUrlProvider(new SvnRevisionPanel.UrlProvider() { - public String getUrl() { - return myMergeText1.getText(); - } - }); + myRevision1.setUrlProvider(() -> myMergeText1.getText()); - myRevision2.setUrlProvider(new SvnRevisionPanel.UrlProvider() { - public String getUrl() { - return myMergeText2.getText(); - } - }); + myRevision2.setUrlProvider(() -> myMergeText2.getText()); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnRevisionPanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnRevisionPanel.java index 897f5b76f72b..4b9dd263616a 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnRevisionPanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnRevisionPanel.java @@ -32,8 +32,6 @@ import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.List; public class SvnRevisionPanel extends JPanel { @@ -50,34 +48,27 @@ public class SvnRevisionPanel extends JPanel { super(new BorderLayout()); add(myPanel); myHead.setSelected(true); - myRevisionField.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - chooseRevision(); - } - }); + myRevisionField.addActionListener(e -> chooseRevision()); // myRevisionField.setEditable(false); myRevisionField.setEnabled(false); - mySpecified.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (mySpecified.isSelected()) { - if (myRevisionField.getText().trim().length() == 0) { - myRevisionField.setText("HEAD"); - } - myRevisionField.setEnabled(true); - } else { - myRevisionField.setEnabled(false); + mySpecified.addActionListener(e -> { + if (mySpecified.isSelected()) { + if (myRevisionField.getText().trim().length() == 0) { + myRevisionField.setText("HEAD"); } - notifyChangeListeners(); + myRevisionField.setEnabled(true); } + else { + myRevisionField.setEnabled(false); + } + notifyChangeListeners(); }); - myHead.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - myRevisionField.setEnabled(false); - notifyChangeListeners(); - } + myHead.addActionListener(e -> { + myRevisionField.setEnabled(false); + notifyChangeListeners(); }); myRevisionField.getTextField().setColumns(10); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdatePanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdatePanel.java index 8090de091214..287f04e19110 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdatePanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdatePanel.java @@ -22,8 +22,6 @@ import org.jetbrains.idea.svn.SvnConfiguration; import org.jetbrains.idea.svn.SvnVcs; import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.Collection; public class SvnUpdatePanel extends AbstractSvnUpdatePanel { @@ -53,25 +51,11 @@ public class SvnUpdatePanel extends AbstractSvnUpdatePanel { SvnConfiguration svnConfiguration = myVCS.getSvnConfiguration(); myLockOnDemand.setSelected(svnConfiguration.isUpdateLockOnDemand()); - myLockOnDemand.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - svnConfiguration.setUpdateLockOnDemand(myLockOnDemand.isSelected()); - } - }); + myLockOnDemand.addActionListener(e -> svnConfiguration.setUpdateLockOnDemand(myLockOnDemand.isSelected())); myForceBox.setSelected(svnConfiguration.isForceUpdate()); myIgnoreExternalsCheckBox.setSelected(svnConfiguration.isIgnoreExternals()); - myForceBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - svnConfiguration.setForceUpdate(myForceBox.isSelected()); - } - }); - myIgnoreExternalsCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - svnConfiguration.setIgnoreExternals(myIgnoreExternalsCheckBox.isSelected()); - } - }); + myForceBox.addActionListener(e -> svnConfiguration.setForceUpdate(myForceBox.isSelected())); + myIgnoreExternalsCheckBox.addActionListener(e -> svnConfiguration.setIgnoreExternals(myIgnoreExternalsCheckBox.isSelected())); } protected JPanel getRootsPanel() { diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdateRootOptionsPanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdateRootOptionsPanel.java index d08ea3f4be35..70e202f205be 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdateRootOptionsPanel.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdateRootOptionsPanel.java @@ -37,8 +37,6 @@ import org.tmatesoft.svn.core.wc.SVNRevision; import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.Collection; public class SvnUpdateRootOptionsPanel implements SvnPanel{ @@ -62,59 +60,46 @@ public class SvnUpdateRootOptionsPanel implements SvnPanel{ myVcs = vcs; myURLText.setEditable(true); - myURLText.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - chooseUrl(); - } - }); + myURLText.addActionListener(e -> chooseUrl()); myBranchField.setEditable(false); - myBranchField.addActionListener(new ActionListener() { - public void actionPerformed(final ActionEvent e) { - chooseBranch(); - } - }); + myBranchField.addActionListener(e -> chooseBranch()); myBranchLabel.setLabelFor(myBranchField); myUrlLabel.setLabelFor(myURLText); - myUpdateToSpecificUrl.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (myUpdateToSpecificUrl.isSelected()) { - myURLText.setEnabled(true); - myBranchField.setEnabled(mySourceUrl != null); - } else { - myURLText.setEnabled(false); - myBranchField.setEnabled(false); - } + myUpdateToSpecificUrl.addActionListener(e -> { + if (myUpdateToSpecificUrl.isSelected()) { + myURLText.setEnabled(true); + myBranchField.setEnabled(mySourceUrl != null); + } + else { + myURLText.setEnabled(false); + myBranchField.setEnabled(false); } }); - myRevisionBox.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (e.getSource() == myRevisionBox) { - myRevisionText.setEnabled(myRevisionBox.isSelected()); - if (myRevisionBox.isSelected()) { - if (myRevisionText.getText().trim().isEmpty()) { - myRevisionText.setText("HEAD"); - } - myRevisionText.getTextField().selectAll(); - IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { - IdeFocusManager.getGlobalInstance().requestFocus(myRevisionText, true); - }); + myRevisionBox.addActionListener(e -> { + if (e.getSource() == myRevisionBox) { + myRevisionText.setEnabled(myRevisionBox.isSelected()); + if (myRevisionBox.isSelected()) { + if (myRevisionText.getText().trim().isEmpty()) { + myRevisionText.setText("HEAD"); } + myRevisionText.getTextField().selectAll(); + IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { + IdeFocusManager.getGlobalInstance().requestFocus(myRevisionText, true); + }); } } }); - myRevisionText.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - final Project project = vcs.getProject(); - // todo check whether ok; rather shoudl be used if checkbox is turned on - final SvnRepositoryLocation location = new SvnRepositoryLocation(myURLText.getText()); - final SvnChangeList repositoryVersion = SvnSelectRevisionUtil.chooseCommittedChangeList(project, location, myRoot.getVirtualFile()); - if (repositoryVersion != null) { - myRevisionText.setText(String.valueOf(repositoryVersion.getNumber())); - } + myRevisionText.addActionListener(e -> { + final Project project = vcs.getProject(); + // todo check whether ok; rather shoudl be used if checkbox is turned on + final SvnRepositoryLocation location = new SvnRepositoryLocation(myURLText.getText()); + final SvnChangeList repositoryVersion = SvnSelectRevisionUtil.chooseCommittedChangeList(project, location, myRoot.getVirtualFile()); + if (repositoryVersion != null) { + myRevisionText.setText(String.valueOf(repositoryVersion.getNumber())); } }); @@ -149,24 +134,22 @@ public class SvnUpdateRootOptionsPanel implements SvnPanel{ myBranchField.setEnabled(false); return; } - SelectBranchPopup.show(myVcs.getProject(), myRoot.getVirtualFile(), new SelectBranchPopup.BranchSelectedCallback() { - public void branchSelected(final Project project, final SvnBranchConfigurationNew configuration, final String url, final long revision) { - // TODO: It seems that we could reuse configuration passed as parameter to this callback - SvnBranchConfigurationNew branchConfiguration = getBranchConfiguration(); - String branchRelativeUrl = branchConfiguration != null ? branchConfiguration.getRelativeUrl(mySourceUrl.toString()) : null; + SelectBranchPopup.show(myVcs.getProject(), myRoot.getVirtualFile(), (project, configuration, url, revision) -> { + // TODO: It seems that we could reuse configuration passed as parameter to this callback + SvnBranchConfigurationNew branchConfiguration = getBranchConfiguration(); + String branchRelativeUrl = branchConfiguration != null ? branchConfiguration.getRelativeUrl(mySourceUrl.toString()) : null; - if (mySourceUrl == null || branchRelativeUrl == null) { - myBranchField.setText(""); + if (mySourceUrl == null || branchRelativeUrl == null) { + myBranchField.setText(""); + } + else { + try { + myURLText.setText(SVNURL.parseURIEncoded(url).appendPath(branchRelativeUrl, true).toDecodedString()); } - else { - try { - myURLText.setText(SVNURL.parseURIEncoded(url).appendPath(branchRelativeUrl, true).toDecodedString()); - } - catch (SVNException e) { - LOG.error(e); - } - myBranchField.setText(SVNPathUtil.tail(url)); + catch (SVNException e) { + LOG.error(e); } + myBranchField.setText(SVNPathUtil.tail(url)); } }, SvnBundle.message("select.branch.popup.general.title"), myPanel); } diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/UpdateEventHandler.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/UpdateEventHandler.java index d8bbaccd9f47..f6eb96acbaa2 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/update/UpdateEventHandler.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/update/UpdateEventHandler.java @@ -89,7 +89,7 @@ public class UpdateEventHandler implements ProgressTracker { * TODO: UPDATE_STARTED event in some code paths. */ public void startUpdate() { - myFilesWaitingForRevision.push(ContainerUtil.>newArrayList()); + myFilesWaitingForRevision.push(ContainerUtil.newArrayList()); } public void finishUpdate() { @@ -189,7 +189,7 @@ public class UpdateEventHandler implements ProgressTracker { if (mySequentialUpdatesContext != null) { mySequentialUpdatesContext.registerExternalRootBeingUpdated(event.getFile()); } - myFilesWaitingForRevision.push(ContainerUtil.>newArrayList()); + myFilesWaitingForRevision.push(ContainerUtil.newArrayList()); myExternalsCount++; myText = SvnBundle.message("progress.text.updating.external.location", event.getFile().getAbsolutePath()); } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/SvnTestCase.java b/plugins/svn4idea/testSource/org/jetbrains/idea/SvnTestCase.java index 1e3924e0be6f..d0e7ec018d0d 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/SvnTestCase.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/SvnTestCase.java @@ -17,7 +17,10 @@ package org.jetbrains.idea; import com.intellij.execution.process.ProcessOutput; import com.intellij.ide.startup.impl.StartupManagerImpl; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.ActionManager; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.PluginPathManager; @@ -41,7 +44,6 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent; -import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import com.intellij.testFramework.fixtures.TempDirTestFixture; import com.intellij.testFramework.vcs.AbstractJunitVcsTestCase; @@ -53,7 +55,6 @@ import com.intellij.util.TimeoutUtil; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.io.ZipUtil; import com.intellij.util.ui.UIUtil; -import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.svn.SvnApplicationSettings; @@ -121,63 +122,60 @@ public abstract class SvnTestCase extends AbstractJunitVcsTestCase { myTestDataDir = property; } - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); - myTempDirFixture = fixtureFactory.createTempDirTestFixture(); - myTempDirFixture.setUp(); + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + try { + final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); + myTempDirFixture = fixtureFactory.createTempDirTestFixture(); + myTempDirFixture.setUp(); - myRepoRoot = new File(myTempDirFixture.getTempDirPath(), "svnroot"); - assert myRepoRoot.mkdir() || myRepoRoot.isDirectory() : myRepoRoot; + myRepoRoot = new File(myTempDirFixture.getTempDirPath(), "svnroot"); + assert myRepoRoot.mkdir() || myRepoRoot.isDirectory() : myRepoRoot; - myPluginRoot = new File(PluginPathManager.getPluginHomePath("svn4idea")); - if (!myPluginRoot.isDirectory()) { - // try standalone mode - Class aClass = SvnTestCase.class; - String rootPath = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class"); - myPluginRoot = new File(rootPath).getParentFile().getParentFile().getParentFile(); - } - - File svnBinDir = new File(myPluginRoot, getTestDataDir() + "/svn/bin"); - File svnExecutable = null; - if (SystemInfo.isWindows) { - svnExecutable = new File(svnBinDir, "windows/svn.exe"); - } - else if (SystemInfo.isLinux) { - svnExecutable = new File(svnBinDir, "linux/svn"); - } - else if (SystemInfo.isMac) { - svnExecutable = new File(svnBinDir, "mac/svn"); - } - assertTrue("No Subversion executable was found: " + svnExecutable + ", " + SystemInfo.OS_NAME, - svnExecutable != null && svnExecutable.canExecute()); - myClientBinaryPath = svnExecutable.getParentFile(); - myRunner = SystemInfo.isMac - ? createClientRunner(Collections.singletonMap("DYLD_LIBRARY_PATH", myClientBinaryPath.getPath())) - : createClientRunner(); - - ZipUtil.extract(new File(myPluginRoot, getTestDataDir() + "/svn/newrepo.zip"), myRepoRoot, null); - - myWcRoot = new File(myTempDirFixture.getTempDirPath(), myWcRootName); - assert myWcRoot.mkdir() || myWcRoot.isDirectory() : myWcRoot; - - myRepoUrl = (SystemInfo.isWindows ? "file:///" : "file://") + FileUtil.toSystemIndependentName(myRepoRoot.getPath()); - - verify(runSvn("co", myRepoUrl, myWcRoot.getPath())); - - initProject(myWcRoot, SvnTestCase.this.getTestName()); - activateVCS(SvnVcs.VCS_NAME); - - myGate = new MockChangeListManagerGate(ChangeListManager.getInstance(myProject)); - - ((StartupManagerImpl) StartupManager.getInstance(myProject)).runPostStartupActivities(); - refreshSvnMappingsSynchronously(); + myPluginRoot = new File(PluginPathManager.getPluginHomePath("svn4idea")); + if (!myPluginRoot.isDirectory()) { + // try standalone mode + Class aClass = SvnTestCase.class; + String rootPath = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class"); + myPluginRoot = new File(rootPath).getParentFile().getParentFile().getParentFile(); } - catch (Exception e) { - throw new RuntimeException(e); + + File svnBinDir = new File(myPluginRoot, getTestDataDir() + "/svn/bin"); + File svnExecutable = null; + if (SystemInfo.isWindows) { + svnExecutable = new File(svnBinDir, "windows/svn.exe"); } + else if (SystemInfo.isLinux) { + svnExecutable = new File(svnBinDir, "linux/svn"); + } + else if (SystemInfo.isMac) { + svnExecutable = new File(svnBinDir, "mac/svn"); + } + assertTrue("No Subversion executable was found: " + svnExecutable + ", " + SystemInfo.OS_NAME, + svnExecutable != null && svnExecutable.canExecute()); + myClientBinaryPath = svnExecutable.getParentFile(); + myRunner = SystemInfo.isMac + ? createClientRunner(Collections.singletonMap("DYLD_LIBRARY_PATH", myClientBinaryPath.getPath())) + : createClientRunner(); + + ZipUtil.extract(new File(myPluginRoot, getTestDataDir() + "/svn/newrepo.zip"), myRepoRoot, null); + + myWcRoot = new File(myTempDirFixture.getTempDirPath(), myWcRootName); + assert myWcRoot.mkdir() || myWcRoot.isDirectory() : myWcRoot; + + myRepoUrl = (SystemInfo.isWindows ? "file:///" : "file://") + FileUtil.toSystemIndependentName(myRepoRoot.getPath()); + + verify(runSvn("co", myRepoUrl, myWcRoot.getPath())); + + initProject(myWcRoot, SvnTestCase.this.getTestName()); + activateVCS(SvnVcs.VCS_NAME); + + myGate = new MockChangeListManagerGate(ChangeListManager.getInstance(myProject)); + + ((StartupManagerImpl) StartupManager.getInstance(myProject)).runPostStartupActivities(); + refreshSvnMappingsSynchronously(); + } + catch (Exception e) { + throw new RuntimeException(e); } }); @@ -196,12 +194,7 @@ public abstract class SvnTestCase extends AbstractJunitVcsTestCase { } final Semaphore semaphore = new Semaphore(); semaphore.down(); - ((SvnFileUrlMappingImpl) vcs.getSvnFileUrlMapping()).realRefresh(new Runnable() { - @Override - public void run() { - semaphore.up(); - } - }); + ((SvnFileUrlMappingImpl) vcs.getSvnFileUrlMapping()).realRefresh(() -> semaphore.up()); semaphore.waitFor(); } @@ -216,28 +209,25 @@ public abstract class SvnTestCase extends AbstractJunitVcsTestCase { public void tearDown() throws Exception { ((ChangeListManagerImpl) ChangeListManager.getInstance(myProject)).stopEveryThingIfInTestMode(); sleep(100); - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - tearDownProject(); + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + try { + tearDownProject(); - if (myWcRoot != null && myWcRoot.exists()) { - FileUtil.delete(myWcRoot); - } - if (myRepoRoot != null && myRepoRoot.exists()) { - FileUtil.delete(myRepoRoot); - } + if (myWcRoot != null && myWcRoot.exists()) { + FileUtil.delete(myWcRoot); + } + if (myRepoRoot != null && myRepoRoot.exists()) { + FileUtil.delete(myRepoRoot); + } - if (myTempDirFixture != null) { - myTempDirFixture.tearDown(); - myTempDirFixture = null; - } - } - catch (Exception e) { - throw new RuntimeException(e); + if (myTempDirFixture != null) { + myTempDirFixture.tearDown(); + myTempDirFixture = null; } } + catch (Exception e) { + throw new RuntimeException(e); + } }); } @@ -269,16 +259,13 @@ public abstract class SvnTestCase extends AbstractJunitVcsTestCase { } protected void undo() { - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - final TestDialog oldTestDialog = Messages.setTestDialog(TestDialog.OK); - try { - UndoManager.getInstance(myProject).undo(null); - } - finally { - Messages.setTestDialog(oldTestDialog); - } + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + final TestDialog oldTestDialog = Messages.setTestDialog(TestDialog.OK); + try { + UndoManager.getInstance(myProject).undo(null); + } + finally { + Messages.setTestDialog(oldTestDialog); } }); } @@ -485,15 +472,11 @@ public abstract class SvnTestCase extends AbstractJunitVcsTestCase { final CommonUpdateProjectAction action = new CommonUpdateProjectAction(); action.getTemplatePresentation().setText("1"); action.actionPerformed(new AnActionEvent(null, - new DataContext() { - @Nullable - @Override - public Object getData(@NonNls String dataId) { - if (CommonDataKeys.PROJECT.is(dataId)) { - return project; - } - return null; + dataId -> { + if (CommonDataKeys.PROJECT.is(dataId)) { + return project; } + return null; }, "test", new Presentation(), ActionManager.getInstance(), 0)); final ChangeListManager clManager = ChangeListManager.getInstance(project); @@ -511,29 +494,23 @@ public abstract class SvnTestCase extends AbstractJunitVcsTestCase { } private void runStatusAcrossLocks(@Nullable File workingDir, final boolean sorted, final String... stdoutLines) throws IOException { - final Processor primitiveVerifier = new Processor() { - @Override - public boolean process(ProcessOutput output) { - if (sorted) { - verifySorted(output, stdoutLines); // will assert if err not empty - } else { - verify(output, stdoutLines); // will assert if err not empty - } - return false; + final Processor primitiveVerifier = output -> { + if (sorted) { + verifySorted(output, stdoutLines); // will assert if err not empty + } else { + verify(output, stdoutLines); // will assert if err not empty } + return false; }; - runAndVerifyAcrossLocks(workingDir, new String[]{"status"}, new Processor() { - @Override - public boolean process(ProcessOutput output) { - final List lines = output.getStdoutLines(); - for (String line : lines) { - if (line.trim().startsWith("L")) { - return true; // i.e. continue tries - } + runAndVerifyAcrossLocks(workingDir, new String[]{"status"}, output -> { + final List lines = output.getStdoutLines(); + for (String line : lines) { + if (line.trim().startsWith("L")) { + return true; // i.e. continue tries } - primitiveVerifier.process(output); - return false; } + primitiveVerifier.process(output); + return false; }, primitiveVerifier); } @@ -543,12 +520,9 @@ public abstract class SvnTestCase extends AbstractJunitVcsTestCase { } private static Processor createPrimitiveExitCodeVerifier() { - return new Processor() { - @Override - public boolean process(ProcessOutput output) { - assertEquals(output.getStderr(), 0, output.getExitCode()); - return false; - } + return output -> { + assertEquals(output.getStderr(), 0, output.getExitCode()); + return false; }; } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/IgnoredFilesTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/IgnoredFilesTest.java index a58ff1d3910e..97641e1cc7c4 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/IgnoredFilesTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/IgnoredFilesTest.java @@ -54,57 +54,51 @@ public class IgnoredFilesTest extends Svn17TestCase { @Before public void setUp() throws Exception { super.setUp(); - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); - myTempDirFixture = fixtureFactory.createTempDirTestFixture(); - myTempDirFixture.setUp(); + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + try { + final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); + myTempDirFixture = fixtureFactory.createTempDirTestFixture(); + myTempDirFixture.setUp(); - myClientRoot = new File(myTempDirFixture.getTempDirPath(), "clientroot"); - myClientRoot.mkdir(); + myClientRoot = new File(myTempDirFixture.getTempDirPath(), "clientroot"); + myClientRoot.mkdir(); - initProject(myClientRoot, IgnoredFilesTest.this.getTestName()); + initProject(myClientRoot, IgnoredFilesTest.this.getTestName()); - ((StartupManagerImpl)StartupManager.getInstance(myProject)).runPostStartupActivities(); + ((StartupManagerImpl)StartupManager.getInstance(myProject)).runPostStartupActivities(); - myChangeListManager = ChangeListManager.getInstance(myProject); - myVcs = SvnVcs.getInstance(myProject); - myVcsManager = (ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(myProject); - myVcsManager.registerVcs(myVcs); - myVcsManager.setDirectoryMapping(myWorkingCopyDir.getPath(), myVcs.getName()); + myChangeListManager = ChangeListManager.getInstance(myProject); + myVcs = SvnVcs.getInstance(myProject); + myVcsManager = (ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(myProject); + myVcsManager.registerVcs(myVcs); + myVcsManager.setDirectoryMapping(myWorkingCopyDir.getPath(), myVcs.getName()); - myVcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject); - myLocalFileSystem = LocalFileSystem.getInstance(); - } - catch (Exception e) { - throw new RuntimeException(e); - } + myVcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject); + myLocalFileSystem = LocalFileSystem.getInstance(); + } + catch (Exception e) { + throw new RuntimeException(e); } }); } @After public void tearDown() throws Exception { - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - myVcsManager.unregisterVcs(myVcs); - myVcsManager = null; - myVcs = null; + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + try { + myVcsManager.unregisterVcs(myVcs); + myVcsManager = null; + myVcs = null; - tearDownProject(); - if (myTempDirFixture != null) { - myTempDirFixture.tearDown(); - myTempDirFixture = null; - } - FileUtil.delete(myClientRoot); - } - catch (Exception e) { - throw new RuntimeException(e); + tearDownProject(); + if (myTempDirFixture != null) { + myTempDirFixture.tearDown(); + myTempDirFixture = null; } + FileUtil.delete(myClientRoot); + } + catch (Exception e) { + throw new RuntimeException(e); } }); } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnAnnotationIsClosedTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnAnnotationIsClosedTest.java index 73000a14880e..2fd35356a471 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnAnnotationIsClosedTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnAnnotationIsClosedTest.java @@ -15,7 +15,10 @@ */ package org.jetbrains.idea.svn; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.ActionManager; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.openapi.vcs.VcsException; @@ -31,8 +34,6 @@ import com.intellij.openapi.vcs.update.CommonUpdateProjectAction; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import junit.framework.Assert; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.Nullable; import org.junit.Before; import org.junit.Test; @@ -77,12 +78,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); @@ -116,12 +114,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); @@ -132,15 +127,11 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final CommonUpdateProjectAction action = new CommonUpdateProjectAction(); action.getTemplatePresentation().setText("1"); action.actionPerformed(new AnActionEvent(null, - new DataContext() { - @Nullable - @Override - public Object getData(@NonNls String dataId) { - if (CommonDataKeys.PROJECT.is(dataId)) { - return myProject; - } - return null; + dataId -> { + if (CommonDataKeys.PROJECT.is(dataId)) { + return myProject; } + return null; }, "test", new Presentation(), ActionManager.getInstance(), 0)); myChangeListManager.ensureUpToDate(false); @@ -161,12 +152,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); VcsTestUtil.editFileInCommand(myProject, tree.myS1File, "1+\n2\n3\n4\n"); @@ -179,15 +167,11 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final CommonUpdateProjectAction action = new CommonUpdateProjectAction(); action.getTemplatePresentation().setText("1"); action.actionPerformed(new AnActionEvent(null, - new DataContext() { - @Nullable - @Override - public Object getData(@NonNls String dataId) { - if (CommonDataKeys.PROJECT.is(dataId)) { - return myProject; - } - return null; + dataId -> { + if (CommonDataKeys.PROJECT.is(dataId)) { + return myProject; } + return null; }, "test", new Presentation(), ActionManager.getInstance(), 0)); myChangeListManager.ensureUpToDate(false); @@ -208,12 +192,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); VcsTestUtil.editFileInCommand(myProject, tree.myS1File, "1+\n2\n3\n4\n"); @@ -243,12 +224,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); @@ -275,12 +253,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); @@ -303,12 +278,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); VcsTestUtil.editFileInCommand(myProject, tree.myS1File, "1+\n2\n3\n4\n"); @@ -374,22 +346,16 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { // then annotate both final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), vf1); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(vf1, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(vf1, annotation); }); listener.registerAnnotation(vf1, annotation); final FileAnnotation annotation1 = createTestAnnotation(myVcs.getAnnotationProvider(), vf2); - annotation1.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed1 = true; - listener.unregisterAnnotation(vf1, annotation1); - } + annotation1.setCloser(() -> { + myIsClosed1 = true; + listener.unregisterAnnotation(vf1, annotation1); }); listener.registerAnnotation(vf1, annotation1); diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnAuthenticationTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnAuthenticationTest.java index 29cdf6d5e876..23d5903375c6 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnAuthenticationTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnAuthenticationTest.java @@ -79,15 +79,12 @@ public class SvnAuthenticationTest extends PlatformTestCase { @Override protected void tearDown() throws Exception { - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - SvnAuthenticationTest.super.tearDown(); - } - catch (Exception e) { - throw new RuntimeException(e); - } + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + try { + SvnAuthenticationTest.super.tearDown(); + } + catch (Exception e) { + throw new RuntimeException(e); } }); @@ -175,31 +172,28 @@ public class SvnAuthenticationTest extends PlatformTestCase { try { FileUtil.appendToFile(servers, "\nstore-plaintext-passwords=yes\n"); - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.save)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.save)); - commonScheme(url, false, null); - Assert.assertEquals(3, listener.getCnt()); - //long start = System.currentTimeMillis(); - //waitListenerStep(start, listener, 3); + commonScheme(url, false, null); + Assert.assertEquals(3, listener.getCnt()); + //long start = System.currentTimeMillis(); + //waitListenerStep(start, listener, 3); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - commonScheme(url, false, null); - //start = System.currentTimeMillis(); - //waitListenerStep(start, listener, 4); - Assert.assertEquals(4, listener.getCnt()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + commonScheme(url, false, null); + //start = System.currentTimeMillis(); + //waitListenerStep(start, listener, 4); + Assert.assertEquals(4, listener.getCnt()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); } finally { FileUtil.delete(servers); @@ -245,35 +239,32 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - commonScheme(url, false, null); - //long start = System.currentTimeMillis(); - //waitListenerStep(start, listener, 2); - Assert.assertEquals(2, listener.getCnt()); + commonScheme(url, false, null); + //long start = System.currentTimeMillis(); + //waitListenerStep(start, listener, 2); + Assert.assertEquals(2, listener.getCnt()); - savedOnceListener.assertNotSaved(url, ISVNAuthenticationManager.PASSWORD); - // cause is not cleared though - savedOnceListener.reset(); + savedOnceListener.assertNotSaved(url, ISVNAuthenticationManager.PASSWORD); + // cause is not cleared though + savedOnceListener.reset(); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - commonScheme(url, false, null); - Assert.assertEquals(4, listener.getCnt()); - //start = System.currentTimeMillis(); - //waitListenerStep(start, listener, 4); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + commonScheme(url, false, null); + Assert.assertEquals(4, listener.getCnt()); + //start = System.currentTimeMillis(); + //waitListenerStep(start, listener, 4); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -311,32 +302,29 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - commonScheme(url, false, null); - Assert.assertEquals(2, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumAuthWarn()); - myTestInteraction.reset(); - savedOnceListener.assertForAwt(); - savedOnceListener.reset(); + commonScheme(url, false, null); + Assert.assertEquals(2, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumAuthWarn()); + myTestInteraction.reset(); + savedOnceListener.assertForAwt(); + savedOnceListener.reset(); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - commonScheme(url, false, null); - Assert.assertEquals(4, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumAuthWarn()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + commonScheme(url, false, null); + Assert.assertEquals(4, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumAuthWarn()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -372,32 +360,29 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - commonScheme(url, false, null); - Assert.assertEquals(2, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumAuthWarn()); - myTestInteraction.reset(); - savedOnceListener.assertForAwt(); - savedOnceListener.reset(); + commonScheme(url, false, null); + Assert.assertEquals(2, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumAuthWarn()); + myTestInteraction.reset(); + savedOnceListener.assertForAwt(); + savedOnceListener.reset(); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - commonScheme(url, false, null); - Assert.assertEquals(4, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumAuthWarn()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + commonScheme(url, false, null); + Assert.assertEquals(4, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumAuthWarn()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -439,34 +424,31 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - Assert.assertEquals(3, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); - myTestInteraction.reset(); - savedOnceListener.assertForAwt(); - savedOnceListener.reset(); + commonScheme(url, false, null); + Assert.assertEquals(3, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); + myTestInteraction.reset(); + savedOnceListener.assertForAwt(); + savedOnceListener.reset(); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - Assert.assertEquals(6, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + commonScheme(url, false, null); + Assert.assertEquals(6, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -502,34 +484,31 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - Assert.assertEquals(3, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); - myTestInteraction.reset(); - savedOnceListener.assertForAwt(); - savedOnceListener.reset(); + commonScheme(url, false, null); + Assert.assertEquals(3, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); + myTestInteraction.reset(); + savedOnceListener.assertForAwt(); + savedOnceListener.reset(); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - Assert.assertEquals(6, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + commonScheme(url, false, null); + Assert.assertEquals(6, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -572,34 +551,31 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - Assert.assertEquals(3, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); - myTestInteraction.reset(); - savedOnceListener.assertForAwt(); - savedOnceListener.reset(); + commonScheme(url, false, null); + Assert.assertEquals(3, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); + myTestInteraction.reset(); + savedOnceListener.assertForAwt(); + savedOnceListener.reset(); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - Assert.assertEquals(6, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + commonScheme(url, false, null); + Assert.assertEquals(6, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumPasswordsWarn()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -635,34 +611,31 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - Assert.assertEquals(3, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumSSLWarn()); - myTestInteraction.reset(); - savedOnceListener.assertForAwt(); - savedOnceListener.reset(); + commonScheme(url, false, null); + Assert.assertEquals(3, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumSSLWarn()); + myTestInteraction.reset(); + savedOnceListener.assertForAwt(); + savedOnceListener.reset(); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - Assert.assertEquals(6, listener.getCnt()); - Assert.assertEquals(1, myTestInteraction.getNumSSLWarn()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + commonScheme(url, false, null); + Assert.assertEquals(6, listener.getCnt()); + Assert.assertEquals(1, myTestInteraction.getNumSSLWarn()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -695,61 +668,55 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.save)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.save)); - commonScheme(url, false, null); - long start = System.currentTimeMillis(); - waitListenerStep(start, listener, 3); - Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); - savedOnceListener.assertSaved(url, ISVNAuthenticationManager.PASSWORD); - savedOnceListener.reset(); - myTestInteraction.reset(); + commonScheme(url, false, null); + long start = System.currentTimeMillis(); + waitListenerStep(start, listener, 3); + Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); + savedOnceListener.assertSaved(url, ISVNAuthenticationManager.PASSWORD); + savedOnceListener.reset(); + myTestInteraction.reset(); - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - clearAuthCache(); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - }); + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + try { + clearAuthCache(); + } + catch (Exception e) { + throw new RuntimeException(e); + } + }); - myTestInteraction.setPlaintextAnswer(false); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + myTestInteraction.setPlaintextAnswer(false); + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - start = System.currentTimeMillis(); - waitListenerStep(start, listener, 6); - Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + commonScheme(url, false, null); + start = System.currentTimeMillis(); + waitListenerStep(start, listener, 6); + Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); - savedOnceListener.reset(); - myTestInteraction.reset(); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - start = System.currentTimeMillis(); - waitListenerStep(start, listener, 9); - Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + savedOnceListener.reset(); + myTestInteraction.reset(); + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + commonScheme(url, false, null); + start = System.currentTimeMillis(); + waitListenerStep(start, listener, 9); + Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -784,36 +751,33 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - long start = System.currentTimeMillis(); - waitListenerStep(start, listener, 3); - Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); - // actually password not saved, but save was called - savedOnceListener.assertSaved(url, ISVNAuthenticationManager.PASSWORD); - savedOnceListener.reset(); - myTestInteraction.reset(); + commonScheme(url, false, null); + long start = System.currentTimeMillis(); + waitListenerStep(start, listener, 3); + Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); + // actually password not saved, but save was called + savedOnceListener.assertSaved(url, ISVNAuthenticationManager.PASSWORD); + savedOnceListener.reset(); + myTestInteraction.reset(); - listener.addStep(new Trinity<>(ProviderType.persistent, url2, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url2, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url2, Type.without_pasword_save)); - commonScheme(url2, false, "anotherRealm"); - start = System.currentTimeMillis(); - waitListenerStep(start, listener, 6); - Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + listener.addStep(new Trinity<>(ProviderType.persistent, url2, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url2, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url2, Type.without_pasword_save)); + commonScheme(url2, false, "anotherRealm"); + start = System.currentTimeMillis(); + waitListenerStep(start, listener, 6); + Assert.assertEquals(1, myTestInteraction.getNumPlaintextPrompt()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -844,62 +808,56 @@ public class SvnAuthenticationTest extends PlatformTestCase { final SVNException[] exception = new SVNException[1]; final Boolean[] result = new Boolean[1]; - synchronousBackground(new Runnable() { - @Override - public void run() { - try { - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.save)); + synchronousBackground(() -> { + try { + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.save)); - commonScheme(url, false, null); - long start = System.currentTimeMillis(); - waitListenerStep(start, listener, 3); - Assert.assertEquals(1, myTestInteraction.getNumSSLPlaintextPrompt()); - savedOnceListener.assertSaved(url, ISVNAuthenticationManager.SSL); - savedOnceListener.reset(); - myTestInteraction.reset(); + commonScheme(url, false, null); + long start = System.currentTimeMillis(); + waitListenerStep(start, listener, 3); + Assert.assertEquals(1, myTestInteraction.getNumSSLPlaintextPrompt()); + savedOnceListener.assertSaved(url, ISVNAuthenticationManager.SSL); + savedOnceListener.reset(); + myTestInteraction.reset(); - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - clearAuthCache(); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - }); + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + try { + clearAuthCache(); + } + catch (Exception e) { + throw new RuntimeException(e); + } + }); - myTestInteraction.setSSLPlaintextAnswer(false); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + myTestInteraction.setSSLPlaintextAnswer(false); + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - start = System.currentTimeMillis(); - waitListenerStep(start, listener, 6); - Assert.assertEquals(1, myTestInteraction.getNumSSLPlaintextPrompt()); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + commonScheme(url, false, null); + start = System.currentTimeMillis(); + waitListenerStep(start, listener, 6); + Assert.assertEquals(1, myTestInteraction.getNumSSLPlaintextPrompt()); - SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); - myTestInteraction.reset(); - savedOnceListener.reset(); + SvnConfiguration.RUNTIME_AUTH_CACHE.clear(); + myTestInteraction.reset(); + savedOnceListener.reset(); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); - listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); - commonScheme(url, false, null); - start = System.currentTimeMillis(); - waitListenerStep(start, listener, 9); - Assert.assertEquals(1, myTestInteraction.getNumSSLPlaintextPrompt()); - } - catch (SVNException e) { - exception[0] = e; - } - result[0] = true; + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.interactive, url, Type.request)); + listener.addStep(new Trinity<>(ProviderType.persistent, url, Type.without_pasword_save)); + commonScheme(url, false, null); + start = System.currentTimeMillis(); + waitListenerStep(start, listener, 9); + Assert.assertEquals(1, myTestInteraction.getNumSSLPlaintextPrompt()); } + catch (SVNException e) { + exception[0] = e; + } + result[0] = true; }); Assert.assertTrue(result[0]); @@ -918,14 +876,11 @@ public class SvnAuthenticationTest extends PlatformTestCase { private static void synchronousBackground(final Runnable runnable) throws InterruptedException { final Semaphore semaphore = new Semaphore(); semaphore.down(); - ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { - @Override - public void run() { - try { - runnable.run(); - } finally { - semaphore.up(); - } + ApplicationManager.getApplication().executeOnPooledThread(() -> { + try { + runnable.run(); + } finally { + semaphore.up(); } }); semaphore.waitFor(); diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCachingRepositoryPoolTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCachingRepositoryPoolTest.java index e4ae9146d47f..a97125002255 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCachingRepositoryPoolTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCachingRepositoryPoolTest.java @@ -20,7 +20,6 @@ import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.impl.ProgressManagerImpl; import com.intellij.testFramework.vcs.FileBasedTest; import com.intellij.util.ConcurrencyUtil; -import com.intellij.util.ThrowableConvertor; import com.intellij.util.TimeoutUtil; import com.intellij.util.concurrency.Semaphore; import junit.framework.Assert; @@ -31,7 +30,6 @@ import org.junit.Test; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.io.ISVNSession; -import org.tmatesoft.svn.core.io.SVNRepository; import java.util.ArrayList; import java.util.List; @@ -75,45 +73,29 @@ public class SvnCachingRepositoryPoolTest extends FileBasedTest { public void testCancel() throws Exception { final SvnIdeaRepositoryPoolManager poolManager = new SvnIdeaRepositoryPoolManager(true, null, null, 1, 1); final SVNURL url = SVNURL.parseURIEncoded("http://a.b.c"); - poolManager.setCreator(new ThrowableConvertor() { - @Override - public SVNRepository convert(SVNURL svnurl) throws SVNException { - return new MockSvnRepository(svnurl, ISVNSession.DEFAULT); - } - }); + poolManager.setCreator(svnurl -> new MockSvnRepository(svnurl, ISVNSession.DEFAULT)); final MockSvnRepository repository1 = (MockSvnRepository)poolManager.createRepository(url, true); final Semaphore semaphore = new Semaphore(); semaphore.down(); - poolManager.setCreator(new ThrowableConvertor() { - @Override - public SVNRepository convert(SVNURL svnurl) throws SVNException { - semaphore.waitFor(); - return new MockSvnRepository(svnurl, ISVNSession.DEFAULT); - } + poolManager.setCreator(svnurl -> { + semaphore.waitFor(); + return new MockSvnRepository(svnurl, ISVNSession.DEFAULT); }); final SVNException[] exc = new SVNException[1]; - final Runnable target = new Runnable() { - @Override - public void run() { - try { - final MockSvnRepository repository = (MockSvnRepository)poolManager.createRepository(url, true); - repository.fireConnectionClosed(); - } - catch (SVNException e) { - e.printStackTrace(); - exc[0] = e; - } + final Runnable target = () -> { + try { + final MockSvnRepository repository = (MockSvnRepository)poolManager.createRepository(url, true); + repository.fireConnectionClosed(); + } + catch (SVNException e) { + e.printStackTrace(); + exc[0] = e; } }; final EmptyProgressIndicator indicator = new EmptyProgressIndicator(); - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - ((ProgressManagerImpl)ProgressManager.getInstance()).executeProcessUnderProgress(target, indicator); - } - }, "svn cache repo"); + Thread thread = new Thread(() -> ((ProgressManagerImpl)ProgressManager.getInstance()).executeProcessUnderProgress(target, indicator), "svn cache repo"); thread.start(); TimeoutUtil.sleep(10); @@ -156,12 +138,7 @@ public class SvnCachingRepositoryPoolTest extends FileBasedTest { } private void testBigFlow(final SvnIdeaRepositoryPoolManager poolManager, boolean disposeAfter) throws SVNException, InterruptedException { - poolManager.setCreator(new ThrowableConvertor() { - @Override - public SVNRepository convert(SVNURL svnurl) throws SVNException { - return new MockSvnRepository(svnurl, ISVNSession.DEFAULT); - } - }); + poolManager.setCreator(svnurl -> new MockSvnRepository(svnurl, ISVNSession.DEFAULT)); final SVNURL url = SVNURL.parseURIEncoded("http://a.b.c"); final Random random = new Random(System.currentTimeMillis() & 0x00ff); final int[] cnt = new int[1]; @@ -169,24 +146,21 @@ public class SvnCachingRepositoryPoolTest extends FileBasedTest { final SVNException[] exc = new SVNException[1]; List threads = new ArrayList<>(); for (int i = 0; i < 25; i++) { - Runnable target = new Runnable() { - @Override - public void run() { - MockSvnRepository repository = null; - try { - repository = (MockSvnRepository)poolManager.createRepository(url, true); - } - catch (SVNException e) { - e.printStackTrace(); - exc[0] = e; - return; - } - repository.fireConnectionOpened(); - TimeoutUtil.sleep(random.nextInt(10)); - repository.fireConnectionClosed(); - synchronized (cnt) { - -- cnt[0]; - } + Runnable target = () -> { + MockSvnRepository repository = null; + try { + repository = (MockSvnRepository)poolManager.createRepository(url, true); + } + catch (SVNException e) { + e.printStackTrace(); + exc[0] = e; + return; + } + repository.fireConnectionOpened(); + TimeoutUtil.sleep(random.nextInt(10)); + repository.fireConnectionClosed(); + synchronized (cnt) { + -- cnt[0]; } }; Thread thread = new Thread(target, "svn cache"); diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCachingRevisionsTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCachingRevisionsTest.java index a0805c032b62..c2f15c10290a 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCachingRevisionsTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCachingRevisionsTest.java @@ -219,7 +219,7 @@ public class SvnCachingRevisionsTest extends CodeInsightFixtureTestCase { } public void testJustLiveProvider() throws Exception { - performTest(11, 2, null, Collections.>emptyList(), 121); + performTest(11, 2, null, Collections.emptyList(), 121); } public void testLiveAndSimpleInternalProvider() throws Exception { @@ -230,7 +230,7 @@ public class SvnCachingRevisionsTest extends CodeInsightFixtureTestCase { public void testLiveAndSimpleCommittedProvider() throws Exception { for (int i = 0; i < 2 * PAGE; i+=2) { - performTest(11, 2, new Pair<>(19L, 117L), Collections.>emptyList(), 121 + i); + performTest(11, 2, new Pair<>(19L, 117L), Collections.emptyList(), 121 + i); } } @@ -259,7 +259,7 @@ public class SvnCachingRevisionsTest extends CodeInsightFixtureTestCase { } public void testShortLive() throws Exception { - performTest(11, 2, null, Collections.>emptyList(), 13); + performTest(11, 2, null, Collections.emptyList(), 13); } public void testShortInternal() throws Exception { @@ -267,7 +267,7 @@ public class SvnCachingRevisionsTest extends CodeInsightFixtureTestCase { } public void testShortCommitted() throws Exception { - performTest(11, 2, new Pair<>(11L, 15L), Collections.>emptyList(), 15); + performTest(11, 2, new Pair<>(11L, 15L), Collections.emptyList(), 15); } public void testThreeByOne() throws Exception { diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCommitTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCommitTest.java index 76e4de99d8cd..a25ad9ec8b7b 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCommitTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnCommitTest.java @@ -16,16 +16,17 @@ package org.jetbrains.idea.svn; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vcs.*; +import com.intellij.openapi.vcs.FilePath; +import com.intellij.openapi.vcs.FileStatus; +import com.intellij.openapi.vcs.VcsConfiguration; +import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.NullableFunction; import com.intellij.vcsUtil.VcsUtil; import junit.framework.Assert; -import org.jetbrains.annotations.Nullable; import org.junit.Before; import org.junit.Test; @@ -444,14 +445,7 @@ public class SvnCommitTest extends Svn17TestCase { changes.add(change); } final HashSet feedback = new HashSet<>(); - final List exceptions = myVcs.getCheckinEnvironment().commit(changes, "test comment list", - new NullableFunction() { - @Nullable - @Override - public Object fun(Object o) { - return null; - } - }, feedback); + final List exceptions = myVcs.getCheckinEnvironment().commit(changes, "test comment list", o -> null, feedback); if (exceptions !=null && ! exceptions.isEmpty()) { exceptions.get(0).printStackTrace(); } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnConcurrentChangeListManagerTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnConcurrentChangeListManagerTest.java index 97abf82a38ef..2ea1240baf68 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnConcurrentChangeListManagerTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnConcurrentChangeListManagerTest.java @@ -53,12 +53,9 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { final String newName = "renamed"; - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.editName(list.getName(), newName); - checkFilesAreInList(new VirtualFile[] {file}, newName, changeListManager); - } + myScheme.doTest(() -> { + changeListManager.editName(list.getName(), newName); + checkFilesAreInList(new VirtualFile[] {file}, newName, changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, newName, changeListManager); @@ -80,15 +77,12 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty(); changeListManager.ensureUpToDate(false); - final Runnable check = new Runnable() { - @Override - public void run() { - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myS1File)); - Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File)); - Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir)); - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir)); - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1))); - } + final Runnable check = () -> { + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myS1File)); + Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File)); + Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir)); + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir)); + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1))); }; // do before refresh check check.run(); @@ -101,15 +95,12 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty(); changeListManager.ensureUpToDate(false); - final Runnable check2 = new Runnable() { - @Override - public void run() { - Assert.assertEquals(FileStatus.MODIFIED, changeListManager.getStatus(tree.myS1File)); - Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File)); - Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir)); - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir)); - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1))); - } + final Runnable check2 = () -> { + Assert.assertEquals(FileStatus.MODIFIED, changeListManager.getStatus(tree.myS1File)); + Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File)); + Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir)); + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir)); + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1))); }; myScheme.doTest(check2); @@ -130,19 +121,16 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { final String finalText = "final text"; - myScheme.doTest(new Runnable() { - @Override - public void run() { - final String intermediate = "intermediate text"; - changeListManager.editComment(list.getName(), intermediate); - assert changeListManager.findChangeList(listName) != null; - LocalChangeList list = changeListManager.findChangeList(listName); - assert intermediate.equals(list.getComment()); + myScheme.doTest(() -> { + final String intermediate = "intermediate text"; + changeListManager.editComment(list.getName(), intermediate); + assert changeListManager.findChangeList(listName) != null; + LocalChangeList list1 = changeListManager.findChangeList(listName); + assert intermediate.equals(list1.getComment()); - changeListManager.editComment(list.getName(), finalText); - list = changeListManager.findChangeList(listName); - assert finalText.equals(list.getComment()); - } + changeListManager.editComment(list1.getName(), finalText); + list1 = changeListManager.findChangeList(listName); + assert finalText.equals(list1.getComment()); }); LocalChangeList changedList = changeListManager.findChangeList(listName); @@ -164,12 +152,9 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { final LocalChangeList target = changeListManager.addChangeList("target", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); - } + myScheme.doTest(() -> { + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); @@ -189,12 +174,9 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { final LocalChangeList target = changeListManager.addChangeList("target", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.setDefaultChangeList(target); - assert changeListManager.getDefaultChangeList().getName().equals(target.getName()); - } + myScheme.doTest(() -> { + changeListManager.setDefaultChangeList(target); + assert changeListManager.getDefaultChangeList().getName().equals(target.getName()); }); assert changeListManager.getDefaultChangeList().getName().equals(target.getName()); @@ -214,13 +196,10 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { final LocalChangeList list = changeListManager.addChangeList("test", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.removeChangeList(list.getName()); - assert changeListManager.findChangeList(list.getName()) == null; - checkFilesAreInList(new VirtualFile[] {file, fileB}, myDefaulListName, changeListManager); - } + myScheme.doTest(() -> { + changeListManager.removeChangeList(list.getName()); + assert changeListManager.findChangeList(list.getName()) == null; + checkFilesAreInList(new VirtualFile[] {file, fileB}, myDefaulListName, changeListManager); }); assert changeListManager.findChangeList(list.getName()) == null; @@ -243,14 +222,11 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { final LocalChangeList target2 = changeListManager.addChangeList("target2", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); - changeListManager.moveChangesTo(target2, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, target2.getName(), changeListManager); - } + myScheme.doTest(() -> { + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); + changeListManager.moveChangesTo(target2, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, target2.getName(), changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, target2.getName(), changeListManager); @@ -270,14 +246,11 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { final LocalChangeList target = changeListManager.addChangeList("target", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); - changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, list.getName(), changeListManager); - } + myScheme.doTest(() -> { + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); + changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, list.getName(), changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, list.getName(), changeListManager); @@ -298,13 +271,10 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { final String targetName = "target"; - myScheme.doTest(new Runnable() { - @Override - public void run() { - final LocalChangeList target = changeListManager.addChangeList(targetName, null); - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager); - } + myScheme.doTest(() -> { + final LocalChangeList target = changeListManager.addChangeList(targetName, null); + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager); @@ -347,21 +317,18 @@ public class SvnConcurrentChangeListManagerTest extends Svn17TestCase { final String targetName = "target"; final String finalName = "final list name"; - myScheme.doTest(new Runnable() { - @Override - public void run() { - final LocalChangeList target = changeListManager.addChangeList(targetName, null); - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file), changeListManager.getChange(fileB)}); - checkFilesAreInList(new VirtualFile[] {file, fileB}, targetName, changeListManager); - changeListManager.editName(targetName, finalName); - checkFilesAreInList(new VirtualFile[] {file, fileB}, finalName, changeListManager); - changeListManager.removeChangeList(toBeDeletedList.getName()); - checkFilesAreInList(new VirtualFile[] {fileC, fileD}, myDefaulListName, changeListManager); - changeListManager.moveChangesTo(LocalChangeList.createEmptyChangeList(myProject, finalName), - new Change[] {changeListManager.getChange(fileC)}); - checkFilesAreInList(new VirtualFile[] {file, fileB, fileC}, finalName, changeListManager); - checkFilesAreInList(new VirtualFile[] {fileD}, myDefaulListName, changeListManager); - } + myScheme.doTest(() -> { + final LocalChangeList target = changeListManager.addChangeList(targetName, null); + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file), changeListManager.getChange(fileB)}); + checkFilesAreInList(new VirtualFile[] {file, fileB}, targetName, changeListManager); + changeListManager.editName(targetName, finalName); + checkFilesAreInList(new VirtualFile[] {file, fileB}, finalName, changeListManager); + changeListManager.removeChangeList(toBeDeletedList.getName()); + checkFilesAreInList(new VirtualFile[] {fileC, fileD}, myDefaulListName, changeListManager); + changeListManager.moveChangesTo(LocalChangeList.createEmptyChangeList(myProject, finalName), + new Change[] {changeListManager.getChange(fileC)}); + checkFilesAreInList(new VirtualFile[] {file, fileB, fileC}, finalName, changeListManager); + checkFilesAreInList(new VirtualFile[] {fileD}, myDefaulListName, changeListManager); }); checkFilesAreInList(new VirtualFile[] {file, fileB, fileC}, finalName, changeListManager); diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnExternalTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnExternalTest.java index 9ea6bff797b9..b1bd43f6297a 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnExternalTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnExternalTest.java @@ -178,13 +178,8 @@ public class SvnExternalTest extends Svn17TestCase { } private void setNewDirectoryMappings(final File sourceDir) { - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - ProjectLevelVcsManager.getInstance(myProject).setDirectoryMappings( - Arrays.asList(new VcsDirectoryMapping(FileUtil.toSystemIndependentName(sourceDir.getPath()), myVcs.getName()))); - } - }); + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> ProjectLevelVcsManager.getInstance(myProject).setDirectoryMappings( + Arrays.asList(new VcsDirectoryMapping(FileUtil.toSystemIndependentName(sourceDir.getPath()), myVcs.getName())))); } @Test diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnLockingTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnLockingTest.java deleted file mode 100644 index 30e130ebebb3..000000000000 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnLockingTest.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * 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.idea.svn; - -import com.intellij.idea.Bombed; -import com.intellij.openapi.application.PathManager; -import com.intellij.openapi.application.PluginPathManager; -import com.intellij.util.TimeoutUtil; -import com.intellij.util.concurrency.Semaphore; -import junit.framework.Assert; -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Ignore; -import org.tmatesoft.sqljet.core.SqlJetException; -import org.tmatesoft.sqljet.core.table.ISqlJetBusyHandler; -import org.tmatesoft.sqljet.core.table.ISqlJetTransaction; -import org.tmatesoft.sqljet.core.table.SqlJetDb; -import org.tmatesoft.svn.core.SVNException; -import org.tmatesoft.svn.core.SVNURL; -import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; -import org.tmatesoft.svn.core.wc.ISVNRepositoryPool; -import org.tmatesoft.svn.core.wc.SVNRevision; -import org.tmatesoft.svn.core.wc.SVNWCClient; - -import java.io.File; -import java.util.Calendar; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Created with IntelliJ IDEA. - * User: Irina.Chernushina - * Date: 10/23/12 - * Time: 2:27 PM - */ -// TODO: Locking functionality which is tested by this test is not required anymore. Likely test needs to be removed. -@Ignore -public class SvnLockingTest extends TestCase { - private File myWorkingCopyRoot; - private SvnTestWriteOperationLocks myLocks; - - @Before - public void setUp() throws Exception { - super.setUp(); - //PlatformTestCase.initPlatformLangPrefix(); - File pluginRoot = new File(PluginPathManager.getPluginHomePath("svn4idea")); - if (!pluginRoot.isDirectory()) { - // try standalone mode - Class aClass = Svn17TestCase.class; - String rootPath = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class"); - pluginRoot = new File(rootPath).getParentFile().getParentFile().getParentFile(); - } - myWorkingCopyRoot = new File(pluginRoot, "testData/move2unv"); - myLocks = new SvnTestWriteOperationLocks(new WorkingCopy(myWorkingCopyRoot, SVNURL.parseURIEncoded("http://a.b.c"), true)); - } - - @Override - public void tearDown() throws Exception { - super.tearDown(); - } - - public void testPrepare() throws Exception { - final HangInWrite operation1 = new HangInWrite("one", false); - operation1.hang(); - operation1.go(); - } - - public void testPrepareRead() throws Exception { - final HangInRead read = new HangInRead("READ", false); - read.run(); - read.go(); - } - - public void testWritesSequential() throws Exception { - final HangInWrite operation1 = new HangInWrite("one_"); - final HangInWrite operation2 = new HangInWrite("two_"); - - final Thread thread1 = new Thread(operation1,"op1"); - final Thread thread2 = new Thread(operation2,"op2"); - try { - thread1.start(); - waitForRunning(operation1); - Assert.assertTrue(operation1.isRunning()); - - thread2.start(); - waitForRunning(operation2); - Assert.assertFalse(operation2.isRunning()); - - operation1.go(); - waitForRunning(operation2); - Assert.assertTrue(operation2.isRunning()); - operation2.go(); - Thread.sleep(10); - } finally { - operation1.stop(); - operation2.stop(); - - thread1.interrupt(); - thread2.interrupt(); - thread1.join(); - thread2.join(); - } - } - - public void testOnlyWrites() throws Exception { - final OnlyWrite operation1 = new OnlyWrite("one"); - final OnlyWrite operation2 = new OnlyWrite("two"); - - final Thread thread1 = new Thread(operation1,"one"); - final Thread thread2 = new Thread(operation2,"two"); - - try { - thread1.start(); - TimeoutUtil.sleep(500); - Assert.assertTrue(operation1.isInsideWrite()); - thread2.start(); - TimeoutUtil.sleep(500); - Assert.assertFalse(operation2.isInsideWrite()); - operation1.go(); - TimeoutUtil.sleep(500); - Assert.assertTrue(operation2.isInsideWrite()); - operation2.go(); - TimeoutUtil.sleep(500); - } finally { - myLocks.dispose(); - operation1.stop(); - operation2.stop(); - Thread.sleep(100); - - thread1.interrupt(); - thread2.interrupt(); - thread1.join(); - thread2.join(); - } - } - - /*public void testDelays() throws Exception { - final HandlerCopy handler = new HandlerCopy(10000); - for (int i = 0; i < 1000; i++) { - final Pair pair = handler.call(i); - System.out.println("# " + i + " DELAY: " + pair.getSecond() + " CONTINUE: " + pair.getFirst()); - } - } - - private static class HandlerCopy { - private static final int[] delays = { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; - private static final int[] totals = { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 }; - - private final int timeout; - - public HandlerCopy(int timeout) { - this.timeout = timeout; - } - - public Pair call(int number) { - int delay; - int prior; - if (number < delays.length) { - delay = delays[number]; - prior = totals[number]; - } else { - delay = delays[delays.length - 1]; - prior = totals[delays.length - 1] + delay*(number - (delays.length - 1)); - } - if (prior + delay > timeout) { - delay = timeout - prior; - if (delay <= 0) { - return new Pair(false, delay); - } - } - try { - Thread.sleep(delay); - } catch (InterruptedException e) { - // - } - return new Pair(true, delay); - } - }*/ - - @Bombed(user="irengrig", year = 2020, month = Calendar.FEBRUARY, day = 1, - description = "not clear. by specification, read should not get access if write lock is taken; sometimes it is not the case.") - public void testReadInBetweenWrites() throws Exception { - final HangInWrite operation1 = new HangInWrite("one1"); - final HangInWrite operation2 = new HangInWrite("two1"); - final HangInRead read = new HangInRead("READ"); - - final Thread thread1 = new Thread(operation1,"op1"); - final Thread threadRead = new Thread(read,"read1"); - final Thread thread2 = new Thread(operation2,"op2"); - - try { - thread1.start(); - waitForRunning(operation1); - Assert.assertTrue(operation1.isRunning()); - - threadRead.start(); - waitForRunning(read); - Assert.assertFalse(read.isRunning()); // not clear why read is allowed to run when write is active, but I've not thought it over so much - - operation1.go(); - waitForRunning(read, 20); - Assert.assertTrue(read.isRunning()); - - thread2.start(); - waitForRunning(operation2); - Assert.assertFalse(operation2.isRunning()); // again, not clear why write is allowed to run when read is active, but I've not thought it over so much - - read.go(); - waitForRunning(operation2); - Assert.assertTrue(operation2.isRunning()); - // have some time after read to complete - Thread.sleep(100); - } finally { - myLocks.dispose(); - operation1.stop(); - operation2.stop(); - Thread.sleep(100); - - thread1.interrupt(); - thread2.interrupt(); - threadRead.interrupt(); - thread1.join(); - thread2.join(); - threadRead.join(); - } - } - - private void waitForRunning(HangRun operation1) { - waitForRunning(operation1, 1); - } - - private void waitForRunning(HangRun operation1, int multiply) { - int cnt = 10 * multiply; - while (cnt > 0) { - TimeoutUtil.sleep(10 * multiply); - if (operation1.isRunning()) break; - -- cnt; - } - } - - public interface HangRun { - void go(); - boolean isRunning(); - void stop(); - } - - private class HangInRead implements Runnable, HangRun { - private final AtomicBoolean myIsRunning; - private final String myName; - private final boolean myWaitFor; - private final Semaphore mySemaphore; - - private HangInRead(String name) { - this(name, true); - } - - private HangInRead(String name, final boolean waitFor) { - myName = name; - myWaitFor = waitFor; - myIsRunning = new AtomicBoolean(false); - mySemaphore = new Semaphore(); - } - - @Override - public void run() { - mySemaphore.down(); - try { - System.out.println("starting read " + myName); - myLocks.wrapRead(myWorkingCopyRoot, new Runnable() { - @Override - public void run() { - System.out.println("inside read " + myName); - final SVNWCClient client = new SVNWCClient((ISVNRepositoryPool)null, new DefaultSVNOptions()); - try { - client.doInfo(myWorkingCopyRoot, SVNRevision.BASE); - } - catch (SVNException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - myIsRunning.set(true); - System.out.println("got status " + myName); - if (myWaitFor) { - mySemaphore.waitFor(); - } - System.out.println("have read " + myName); - } - }); - } - catch (SVNException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - @Override - public void go() { - System.out.println("read going " + myName); - mySemaphore.up(); - } - - @Override - public boolean isRunning() { - System.out.println("read running " + myName + " " + myIsRunning.get()); - return myIsRunning.get(); - } - - @Override - public void stop() { - } - } - - private class OnlyWrite extends HangInWrite { - private OnlyWrite(String name) { - super(name); - } - - @Override - public void run() { - mySemaphore.down(); - operation(); - } - } - - private class HangInWrite implements Runnable, HangRun { - protected final Semaphore mySemaphore; - private final AtomicBoolean myIsRunning; - private final AtomicBoolean myInsideWrite; - private final String myName; - private boolean shouldWait; - private volatile boolean myStopped; - - private HangInWrite(final String name) { - this(name, true); - } - - private HangInWrite(final String name, final boolean shouldWait) { - myName = name; - mySemaphore = new Semaphore(); - this.shouldWait = shouldWait; - myIsRunning = new AtomicBoolean(false); - myInsideWrite = new AtomicBoolean(false); - } - - @Override - public void run() { - try { - hang(); - } - catch (SVNException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - protected void operation() { - System.out.println("TRY OPEN FOR WRITE==="); - SqlJetDb open = null; - try { - open = SqlJetDb.open(SvnUtil.getWcDb(myWorkingCopyRoot), true); - open.setBusyHandler(new ISqlJetBusyHandler() { - @Override - public boolean call(int i) { - if (myStopped) return false; - System.out.println("busy " + myName); - TimeoutUtil.sleep(10); - return true; - } - }); - try { - System.out.println("TRY OPEN FOR WRITE " + myName); - open.runWriteTransaction(new ISqlJetTransaction() { - @Override - public Object run(SqlJetDb db) throws SqlJetException { - System.out.println("OPENed FOR WRITE " + myName); - myInsideWrite.set(true); - if (shouldWait) { - mySemaphore.waitFor(); - } - return null; - } - }); - } finally { - myInsideWrite.set(false); - open.rollback(); - } - } - catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - finally { - if (open != null) { - try { - open.close(); - } - catch (SqlJetException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - System.out.println("CLOSed FOR WRITE " + myName); - } - } - } - - public boolean isInsideWrite() { - return myInsideWrite.get(); - } - - public void hang() throws SVNException { - System.out.println("starting " + myName); - mySemaphore.down(); - myLocks.lockWrite(myWorkingCopyRoot); - myIsRunning.set(true); - System.out.println("started " + myName); - try { - operation(); - } finally { - myLocks.unlockWrite(myWorkingCopyRoot); - myIsRunning.set(false); - } - } - - public boolean isRunning() { - System.out.println("running " + myName + " " + myIsRunning.get()); - return myIsRunning.get(); - } - - @Override - public void stop() { - myStopped = true; - } - - public void go() { - System.out.println("going " + myName); - mySemaphore.up(); - } - } -} diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnMergeInfoTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnMergeInfoTest.java index f29a61acafbb..fb6fdac7d0ad 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnMergeInfoTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnMergeInfoTest.java @@ -100,7 +100,7 @@ public class SvnMergeInfoTest extends Svn17TestCase { enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); final String repoUrl = SVNURL.parseURIDecoded(myRepoUrl).toString(); - myWCInfoWithBranches = new WCInfoWithBranches(myWCInfo, Collections.emptyList(), vcsRoot, + myWCInfoWithBranches = new WCInfoWithBranches(myWCInfo, Collections.emptyList(), vcsRoot, new WCInfoWithBranches.Branch(repoUrl + "/trunk")); myMergeChecker = new BranchInfo(myVcs, myWCInfoWithBranches, new WCInfoWithBranches.Branch(repoUrl + "/branch")); } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnNativeClientAuthTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnNativeClientAuthTest.java index 59ea65a49a19..ea79d7650ba4 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnNativeClientAuthTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnNativeClientAuthTest.java @@ -21,13 +21,10 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.CurrentContentRevision; -import com.intellij.openapi.vcs.update.SequentialUpdatesContext; import com.intellij.openapi.vcs.update.UpdateSession; import com.intellij.openapi.vcs.update.UpdatedFiles; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Processor; -import com.intellij.util.containers.Convertor; import com.intellij.vcsUtil.VcsUtil; import junit.framework.Assert; import org.jetbrains.annotations.NotNull; @@ -36,7 +33,10 @@ import org.jetbrains.idea.svn.auth.SvnAuthenticationManager; import org.jetbrains.idea.svn.auth.SvnAuthenticationNotifier; import org.jetbrains.idea.svn.checkout.SvnCheckoutProvider; import org.junit.Before; -import org.tmatesoft.svn.core.*; +import org.tmatesoft.svn.core.SVNDirEntry; +import org.tmatesoft.svn.core.SVNErrorMessage; +import org.tmatesoft.svn.core.SVNException; +import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.*; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNRevision; @@ -111,31 +111,25 @@ public class SvnNativeClientAuthTest extends Svn17TestCase { manager.setAuthenticationProvider(authentication); authentication.addAuthentication(ISVNAuthenticationManager.PASSWORD, - new Convertor() { - @Override - public SVNAuthentication convert(SVNURL o) { - ++ myCredentialsAskedInteractivelyCount; - if (myCancelAuth) return null; - if (myCredentialsCorrect) { - return new SVNPasswordAuthentication(outHttpUser, outHttpPassword, mySaveCredentials, o, false); - } else { - myCredentialsCorrect = true;// only once - return new SVNPasswordAuthentication("1234214 23 4234", "324324", mySaveCredentials, o, false); - } + o -> { + ++ myCredentialsAskedInteractivelyCount; + if (myCancelAuth) return null; + if (myCredentialsCorrect) { + return new SVNPasswordAuthentication(outHttpUser, outHttpPassword, mySaveCredentials, o, false); + } else { + myCredentialsCorrect = true;// only once + return new SVNPasswordAuthentication("1234214 23 4234", "324324", mySaveCredentials, o, false); } }); authentication.addAuthentication(ISVNAuthenticationManager.SSL, - new Convertor() { - @Override - public SVNAuthentication convert(SVNURL o) { - ++ myCredentialsAskedInteractivelyCount; - if (myCancelAuth) return null; - if (myCredentialsCorrect) { - return new SVNSSLAuthentication(certFile, "12345", mySaveCredentials, o, false); - } else { - myCredentialsCorrect = true;// only once - return new SVNSSLAuthentication(new File("1232432423"), "3245321532534235445", mySaveCredentials, o, false); - } + o -> { + ++ myCredentialsAskedInteractivelyCount; + if (myCancelAuth) return null; + if (myCredentialsCorrect) { + return new SVNSSLAuthentication(certFile, "12345", mySaveCredentials, o, false); + } else { + myCredentialsCorrect = true;// only once + return new SVNSSLAuthentication(new File("1232432423"), "3245321532534235445", mySaveCredentials, o, false); } }); myCertificateAskedInteractivelyCount = 0; @@ -557,12 +551,9 @@ public class SvnNativeClientAuthTest extends Svn17TestCase { }, WorkingCopyFormat.ONE_DOT_SEVEN); final int[] cnt = new int[1]; cnt[0] = 0; - FileUtil.processFilesRecursively(root, new Processor() { - @Override - public boolean process(File file) { - ++ cnt[0]; - return ! (cnt[0] > 1); - } + FileUtil.processFilesRecursively(root, file -> { + ++ cnt[0]; + return ! (cnt[0] > 1); }); Assert.assertTrue(cnt[0] > 1); myIsSecure = url.contains("https:"); @@ -610,12 +601,7 @@ public class SvnNativeClientAuthTest extends Svn17TestCase { private void testBrowseRepositoryImpl(final String url) throws SVNException { final List list = new ArrayList<>(); final SVNRepository repository = myVcs.getSvnKitManager().createRepository(url); - repository.getDir(".", -1, null, new ISVNDirEntryHandler() { - @Override - public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException { - list.add(dirEntry); - } - }); + repository.getDir(".", -1, null, dirEntry -> list.add(dirEntry)); Assert.assertTrue(!list.isEmpty()); } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnParseCommandLineParseTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnParseCommandLineParseTest.java index 50caf38eee9e..26ee3feadbf8 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnParseCommandLineParseTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnParseCommandLineParseTest.java @@ -19,17 +19,16 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.util.Consumer; -import com.intellij.util.containers.Convertor; import com.intellij.util.containers.MultiMap; import junit.framework.Assert; import junit.framework.TestCase; import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.api.NodeKind; -import org.jetbrains.idea.svn.status.Status; import org.jetbrains.idea.svn.info.Info; -import org.jetbrains.idea.svn.status.*; import org.jetbrains.idea.svn.info.SvnInfoHandler; +import org.jetbrains.idea.svn.status.CmdStatusClient; +import org.jetbrains.idea.svn.status.PortableStatus; +import org.jetbrains.idea.svn.status.SvnStatusHandler; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.wc.SVNRevision; @@ -81,12 +80,7 @@ public class SvnParseCommandLineParseTest extends TestCase { ""; final Info[] info = new Info[1]; - final SvnInfoHandler handler = new SvnInfoHandler(new File("C:/base/"), new Consumer() { - @Override - public void consume(Info info1) { - info[0] = info1; - } - }); + final SvnInfoHandler handler = new SvnInfoHandler(new File("C:/base/"), info1 -> info[0] = info1); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(new ByteArrayInputStream(s.getBytes(CharsetToolkit.UTF8_CHARSET)), handler); @@ -570,33 +564,30 @@ public class SvnParseCommandLineParseTest extends TestCase { @Override public void switchChangeList(String newList) { } - }, new File(basePath), new Convertor() { - @Override - public Info convert(File o) { - try { - o.getCanonicalFile(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - if (isWindows) { - final int idx = o.getPath().indexOf(":"); - Assert.assertTrue(idx > 0); - final int secondIdx = o.getPath().indexOf(":", idx + 1); - Assert.assertTrue(o.getPath(), secondIdx == -1); - } else { - if (o.getPath().contains(LINUX_ROOT)) { - Assert.assertFalse(o.getPath().contains(basePath)); - } - } - try { - return createStubInfo(basePath + "1", "http://a.b.c"); - } - catch (SVNException e) { - // - throw new RuntimeException(e); + }, new File(basePath), o -> { + try { + o.getCanonicalFile(); + } + catch (IOException e) { + throw new RuntimeException(e); + } + if (isWindows) { + final int idx = o.getPath().indexOf(":"); + Assert.assertTrue(idx > 0); + final int secondIdx = o.getPath().indexOf(":", idx + 1); + Assert.assertTrue(o.getPath(), secondIdx == -1); + } else { + if (o.getPath().contains(LINUX_ROOT)) { + Assert.assertFalse(o.getPath().contains(basePath)); } } + try { + return createStubInfo(basePath + "1", "http://a.b.c"); + } + catch (SVNException e) { + // + throw new RuntimeException(e); + } }); handlerArr[0] = handler; @@ -667,33 +658,27 @@ public class SvnParseCommandLineParseTest extends TestCase { final String basePath = "C:\\TestProjects\\sortedProjects\\Subversion\\local2\\sep12main\\main"; final SvnStatusHandler[] handler = new SvnStatusHandler[1]; final File baseFile = new File(basePath); - final SvnStatusHandler.ExternalDataCallback callback = CmdStatusClient.createStatusCallback(new StatusConsumer() { - @Override - public void consume(Status status) throws SVNException { - System.out.println(status.getURL()); - if (new File( - "C:\\TestProjects\\sortedProjects\\Subversion\\local2\\sep12main\\main\\slave\\src\\com\\slave\\MacMessagesParser.java") - .equals(status.getFile())) { - Assert.assertEquals("http://external/src/com/slave/MacMessagesParser.java", status.getURL().toString()); - } - if (new File("C:\\TestProjects\\sortedProjects\\Subversion\\local2\\sep12main\\main\\slave\\src\\com\\slave\\SomeOtherClass.java") - .equals(status.getFile())) { - Assert.assertEquals("http://external/src/com/slave/SomeOtherClass.java", status.getURL().toString()); - } + final SvnStatusHandler.ExternalDataCallback callback = CmdStatusClient.createStatusCallback(status1 -> { + System.out.println(status1.getURL()); + if (new File( + "C:\\TestProjects\\sortedProjects\\Subversion\\local2\\sep12main\\main\\slave\\src\\com\\slave\\MacMessagesParser.java") + .equals(status1.getFile())) { + Assert.assertEquals("http://external/src/com/slave/MacMessagesParser.java", status1.getURL().toString()); + } + if (new File("C:\\TestProjects\\sortedProjects\\Subversion\\local2\\sep12main\\main\\slave\\src\\com\\slave\\SomeOtherClass.java") + .equals(status1.getFile())) { + Assert.assertEquals("http://external/src/com/slave/SomeOtherClass.java", status1.getURL().toString()); } }, baseFile, createStubInfo(basePath, "http://mainurl/"), handler); - handler[0] = new SvnStatusHandler(callback, baseFile, new Convertor() { - @Override - public Info convert(File o) { - try { - if (new File("C:\\TestProjects\\sortedProjects\\Subversion\\local2\\sep12main\\main\\slave").equals(o)) { - return createStubInfo(o.getPath(), "http://external"); - } - return createStubInfo(o.getPath(), "http://12345"); - } - catch (SVNException e) { - throw new RuntimeException(e); + handler[0] = new SvnStatusHandler(callback, baseFile, o -> { + try { + if (new File("C:\\TestProjects\\sortedProjects\\Subversion\\local2\\sep12main\\main\\slave").equals(o)) { + return createStubInfo(o.getPath(), "http://external"); } + return createStubInfo(o.getPath(), "http://12345"); + } + catch (SVNException e) { + throw new RuntimeException(e); } }); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); @@ -752,33 +737,30 @@ public class SvnParseCommandLineParseTest extends TestCase { @Override public void switchChangeList(String newList) { } - }, new File(basePath), new Convertor() { - @Override - public Info convert(File o) { - try { - o.getCanonicalFile(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - if (isWindows) { - final int idx = o.getPath().indexOf(":"); - Assert.assertTrue(idx > 0); - final int secondIdx = o.getPath().indexOf(":", idx + 1); - Assert.assertTrue(o.getPath(), secondIdx == -1); - } else { - if (o.getPath().contains(LINUX_ROOT)) { - Assert.assertFalse(o.getPath().contains(basePath)); - } - } - try { - return createStubInfo(basePath + "1", "http://a.b.c"); - } - catch (SVNException e) { - // - throw new RuntimeException(e); + }, new File(basePath), o -> { + try { + o.getCanonicalFile(); + } + catch (IOException e) { + throw new RuntimeException(e); + } + if (isWindows) { + final int idx = o.getPath().indexOf(":"); + Assert.assertTrue(idx > 0); + final int secondIdx = o.getPath().indexOf(":", idx + 1); + Assert.assertTrue(o.getPath(), secondIdx == -1); + } else { + if (o.getPath().contains(LINUX_ROOT)) { + Assert.assertFalse(o.getPath().contains(basePath)); } } + try { + return createStubInfo(basePath + "1", "http://a.b.c"); + } + catch (SVNException e) { + // + throw new RuntimeException(e); + } }); handlerArr[0] = handler; @@ -842,33 +824,30 @@ public class SvnParseCommandLineParseTest extends TestCase { public void switchChangeList(String newList) { clName[0] = newList; } - }, new File(basePath), new Convertor() { - @Override - public Info convert(File o) { - try { - o.getCanonicalFile(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - if (isWindows) { - final int idx = o.getPath().indexOf(":"); - Assert.assertTrue(idx > 0); - final int secondIdx = o.getPath().indexOf(":", idx + 1); - Assert.assertTrue(o.getPath(), secondIdx == -1); - } else { - if (o.getPath().contains(LINUX_ROOT)) { - Assert.assertFalse(o.getPath().contains(basePath)); - } - } - try { - return createStubInfo(basePath + "1", "http://a.b.c"); - } - catch (SVNException e) { - // - throw new RuntimeException(e); + }, new File(basePath), o -> { + try { + o.getCanonicalFile(); + } + catch (IOException e) { + throw new RuntimeException(e); + } + if (isWindows) { + final int idx = o.getPath().indexOf(":"); + Assert.assertTrue(idx > 0); + final int secondIdx = o.getPath().indexOf(":", idx + 1); + Assert.assertTrue(o.getPath(), secondIdx == -1); + } else { + if (o.getPath().contains(LINUX_ROOT)) { + Assert.assertFalse(o.getPath().contains(basePath)); } } + try { + return createStubInfo(basePath + "1", "http://a.b.c"); + } + catch (SVNException e) { + // + throw new RuntimeException(e); + } }); handlerArr[0] = handler; diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnProtocolsTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnProtocolsTest.java index 9669701c1012..d05054b41068 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnProtocolsTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnProtocolsTest.java @@ -19,7 +19,10 @@ import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vcs.*; +import com.intellij.openapi.vcs.CheckoutProvider; +import com.intellij.openapi.vcs.FilePath; +import com.intellij.openapi.vcs.VcsException; +import com.intellij.openapi.vcs.VcsKey; import com.intellij.openapi.vcs.actions.VcsContextFactory; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.CurrentContentRevision; @@ -27,20 +30,19 @@ import com.intellij.openapi.vcs.history.VcsAppendableHistoryPartnerAdapter; import com.intellij.openapi.vcs.history.VcsFileRevision; import com.intellij.openapi.vcs.history.VcsHistoryProvider; import com.intellij.openapi.vcs.update.FileGroup; -import com.intellij.openapi.vcs.update.SequentialUpdatesContext; import com.intellij.openapi.vcs.update.UpdateSession; import com.intellij.openapi.vcs.update.UpdatedFiles; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Processor; -import com.intellij.util.containers.Convertor; import com.intellij.vcsUtil.VcsUtil; import junit.framework.Assert; import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.auth.SvnAuthenticationManager; import org.jetbrains.idea.svn.checkout.SvnCheckoutProvider; import org.junit.Before; -import org.tmatesoft.svn.core.*; +import org.tmatesoft.svn.core.SVNDirEntry; +import org.tmatesoft.svn.core.SVNException; +import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.*; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNRevision; @@ -96,25 +98,10 @@ public class SvnProtocolsTest extends Svn17TestCase { manager.setAuthenticationProvider(authentication); authentication.addAuthentication(ISVNAuthenticationManager.SSH, - new Convertor() { - @Override - public SVNAuthentication convert(SVNURL o) { - return new SVNSSHAuthentication(SSH_USER_NAME, SSH_PASSWORD, SSH_PORT_NUMBER, true, o, false); - } - }); - authentication.addAuthentication(ISVNAuthenticationManager.USERNAME, new Convertor() { - @Override - public SVNAuthentication convert(SVNURL o) { - return new SVNUserNameAuthentication(SSH_USER_NAME, true, o, false); - } - }); - authentication.addAuthentication(ISVNAuthenticationManager.PASSWORD, - new Convertor() { - @Override - public SVNAuthentication convert(SVNURL o) { - return new SVNPasswordAuthentication("sally", "abcde", true, o, false); - } - }); + o -> new SVNSSHAuthentication(SSH_USER_NAME, SSH_PASSWORD, SSH_PORT_NUMBER, true, o, false)); + authentication.addAuthentication(ISVNAuthenticationManager.USERNAME, o -> new SVNUserNameAuthentication(SSH_USER_NAME, true, o, false)); + authentication + .addAuthentication(ISVNAuthenticationManager.PASSWORD, o -> new SVNPasswordAuthentication("sally", "abcde", true, o, false)); } @Test @@ -128,12 +115,7 @@ public class SvnProtocolsTest extends Svn17TestCase { private void testBrowseRepositoryImpl(final String url) throws SVNException { final List list = new ArrayList<>(); final SVNRepository repository = myVcs.getSvnKitManager().createRepository(url); - repository.getDir(".", -1, null, new ISVNDirEntryHandler() { - @Override - public void handleDirEntry(SVNDirEntry dirEntry) throws SVNException { - list.add(dirEntry); - } - }); + repository.getDir(".", -1, null, dirEntry -> list.add(dirEntry)); Assert.assertTrue(! list.isEmpty()); } @@ -235,12 +217,9 @@ public class SvnProtocolsTest extends Svn17TestCase { }, WorkingCopyFormat.ONE_DOT_SEVEN); final int[] cnt = new int[1]; cnt[0] = 0; - FileUtil.processFilesRecursively(root, new Processor() { - @Override - public boolean process(File file) { - ++ cnt[0]; - return ! (cnt[0] > 1); - } + FileUtil.processFilesRecursively(root, file -> { + ++ cnt[0]; + return ! (cnt[0] > 1); }); Assert.assertTrue(cnt[0] > 1); return root; diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java index b3e0c53ac716..ad58cdf6a4b4 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java @@ -110,18 +110,15 @@ public class SvnRenameTest extends Svn17TestCase { refreshVfs(); // wait for end of refresh operations initiated from SvnFileSystemListener final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); - insideInitializedChangeListManager(changeListManager, new Runnable() { - @Override - public void run() { - changeListManager.ensureUpToDate(false); - List changes = new ArrayList<>(changeListManager.getDefaultChangeList().getChanges()); - Assert.assertEquals(4, changes.size()); - sortChanges(changes); - verifyChange(changes.get(0), "child", "childnew"); - verifyChange(changes.get(1), "child" + File.separatorChar + "a.txt", "childnew" + File.separatorChar + "a.txt"); - verifyChange(changes.get(2), "child" + File.separatorChar + "grandChild", "childnew" + File.separatorChar + "grandChild"); - verifyChange(changes.get(3), "child" + File.separatorChar + "grandChild" + File.separatorChar + "b.txt", "childnew" + File.separatorChar + "grandChild" + File.separatorChar + "b.txt"); - } + insideInitializedChangeListManager(changeListManager, () -> { + changeListManager.ensureUpToDate(false); + List changes = new ArrayList<>(changeListManager.getDefaultChangeList().getChanges()); + Assert.assertEquals(4, changes.size()); + sortChanges(changes); + verifyChange(changes.get(0), "child", "childnew"); + verifyChange(changes.get(1), "child" + File.separatorChar + "a.txt", "childnew" + File.separatorChar + "a.txt"); + verifyChange(changes.get(2), "child" + File.separatorChar + "grandChild", "childnew" + File.separatorChar + "grandChild"); + verifyChange(changes.get(3), "child" + File.separatorChar + "grandChild" + File.separatorChar + "b.txt", "childnew" + File.separatorChar + "grandChild" + File.separatorChar + "b.txt"); }); // there is no such directory any more @@ -181,20 +178,17 @@ public class SvnRenameTest extends Svn17TestCase { renameFileInCommand(child, "newchild"); final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); - insideInitializedChangeListManager(changeListManager, new Runnable() { - @Override - public void run() { - changeListManager.ensureUpToDate(false); - final Change change = changeListManager.getChange(myWorkingCopyDir.findChild("newchild")); - Assert.assertNotNull(change); + insideInitializedChangeListManager(changeListManager, () -> { + changeListManager.ensureUpToDate(false); + final Change change = changeListManager.getChange(myWorkingCopyDir.findChild("newchild")); + Assert.assertNotNull(change); - final List exceptions = new ArrayList<>(); - SvnVcs.getInstance(myProject).getRollbackEnvironment().rollbackChanges(Collections.singletonList(change), exceptions, - RollbackProgressListener.EMPTY); - Assert.assertTrue(exceptions.isEmpty()); - Assert.assertFalse(new File(myWorkingCopyDir.getPath(), "newchild").exists()); - Assert.assertTrue(new File(myWorkingCopyDir.getPath(), "child").exists()); - } + final List exceptions = new ArrayList<>(); + SvnVcs.getInstance(myProject).getRollbackEnvironment().rollbackChanges(Collections.singletonList(change), exceptions, + RollbackProgressListener.EMPTY); + Assert.assertTrue(exceptions.isEmpty()); + Assert.assertFalse(new File(myWorkingCopyDir.getPath(), "newchild").exists()); + Assert.assertTrue(new File(myWorkingCopyDir.getPath(), "child").exists()); }); } @@ -208,19 +202,16 @@ public class SvnRenameTest extends Svn17TestCase { createFileInCommand(grandChild, "a.txt", "a"); checkin(); final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); - insideInitializedChangeListManager(changeListManager, new Runnable() { - @Override - public void run() { - moveFileInCommand(grandChild, myWorkingCopyDir); - refreshVfs(); // wait for end of refresh operations initiated from SvnFileSystemListener - changeListManager.ensureUpToDate(false); - final List changes = new ArrayList<>(changeListManager.getDefaultChangeList().getChanges()); - Assert.assertEquals(listToString(changes), 2, changes.size()); - sortChanges(changes); - verifyChange(changes.get(0), "child" + File.separatorChar + "grandChild", "grandChild"); - verifyChange(changes.get(1), "child" + File.separatorChar + "grandChild" + File.separatorChar + "a.txt", - "grandChild" + File.separatorChar + "a.txt"); - } + insideInitializedChangeListManager(changeListManager, () -> { + moveFileInCommand(grandChild, myWorkingCopyDir); + refreshVfs(); // wait for end of refresh operations initiated from SvnFileSystemListener + changeListManager.ensureUpToDate(false); + final List changes = new ArrayList<>(changeListManager.getDefaultChangeList().getChanges()); + Assert.assertEquals(listToString(changes), 2, changes.size()); + sortChanges(changes); + verifyChange(changes.get(0), "child" + File.separatorChar + "grandChild", "grandChild"); + verifyChange(changes.get(1), "child" + File.separatorChar + "grandChild" + File.separatorChar + "a.txt", + "grandChild" + File.separatorChar + "a.txt"); }); } @@ -241,37 +232,34 @@ public class SvnRenameTest extends Svn17TestCase { createFileInCommand(unversionedDir, "c.txt", "c"); final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); - insideInitializedChangeListManager(changeListManager, new Runnable() { - @Override - public void run() { - changeListManager.ensureUpToDate(false); - Assert.assertEquals(FileStatus.UNKNOWN, changeListManager.getStatus(unversioned)); + insideInitializedChangeListManager(changeListManager, () -> { + changeListManager.ensureUpToDate(false); + Assert.assertEquals(FileStatus.UNKNOWN, changeListManager.getStatus(unversioned)); - renameFileInCommand(child, "newchild"); - File childPath = new File(myWorkingCopyDir.getPath(), "child"); - File newChildPath = new File(myWorkingCopyDir.getPath(), "newchild"); - Assert.assertTrue(new File(newChildPath, "a.txt").exists()); - Assert.assertTrue(new File(newChildPath, "u.txt").exists()); - Assert.assertFalse(new File(childPath, "u.txt").exists()); + renameFileInCommand(child, "newchild"); + File childPath = new File(myWorkingCopyDir.getPath(), "child"); + File newChildPath = new File(myWorkingCopyDir.getPath(), "newchild"); + Assert.assertTrue(new File(newChildPath, "a.txt").exists()); + Assert.assertTrue(new File(newChildPath, "u.txt").exists()); + Assert.assertFalse(new File(childPath, "u.txt").exists()); - refreshVfs(); - changeListManager.ensureUpToDate(false); - final List changes = new ArrayList<>(); - changes.add(ChangeListManager.getInstance(myProject).getChange(myWorkingCopyDir.findChild("newchild").findChild("a.txt"))); - changes.add(ChangeListManager.getInstance(myProject).getChange(myWorkingCopyDir.findChild("newchild"))); + refreshVfs(); + changeListManager.ensureUpToDate(false); + final List changes = new ArrayList<>(); + changes.add(ChangeListManager.getInstance(myProject).getChange(myWorkingCopyDir.findChild("newchild").findChild("a.txt"))); + changes.add(ChangeListManager.getInstance(myProject).getChange(myWorkingCopyDir.findChild("newchild"))); - final List exceptions = new ArrayList<>(); - SvnVcs.getInstance(myProject).getRollbackEnvironment().rollbackChanges(changes, exceptions, RollbackProgressListener.EMPTY); - TimeoutUtil.sleep(300); - Assert.assertTrue(exceptions.isEmpty()); - final File fileA = new File(childPath, "a.txt"); - Assert.assertTrue(fileA.getAbsolutePath(), fileA.exists()); - final File fileU = new File(childPath, "u.txt"); - Assert.assertTrue(fileU.getAbsolutePath(), fileU.exists()); - final File unversionedDirFile = new File(childPath, "uc"); - Assert.assertTrue(unversionedDirFile.exists()); - Assert.assertTrue(new File(unversionedDirFile, "c.txt").exists()); - } + final List exceptions = new ArrayList<>(); + SvnVcs.getInstance(myProject).getRollbackEnvironment().rollbackChanges(changes, exceptions, RollbackProgressListener.EMPTY); + TimeoutUtil.sleep(300); + Assert.assertTrue(exceptions.isEmpty()); + final File fileA = new File(childPath, "a.txt"); + Assert.assertTrue(fileA.getAbsolutePath(), fileA.exists()); + final File fileU = new File(childPath, "u.txt"); + Assert.assertTrue(fileU.getAbsolutePath(), fileU.exists()); + final File unversionedDirFile = new File(childPath, "uc"); + Assert.assertTrue(unversionedDirFile.exists()); + Assert.assertTrue(new File(unversionedDirFile, "c.txt").exists()); }); } @@ -288,15 +276,12 @@ public class SvnRenameTest extends Svn17TestCase { "D child", "D child" + File.separatorChar + "a.txt", "D child" + File.separatorChar + "grandChild", "D child" + File.separatorChar + "grandChild" + File.separatorChar + "b.txt", "D + newchild" + File.separatorChar + "a.txt"); final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); - insideInitializedChangeListManager(changeListManager, new Runnable() { - @Override - public void run() { - refreshVfs(); // wait for end of refresh operations initiated from SvnFileSystemListener - changeListManager.ensureUpToDate(false); - final List changes = new ArrayList<>(changeListManager.getDefaultChangeList().getChanges()); - final List list = SvnVcs.getInstance(myProject).getCheckinEnvironment().commit(changes, "test"); - Assert.assertEquals(0, list.size()); - } + insideInitializedChangeListManager(changeListManager, () -> { + refreshVfs(); // wait for end of refresh operations initiated from SvnFileSystemListener + changeListManager.ensureUpToDate(false); + final List changes = new ArrayList<>(changeListManager.getDefaultChangeList().getChanges()); + final List list = SvnVcs.getInstance(myProject).getCheckinEnvironment().commit(changes, "test"); + Assert.assertEquals(0, list.size()); }); } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnResolveTreeAcceptVariantsTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnResolveTreeAcceptVariantsTest.java index a15068d37f1e..d6d3001a9301 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnResolveTreeAcceptVariantsTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnResolveTreeAcceptVariantsTest.java @@ -17,14 +17,16 @@ package org.jetbrains.idea.svn; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vcs.*; +import com.intellij.openapi.vcs.FilePath; +import com.intellij.openapi.vcs.ProjectLevelVcsManager; +import com.intellij.openapi.vcs.VcsConfiguration; +import com.intellij.openapi.vcs.VcsDirectoryMapping; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.ChangeListManagerImpl; import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Processor; import com.intellij.vcsUtil.VcsUtil; import junit.framework.Assert; import org.jetbrains.idea.svn.info.Info; @@ -84,12 +86,7 @@ public class SvnResolveTreeAcceptVariantsTest extends Svn17TestCase { return withSvn || ! SvnUtil.isAdminDirectory(o); } });*/ - clearDirInCommand(myWorkingCopyDir, new Processor() { - @Override - public boolean process(VirtualFile file) { - return withSvn || ! SvnUtil.isAdminDirectory(file); - } - }); + clearDirInCommand(myWorkingCopyDir, file -> withSvn || ! SvnUtil.isAdminDirectory(file)); myWorkingCopyDir.refresh(false, true); } @@ -257,40 +254,37 @@ public class SvnResolveTreeAcceptVariantsTest extends Svn17TestCase { myTheirs.refresh(false, true); myWorkingCopyDir.refresh(false, true); - VfsUtil.processFileRecursivelyWithoutIgnored(myTheirs, new Processor() { - @Override - public boolean process(VirtualFile file) { - final String relative = VfsUtil.getRelativePath(file, myTheirs, File.separatorChar); - File workingFile = new File(myWorkingCopyDir.getPath(), relative); - boolean exists = workingFile.exists(); - if (! exists) { - String[] excluded = data.getExcludeFromToTheirsCheck(); - if (excluded != null && Arrays.asList(excluded).contains(relative)) { - return true; - } - Assert.assertTrue("Check failed for test: " + getTestName(data) + " and file: " + relative + " in: " + myWorkingCopyDir.getPath(), - exists); + VfsUtil.processFileRecursivelyWithoutIgnored(myTheirs, file -> { + final String relative = VfsUtil.getRelativePath(file, myTheirs, File.separatorChar); + File workingFile = new File(myWorkingCopyDir.getPath(), relative); + boolean exists = workingFile.exists(); + if (! exists) { + String[] excluded = data.getExcludeFromToTheirsCheck(); + if (excluded != null && Arrays.asList(excluded).contains(relative)) { + return true; } - final File theirsFile = new File(file.getPath()); - Info theirsInfo = myVcs.getInfo(theirsFile); - Info thisInfo = myVcs.getInfo(workingFile); - if (theirsInfo != null) { - Assert.assertEquals("Check failed for test: " + getTestName(data) + " and file: " + relative + " in: " + myWorkingCopyDir.getPath() + - ", theirs: " + theirsInfo.getRevision().getNumber() + ", mine: " + thisInfo.getRevision().getNumber(), - theirsInfo.getRevision().getNumber(), thisInfo.getRevision().getNumber()); - if (! theirsFile.isDirectory()){ - try { - final String workText = FileUtil.loadFile(workingFile); - final String theirsText = FileUtil.loadFile(theirsFile); - Assert.assertEquals(theirsText, workText); - } - catch (IOException e) { - Assert.assertTrue(e.getMessage(), false); - } - } - } - return true; + Assert.assertTrue("Check failed for test: " + getTestName(data) + " and file: " + relative + " in: " + myWorkingCopyDir.getPath(), + exists); } + final File theirsFile = new File(file.getPath()); + Info theirsInfo = myVcs.getInfo(theirsFile); + Info thisInfo = myVcs.getInfo(workingFile); + if (theirsInfo != null) { + Assert.assertEquals("Check failed for test: " + getTestName(data) + " and file: " + relative + " in: " + myWorkingCopyDir.getPath() + + ", theirs: " + theirsInfo.getRevision().getNumber() + ", mine: " + thisInfo.getRevision().getNumber(), + theirsInfo.getRevision().getNumber(), thisInfo.getRevision().getNumber()); + if (! theirsFile.isDirectory()){ + try { + final String workText = FileUtil.loadFile(workingFile); + final String theirsText = FileUtil.loadFile(theirsFile); + Assert.assertEquals(theirsText, workText); + } + catch (IOException e) { + Assert.assertTrue(e.getMessage(), false); + } + } + } + return true; }); ++ cnt; } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRollbackTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRollbackTest.java index 4959dfaee83f..349340122686 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRollbackTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRollbackTest.java @@ -31,7 +31,6 @@ import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; -import org.tmatesoft.svn.core.wc.ISVNPropertyValueProvider; import org.tmatesoft.svn.core.wc.SVNPropertyData; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCClient; @@ -76,7 +75,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change change = myChangeListManager.getChange(a); Assert.assertNotNull(change); - rollbackIMpl(Collections.singletonList(change), Collections.emptyList()); + rollbackIMpl(Collections.singletonList(change), Collections.emptyList()); } private void rollbackIMpl(List changes, final List allowedAfter) throws VcsException { @@ -117,7 +116,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change s1Change = assertMovedChange(tree.myS1File); final Change s2Change = assertMovedChange(tree.myS2File); - rollbackIMpl(Collections.singletonList(change), Collections.emptyList()); + rollbackIMpl(Collections.singletonList(change), Collections.emptyList()); } @Test @@ -142,7 +141,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(!FileUtil.filesEqual(new File(unv.getPath()), wasUnversioned)); Assert.assertTrue(! wasUnversioned.exists()); - rollbackIMpl(Arrays.asList(change, s2Change), Collections.emptyList()); + rollbackIMpl(Arrays.asList(change, s2Change), Collections.emptyList()); Assert.assertTrue(wasUnversioned.exists()); } @@ -174,7 +173,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(!FileUtil.filesEqual(new File(deepUnverioned.getPath()), was)); Assert.assertTrue(! was.exists()); - rollbackIMpl(Arrays.asList(change), Collections.emptyList()); + rollbackIMpl(Arrays.asList(change), Collections.emptyList()); Assert.assertTrue(was.exists()); } @@ -310,13 +309,10 @@ public class SvnRollbackTest extends Svn17TestCase { private void setProperty(final File file, final String name, final String value) throws SVNException { final SVNWCClient client = myVcs.getSvnKitManager().createWCClient(); - client.doSetProperty(file, new ISVNPropertyValueProvider() { - @Override - public SVNProperties providePropertyValues(File path, SVNProperties properties) throws SVNException { - final SVNProperties result = new SVNProperties(); - result.put(name, SVNPropertyValue.create(value)); - return result; - } + client.doSetProperty(file, (path, properties) -> { + final SVNProperties result = new SVNProperties(); + result.put(name, SVNPropertyValue.create(value)); + return result; }, true, SVNDepth.EMPTY, null, null); } @@ -336,7 +332,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change change = assertDeletedChange(fpSource); final Change t11Change = assertDeletedChange(fpT11); - rollbackIMpl(Arrays.asList(change, t11Change), Collections.emptyList()); + rollbackIMpl(Arrays.asList(change, t11Change), Collections.emptyList()); } private Change assertDeletedChange(FilePath fpSource) { @@ -363,7 +359,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change inNewDirChange = assertCreatedChange(inNewDir); final Change inSourceChange = assertCreatedChange(inSource); - rollbackIMpl(Arrays.asList(change, inSourceChange), Collections.emptyList()); + rollbackIMpl(Arrays.asList(change, inSourceChange), Collections.emptyList()); } private Change assertCreatedChange(VirtualFile newDir) { @@ -436,7 +432,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(! wasIgnored.exists()); Assert.assertTrue(FileStatus.IGNORED.equals(myChangeListManager.getStatus(ignored))); - rollbackIMpl(Collections.singletonList(dirChange), Collections.emptyList()); + rollbackIMpl(Collections.singletonList(dirChange), Collections.emptyList()); ignored = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(wasIgnored); // ignored property was not committed Assert.assertTrue(FileStatus.UNKNOWN.equals(myChangeListManager.getStatus(ignored))); @@ -470,7 +466,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(! wasIgnored.exists()); Assert.assertTrue(FileStatus.IGNORED.equals(myChangeListManager.getStatus(ignored))); - rollbackIMpl(Collections.singletonList(dirChange), Collections.emptyList()); + rollbackIMpl(Collections.singletonList(dirChange), Collections.emptyList()); ignored = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(wasIgnored); // ignored property was not committed Assert.assertTrue(FileStatus.IGNORED.equals(myChangeListManager.getStatus(ignored))); @@ -494,7 +490,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change s1Change = assertMovedChange(tree.myS1File); final Change s2Change = assertMovedChange(tree.myS2File); - rollbackIMpl(Arrays.asList(dirChange, s1Change, s2Change), Collections.emptyList()); + rollbackIMpl(Arrays.asList(dirChange, s1Change, s2Change), Collections.emptyList()); } @Test @@ -537,7 +533,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(deletedFiles.size() == 1); Assert.assertEquals(wasFile, deletedFiles.get(0).getPath().getIOFile()); - rollbackLocallyDeleted(Collections.singletonList(deletedFiles.get(0).getPath()), Collections.emptyList()); + rollbackLocallyDeleted(Collections.singletonList(deletedFiles.get(0).getPath()), Collections.emptyList()); } @Test @@ -567,7 +563,7 @@ public class SvnRollbackTest extends Svn17TestCase { } Assert.assertTrue(files.isEmpty()); - rollbackLocallyDeleted(Collections.singletonList(VcsUtil.getFilePath(wasFile, true)), Collections.emptyList()); + rollbackLocallyDeleted(Collections.singletonList(VcsUtil.getFilePath(wasFile, true)), Collections.emptyList()); } @Test @@ -608,7 +604,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(files.contains(deletedFiles.get(1).getPath().getIOFile())); Assert.assertTrue(files.contains(deletedFiles.get(2).getPath().getIOFile())); - rollbackLocallyDeleted(Arrays.asList(VcsUtil.getFilePath(wasFile2, true), VcsUtil.getFilePath(wasFile1, false)), Collections.emptyList()); + rollbackLocallyDeleted(Arrays.asList(VcsUtil.getFilePath(wasFile2, true), VcsUtil.getFilePath(wasFile1, false)), Collections.emptyList()); } @Test @@ -639,7 +635,7 @@ public class SvnRollbackTest extends Svn17TestCase { "D root" + File.separator + "source" + File.separator + "s2.txt" ); - rollbackLocallyDeleted(Collections.singletonList(VcsUtil.getFilePath(was, true)), Collections.emptyList()); + rollbackLocallyDeleted(Collections.singletonList(VcsUtil.getFilePath(was, true)), Collections.emptyList()); runAndVerifyStatusSorted("D root" + File.separator + "source", "D root" + File.separator + "source" + File.separator + "s1.txt", "D root" + File.separator + "source" + File.separator + "s2.txt"); diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/IgnoredFilesTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/IgnoredFilesTest.java index 0db6c11facee..10c31912e466 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/IgnoredFilesTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/IgnoredFilesTest.java @@ -52,57 +52,51 @@ public class IgnoredFilesTest extends Svn16TestCase { @Before public void setUp() throws Exception { - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); - myTempDirFixture = fixtureFactory.createTempDirTestFixture(); - myTempDirFixture.setUp(); + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + try { + final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); + myTempDirFixture = fixtureFactory.createTempDirTestFixture(); + myTempDirFixture.setUp(); - myClientRoot = new File(myTempDirFixture.getTempDirPath(), "clientroot"); - myClientRoot.mkdir(); + myClientRoot = new File(myTempDirFixture.getTempDirPath(), "clientroot"); + myClientRoot.mkdir(); - initProject(myClientRoot, IgnoredFilesTest.this.getTestName()); + initProject(myClientRoot, IgnoredFilesTest.this.getTestName()); - ((StartupManagerImpl)StartupManager.getInstance(myProject)).runPostStartupActivities(); + ((StartupManagerImpl)StartupManager.getInstance(myProject)).runPostStartupActivities(); - myChangeListManager = ChangeListManager.getInstance(myProject); - myVcs = SvnVcs.getInstance(myProject); - myVcsManager = (ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(myProject); - myVcsManager.registerVcs(myVcs); - myVcsManager.setDirectoryMapping(myWorkingCopyDir.getPath(), myVcs.getName()); + myChangeListManager = ChangeListManager.getInstance(myProject); + myVcs = SvnVcs.getInstance(myProject); + myVcsManager = (ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(myProject); + myVcsManager.registerVcs(myVcs); + myVcsManager.setDirectoryMapping(myWorkingCopyDir.getPath(), myVcs.getName()); - myVcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject); - myLocalFileSystem = LocalFileSystem.getInstance(); - } - catch (Exception e) { - throw new RuntimeException(e); - } + myVcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject); + myLocalFileSystem = LocalFileSystem.getInstance(); + } + catch (Exception e) { + throw new RuntimeException(e); } }); } @After public void tearDown() throws Exception { - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - myVcsManager.unregisterVcs(myVcs); - myVcsManager = null; - myVcs = null; + UIUtil.invokeAndWaitIfNeeded((Runnable)() -> { + try { + myVcsManager.unregisterVcs(myVcs); + myVcsManager = null; + myVcs = null; - tearDownProject(); - if (myTempDirFixture != null) { - myTempDirFixture.tearDown(); - myTempDirFixture = null; - } - FileUtil.delete(myClientRoot); - } - catch (Exception e) { - throw new RuntimeException(e); + tearDownProject(); + if (myTempDirFixture != null) { + myTempDirFixture.tearDown(); + myTempDirFixture = null; } + FileUtil.delete(myClientRoot); + } + catch (Exception e) { + throw new RuntimeException(e); } }); } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnAnnotationIsClosedTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnAnnotationIsClosedTest.java index ef2cf16793e8..36dbe74a0563 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnAnnotationIsClosedTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnAnnotationIsClosedTest.java @@ -76,12 +76,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); @@ -115,12 +112,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); @@ -143,12 +137,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); VcsTestUtil.editFileInCommand(myProject, tree.myS1File, "1+\n2\n3\n4\n"); @@ -173,12 +164,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); VcsTestUtil.editFileInCommand(myProject, tree.myS1File, "1+\n2\n3\n4\n"); @@ -208,12 +196,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); @@ -240,12 +225,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); @@ -268,12 +250,9 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), tree.myS1File); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(tree.myS1File, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(tree.myS1File, annotation); }); listener.registerAnnotation(tree.myS1File, annotation); VcsTestUtil.editFileInCommand(myProject, tree.myS1File, "1+\n2\n3\n4\n"); @@ -339,22 +318,16 @@ public class SvnAnnotationIsClosedTest extends Svn17TestCase { // then annotate both final VcsAnnotationLocalChangesListener listener = ProjectLevelVcsManager.getInstance(myProject).getAnnotationLocalChangesListener(); final FileAnnotation annotation = createTestAnnotation(myVcs.getAnnotationProvider(), vf1); - annotation.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed = true; - listener.unregisterAnnotation(vf1, annotation); - } + annotation.setCloser(() -> { + myIsClosed = true; + listener.unregisterAnnotation(vf1, annotation); }); listener.registerAnnotation(vf1, annotation); final FileAnnotation annotation1 = createTestAnnotation(myVcs.getAnnotationProvider(), vf2); - annotation1.setCloser(new Runnable() { - @Override - public void run() { - myIsClosed1 = true; - listener.unregisterAnnotation(vf1, annotation1); - } + annotation1.setCloser(() -> { + myIsClosed1 = true; + listener.unregisterAnnotation(vf1, annotation1); }); listener.registerAnnotation(vf1, annotation1); diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnCachingRevisionsTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnCachingRevisionsTest.java index fcf331d5c076..ef9ce40521f7 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnCachingRevisionsTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnCachingRevisionsTest.java @@ -220,7 +220,7 @@ public class SvnCachingRevisionsTest extends CodeInsightFixtureTestCase { } public void testJustLiveProvider() throws Exception { - performTest(11, 2, null, Collections.>emptyList(), 121); + performTest(11, 2, null, Collections.emptyList(), 121); } public void testLiveAndSimpleInternalProvider() throws Exception { @@ -231,7 +231,7 @@ public class SvnCachingRevisionsTest extends CodeInsightFixtureTestCase { public void testLiveAndSimpleCommittedProvider() throws Exception { for (int i = 0; i < 2 * PAGE; i+=2) { - performTest(11, 2, new Pair<>(19L, 117L), Collections.>emptyList(), 121 + i); + performTest(11, 2, new Pair<>(19L, 117L), Collections.emptyList(), 121 + i); } } @@ -260,7 +260,7 @@ public class SvnCachingRevisionsTest extends CodeInsightFixtureTestCase { } public void testShortLive() throws Exception { - performTest(11, 2, null, Collections.>emptyList(), 13); + performTest(11, 2, null, Collections.emptyList(), 13); } public void testShortInternal() throws Exception { @@ -268,7 +268,7 @@ public class SvnCachingRevisionsTest extends CodeInsightFixtureTestCase { } public void testShortCommitted() throws Exception { - performTest(11, 2, new Pair<>(11L, 15L), Collections.>emptyList(), 15); + performTest(11, 2, new Pair<>(11L, 15L), Collections.emptyList(), 15); } public void testThreeByOne() throws Exception { diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnConcurrentChangeListManagerTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnConcurrentChangeListManagerTest.java index 60dfd08119ae..31b3c122bb29 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnConcurrentChangeListManagerTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnConcurrentChangeListManagerTest.java @@ -53,12 +53,9 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { final String newName = "renamed"; - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.editName(list.getName(), newName); - checkFilesAreInList(new VirtualFile[] {file}, newName, changeListManager); - } + myScheme.doTest(() -> { + changeListManager.editName(list.getName(), newName); + checkFilesAreInList(new VirtualFile[] {file}, newName, changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, newName, changeListManager); @@ -80,15 +77,12 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty(); changeListManager.ensureUpToDate(false); - final Runnable check = new Runnable() { - @Override - public void run() { - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myS1File)); - Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File)); - Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir)); - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir)); - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1))); - } + final Runnable check = () -> { + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myS1File)); + Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File)); + Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir)); + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir)); + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1))); }; myScheme.doTest(check); @@ -99,15 +93,12 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty(); changeListManager.ensureUpToDate(false); - final Runnable check2 = new Runnable() { - @Override - public void run() { - Assert.assertEquals(FileStatus.MODIFIED, changeListManager.getStatus(tree.myS1File)); - Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File)); - Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir)); - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir)); - Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1))); - } + final Runnable check2 = () -> { + Assert.assertEquals(FileStatus.MODIFIED, changeListManager.getStatus(tree.myS1File)); + Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.myS2File)); + Assert.assertEquals(FileStatus.NOT_CHANGED, changeListManager.getStatus(tree.mySourceDir)); + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetDir)); + Assert.assertEquals(FileStatus.SWITCHED, changeListManager.getStatus(tree.myTargetFiles.get(1))); }; myScheme.doTest(check2); @@ -128,19 +119,16 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { final String finalText = "final text"; - myScheme.doTest(new Runnable() { - @Override - public void run() { - final String intermediate = "intermediate text"; - changeListManager.editComment(list.getName(), intermediate); - assert changeListManager.findChangeList(listName) != null; - LocalChangeList list = changeListManager.findChangeList(listName); - assert intermediate.equals(list.getComment()); + myScheme.doTest(() -> { + final String intermediate = "intermediate text"; + changeListManager.editComment(list.getName(), intermediate); + assert changeListManager.findChangeList(listName) != null; + LocalChangeList list1 = changeListManager.findChangeList(listName); + assert intermediate.equals(list1.getComment()); - changeListManager.editComment(list.getName(), finalText); - list = changeListManager.findChangeList(listName); - assert finalText.equals(list.getComment()); - } + changeListManager.editComment(list1.getName(), finalText); + list1 = changeListManager.findChangeList(listName); + assert finalText.equals(list1.getComment()); }); LocalChangeList changedList = changeListManager.findChangeList(listName); @@ -162,12 +150,9 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { final LocalChangeList target = changeListManager.addChangeList("target", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); - } + myScheme.doTest(() -> { + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); @@ -187,12 +172,9 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { final LocalChangeList target = changeListManager.addChangeList("target", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.setDefaultChangeList(target); - assert changeListManager.getDefaultChangeList().getName().equals(target.getName()); - } + myScheme.doTest(() -> { + changeListManager.setDefaultChangeList(target); + assert changeListManager.getDefaultChangeList().getName().equals(target.getName()); }); assert changeListManager.getDefaultChangeList().getName().equals(target.getName()); @@ -212,13 +194,10 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { final LocalChangeList list = changeListManager.addChangeList("test", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.removeChangeList(list.getName()); - assert changeListManager.findChangeList(list.getName()) == null; - checkFilesAreInList(new VirtualFile[] {file, fileB}, myDefaulListName, changeListManager); - } + myScheme.doTest(() -> { + changeListManager.removeChangeList(list.getName()); + assert changeListManager.findChangeList(list.getName()) == null; + checkFilesAreInList(new VirtualFile[] {file, fileB}, myDefaulListName, changeListManager); }); assert changeListManager.findChangeList(list.getName()) == null; @@ -241,14 +220,11 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { final LocalChangeList target2 = changeListManager.addChangeList("target2", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); - changeListManager.moveChangesTo(target2, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, target2.getName(), changeListManager); - } + myScheme.doTest(() -> { + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); + changeListManager.moveChangesTo(target2, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, target2.getName(), changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, target2.getName(), changeListManager); @@ -268,14 +244,11 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { final LocalChangeList target = changeListManager.addChangeList("target", null); changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - myScheme.doTest(new Runnable() { - @Override - public void run() { - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); - changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, list.getName(), changeListManager); - } + myScheme.doTest(() -> { + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, target.getName(), changeListManager); + changeListManager.moveChangesTo(list, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, list.getName(), changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, list.getName(), changeListManager); @@ -296,13 +269,10 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { final String targetName = "target"; - myScheme.doTest(new Runnable() { - @Override - public void run() { - final LocalChangeList target = changeListManager.addChangeList(targetName, null); - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); - checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager); - } + myScheme.doTest(() -> { + final LocalChangeList target = changeListManager.addChangeList(targetName, null); + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file)}); + checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager); }); checkFilesAreInList(new VirtualFile[] {file}, targetName, changeListManager); @@ -345,21 +315,18 @@ public class SvnConcurrentChangeListManagerTest extends Svn16TestCase { final String targetName = "target"; final String finalName = "final list name"; - myScheme.doTest(new Runnable() { - @Override - public void run() { - final LocalChangeList target = changeListManager.addChangeList(targetName, null); - changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file), changeListManager.getChange(fileB)}); - checkFilesAreInList(new VirtualFile[] {file, fileB}, targetName, changeListManager); - changeListManager.editName(targetName, finalName); - checkFilesAreInList(new VirtualFile[] {file, fileB}, finalName, changeListManager); - changeListManager.removeChangeList(toBeDeletedList.getName()); - checkFilesAreInList(new VirtualFile[] {fileC, fileD}, myDefaulListName, changeListManager); - changeListManager.moveChangesTo(LocalChangeList.createEmptyChangeList(myProject, finalName), - new Change[] {changeListManager.getChange(fileC)}); - checkFilesAreInList(new VirtualFile[] {file, fileB, fileC}, finalName, changeListManager); - checkFilesAreInList(new VirtualFile[] {fileD}, myDefaulListName, changeListManager); - } + myScheme.doTest(() -> { + final LocalChangeList target = changeListManager.addChangeList(targetName, null); + changeListManager.moveChangesTo(target, new Change[] {changeListManager.getChange(file), changeListManager.getChange(fileB)}); + checkFilesAreInList(new VirtualFile[] {file, fileB}, targetName, changeListManager); + changeListManager.editName(targetName, finalName); + checkFilesAreInList(new VirtualFile[] {file, fileB}, finalName, changeListManager); + changeListManager.removeChangeList(toBeDeletedList.getName()); + checkFilesAreInList(new VirtualFile[] {fileC, fileD}, myDefaulListName, changeListManager); + changeListManager.moveChangesTo(LocalChangeList.createEmptyChangeList(myProject, finalName), + new Change[] {changeListManager.getChange(fileC)}); + checkFilesAreInList(new VirtualFile[] {file, fileB, fileC}, finalName, changeListManager); + checkFilesAreInList(new VirtualFile[] {fileD}, myDefaulListName, changeListManager); }); checkFilesAreInList(new VirtualFile[] {file, fileB, fileC}, finalName, changeListManager); diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnMergeInfoTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnMergeInfoTest.java index 044b6c1609c4..87aaaaa294c7 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnMergeInfoTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnMergeInfoTest.java @@ -104,7 +104,7 @@ public class SvnMergeInfoTest extends Svn16TestCase { enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); final String repoUrl = SVNURL.parseURIDecoded(myRepoUrl).toString(); - myWCInfoWithBranches = new WCInfoWithBranches(myWCInfo, Collections.emptyList(), vcsRoot, + myWCInfoWithBranches = new WCInfoWithBranches(myWCInfo, Collections.emptyList(), vcsRoot, new WCInfoWithBranches.Branch(repoUrl + "/trunk")); myMergeChecker = new BranchInfo(myVcs, myWCInfoWithBranches, new WCInfoWithBranches.Branch(repoUrl + "/branch")); } diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnRollbackTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnRollbackTest.java index 1ec139c92ea6..72331ad427ca 100644 --- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnRollbackTest.java +++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn16/SvnRollbackTest.java @@ -33,7 +33,6 @@ import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; -import org.tmatesoft.svn.core.wc.ISVNPropertyValueProvider; import org.tmatesoft.svn.core.wc.SVNPropertyData; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCClient; @@ -78,7 +77,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change change = myChangeListManager.getChange(a); Assert.assertNotNull(change); - rollbackIMpl(Collections.singletonList(change), Collections.emptyList()); + rollbackIMpl(Collections.singletonList(change), Collections.emptyList()); } private void rollbackIMpl(List changes, final List allowedAfter) throws VcsException { @@ -119,7 +118,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change s1Change = assertMovedChange(tree.myS1File); final Change s2Change = assertMovedChange(tree.myS2File); - rollbackIMpl(Collections.singletonList(change), Collections.emptyList()); + rollbackIMpl(Collections.singletonList(change), Collections.emptyList()); } @Test @@ -144,7 +143,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(!FileUtil.filesEqual(new File(unv.getPath()), wasUnversioned)); Assert.assertTrue(! wasUnversioned.exists()); - rollbackIMpl(Arrays.asList(change, s2Change), Collections.emptyList()); + rollbackIMpl(Arrays.asList(change, s2Change), Collections.emptyList()); Assert.assertTrue(wasUnversioned.exists()); } @@ -176,7 +175,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(!FileUtil.filesEqual(new File(deepUnverioned.getPath()), was)); Assert.assertTrue(! was.exists()); - rollbackIMpl(Arrays.asList(change), Collections.emptyList()); + rollbackIMpl(Arrays.asList(change), Collections.emptyList()); Assert.assertTrue(was.exists()); } @@ -312,13 +311,10 @@ public class SvnRollbackTest extends Svn17TestCase { private void setProperty(final File file, final String name, final String value) throws SVNException { final SVNWCClient client = myVcs.getSvnKitManager().createWCClient(); - client.doSetProperty(file, new ISVNPropertyValueProvider() { - @Override - public SVNProperties providePropertyValues(File path, SVNProperties properties) throws SVNException { - final SVNProperties result = new SVNProperties(); - result.put(name, SVNPropertyValue.create(value)); - return result; - } + client.doSetProperty(file, (path, properties) -> { + final SVNProperties result = new SVNProperties(); + result.put(name, SVNPropertyValue.create(value)); + return result; }, true, SVNDepth.EMPTY, null, null); } @@ -338,7 +334,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change change = assertDeletedChange(fpSource); final Change t11Change = assertDeletedChange(fpT11); - rollbackIMpl(Arrays.asList(change, t11Change), Collections.emptyList()); + rollbackIMpl(Arrays.asList(change, t11Change), Collections.emptyList()); } private Change assertDeletedChange(FilePath fpSource) { @@ -365,7 +361,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change inNewDirChange = assertCreatedChange(inNewDir); final Change inSourceChange = assertCreatedChange(inSource); - rollbackIMpl(Arrays.asList(change, inSourceChange), Collections.emptyList()); + rollbackIMpl(Arrays.asList(change, inSourceChange), Collections.emptyList()); } private Change assertCreatedChange(VirtualFile newDir) { @@ -438,7 +434,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(! wasIgnored.exists()); Assert.assertTrue(FileStatus.IGNORED.equals(myChangeListManager.getStatus(ignored))); - rollbackIMpl(Collections.singletonList(dirChange), Collections.emptyList()); + rollbackIMpl(Collections.singletonList(dirChange), Collections.emptyList()); ignored = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(wasIgnored); // ignored property was not committed Assert.assertTrue(FileStatus.UNKNOWN.equals(myChangeListManager.getStatus(ignored))); @@ -472,7 +468,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(! wasIgnored.exists()); Assert.assertTrue(FileStatus.IGNORED.equals(myChangeListManager.getStatus(ignored))); - rollbackIMpl(Collections.singletonList(dirChange), Collections.emptyList()); + rollbackIMpl(Collections.singletonList(dirChange), Collections.emptyList()); ignored = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(wasIgnored); // ignored property was not committed Assert.assertTrue(FileStatus.IGNORED.equals(myChangeListManager.getStatus(ignored))); @@ -496,7 +492,7 @@ public class SvnRollbackTest extends Svn17TestCase { final Change s1Change = assertMovedChange(tree.myS1File); final Change s2Change = assertMovedChange(tree.myS2File); - rollbackIMpl(Arrays.asList(dirChange, s1Change, s2Change), Collections.emptyList()); + rollbackIMpl(Arrays.asList(dirChange, s1Change, s2Change), Collections.emptyList()); } @Test @@ -539,7 +535,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(deletedFiles.size() == 1); Assert.assertEquals(wasFile, deletedFiles.get(0).getPath().getIOFile()); - rollbackLocallyDeleted(Collections.singletonList(deletedFiles.get(0).getPath()), Collections.emptyList()); + rollbackLocallyDeleted(Collections.singletonList(deletedFiles.get(0).getPath()), Collections.emptyList()); } @Test @@ -569,7 +565,7 @@ public class SvnRollbackTest extends Svn17TestCase { } Assert.assertTrue(files.isEmpty()); - rollbackLocallyDeleted(Collections.singletonList(VcsUtil.getFilePath(wasFile, true)), Collections.emptyList()); + rollbackLocallyDeleted(Collections.singletonList(VcsUtil.getFilePath(wasFile, true)), Collections.emptyList()); } @Test @@ -610,7 +606,7 @@ public class SvnRollbackTest extends Svn17TestCase { Assert.assertTrue(files.contains(deletedFiles.get(1).getPath().getIOFile())); Assert.assertTrue(files.contains(deletedFiles.get(2).getPath().getIOFile())); - rollbackLocallyDeleted(Arrays.asList(VcsUtil.getFilePath(wasFile2, true), VcsUtil.getFilePath(wasFile1, false)), Collections.emptyList()); + rollbackLocallyDeleted(Arrays.asList(VcsUtil.getFilePath(wasFile2, true), VcsUtil.getFilePath(wasFile1, false)), Collections.emptyList()); } @Test @@ -641,7 +637,7 @@ public class SvnRollbackTest extends Svn17TestCase { "D root" + File.separator + "source" + File.separator + "s2.txt" ); - rollbackLocallyDeleted(Collections.singletonList(VcsUtil.getFilePath(was, true)), Collections.emptyList()); + rollbackLocallyDeleted(Collections.singletonList(VcsUtil.getFilePath(was, true)), Collections.emptyList()); runAndVerifyStatusSorted("D root" + File.separator + "source", "D root" + File.separator + "source" + File.separator + "s1.txt", "D root" + File.separator + "source" + File.separator + "s2.txt"); diff --git a/python/educational-core/course-creator/course-creator.iml b/python/educational-core/course-creator/course-creator.iml index 7f8af6dd20f2..53e3680ba045 100644 --- a/python/educational-core/course-creator/course-creator.iml +++ b/python/educational-core/course-creator/course-creator.iml @@ -15,5 +15,6 @@ + \ No newline at end of file diff --git a/python/educational-core/course-creator/resources/META-INF/course-creator-intellij.xml b/python/educational-core/course-creator/resources/META-INF/course-creator-intellij.xml new file mode 100644 index 000000000000..8494fe25521b --- /dev/null +++ b/python/educational-core/course-creator/resources/META-INF/course-creator-intellij.xml @@ -0,0 +1,6 @@ + + JUnit + + + + \ No newline at end of file diff --git a/python/educational-core/course-creator/resources/META-INF/plugin.xml b/python/educational-core/course-creator/resources/META-INF/plugin.xml index e508efb886cf..ede2dfb83d31 100644 --- a/python/educational-core/course-creator/resources/META-INF/plugin.xml +++ b/python/educational-core/course-creator/resources/META-INF/plugin.xml @@ -14,6 +14,7 @@ com.intellij.modules.platform com.jetbrains.edu.interactivelearning + com.intellij.modules.java @@ -46,6 +47,12 @@ + + + + + + diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateLesson.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateLesson.java index 6952f319dcf7..c8af14b57077 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateLesson.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateLesson.java @@ -8,6 +8,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiManager; import com.intellij.util.Function; +import com.jetbrains.edu.coursecreator.creation.CCLessonCreator; import com.jetbrains.edu.learning.core.EduNames; import com.jetbrains.edu.learning.courseFormat.Course; import com.jetbrains.edu.learning.courseFormat.Lesson; @@ -51,6 +52,10 @@ public class CCCreateLesson extends CCCreateStudyItemActionBase { protected PsiDirectory createItemDir(@NotNull final Project project, @NotNull final StudyItem item, @Nullable final IdeView view, @NotNull final PsiDirectory parentDirectory, @NotNull final Course course) { + CCLessonCreator creator = CCLessonCreator.INSTANCE.forLanguage(course.getLanguageById()); + if (creator != null) { + return creator.createLesson(project, item, view, parentDirectory, course); + } final PsiDirectory[] lessonDirectory = new PsiDirectory[1]; ApplicationManager.getApplication().runWriteAction(() -> { lessonDirectory[0] = DirectoryUtil.createSubdirectories(EduNames.LESSON + item.getIndex(), parentDirectory, "\\/"); diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateTask.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateTask.java index 6b4201b22452..6ae62ecd7272 100644 --- a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateTask.java +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCCreateTask.java @@ -9,6 +9,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.util.Function; import com.jetbrains.edu.coursecreator.CCUtils; +import com.jetbrains.edu.coursecreator.creation.CCTaskCreator; import com.jetbrains.edu.learning.core.EduNames; import com.jetbrains.edu.learning.core.EduUtils; import com.jetbrains.edu.learning.courseFormat.Course; @@ -64,7 +65,10 @@ public class CCCreateTask extends CCCreateStudyItemActionBase { protected PsiDirectory createItemDir(@NotNull final Project project, @NotNull final StudyItem item, @Nullable final IdeView view, @NotNull final PsiDirectory parentDirectory, @NotNull final Course course) { - + CCTaskCreator creator = CCTaskCreator.INSTANCE.forLanguage(course.getLanguageById()); + if (creator != null) { + return creator.createTask(project, item, view, parentDirectory, course); + } final Ref taskDirectory = new Ref<>(); ApplicationManager.getApplication().runWriteAction(() -> { String taskDirName = EduNames.TASK + item.getIndex(); diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/creation/CCLessonCreator.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/creation/CCLessonCreator.java new file mode 100644 index 000000000000..28ca6e7d25ac --- /dev/null +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/creation/CCLessonCreator.java @@ -0,0 +1,18 @@ +package com.jetbrains.edu.coursecreator.creation; + +import com.intellij.ide.IdeView; +import com.intellij.lang.LanguageExtension; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiDirectory; +import com.jetbrains.edu.learning.courseFormat.Course; +import com.jetbrains.edu.learning.courseFormat.StudyItem; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface CCLessonCreator { + LanguageExtension INSTANCE = new LanguageExtension<>("Edu.CCLessonCreator"); + + PsiDirectory createLesson(@NotNull final Project project, @NotNull final StudyItem item, + @Nullable final IdeView view, @NotNull final PsiDirectory parentDirectory, + @NotNull final Course course); +} diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/creation/CCTaskCreator.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/creation/CCTaskCreator.java new file mode 100644 index 000000000000..a4591e1577f1 --- /dev/null +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/creation/CCTaskCreator.java @@ -0,0 +1,18 @@ +package com.jetbrains.edu.coursecreator.creation; + +import com.intellij.ide.IdeView; +import com.intellij.lang.LanguageExtension; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiDirectory; +import com.jetbrains.edu.learning.courseFormat.Course; +import com.jetbrains.edu.learning.courseFormat.StudyItem; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface CCTaskCreator { + LanguageExtension INSTANCE = new LanguageExtension<>("Edu.CCTaskCreator"); + + PsiDirectory createTask(@NotNull final Project project, @NotNull final StudyItem item, + @Nullable final IdeView view, @NotNull final PsiDirectory parentDirectory, + @NotNull final Course course); +} diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/intellij/EduCCModuleBuilder.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/intellij/EduCCModuleBuilder.java new file mode 100644 index 000000000000..eba21f6aee29 --- /dev/null +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/intellij/EduCCModuleBuilder.java @@ -0,0 +1,153 @@ +package com.jetbrains.edu.coursecreator.intellij; + +import com.intellij.ide.util.projectWizard.ModuleWizardStep; +import com.intellij.ide.util.projectWizard.ProjectWizardStepFactory; +import com.intellij.ide.util.projectWizard.SettingsStep; +import com.intellij.ide.util.projectWizard.WizardInputField; +import com.intellij.lang.Language; +import com.intellij.lang.LanguageExtensionPoint; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.extensions.ExtensionPointName; +import com.intellij.openapi.module.ModifiableModuleModel; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleWithNameAlreadyExists; +import com.intellij.openapi.options.ConfigurationException; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.roots.ModifiableRootModel; +import com.intellij.openapi.ui.ComboBox; +import com.intellij.openapi.util.Conditions; +import com.intellij.openapi.util.InvalidDataException; +import com.jetbrains.edu.coursecreator.CCUtils; +import com.jetbrains.edu.coursecreator.ui.CCNewProjectPanel; +import com.jetbrains.edu.learning.StudyTaskManager; +import com.jetbrains.edu.learning.courseFormat.Course; +import com.jetbrains.edu.learning.courseFormat.Lesson; +import com.jetbrains.edu.learning.courseFormat.Task; +import com.jetbrains.edu.learning.courseGeneration.StudyProjectGenerator; +import com.jetbrains.edu.learning.intellij.EduCourseConfigurator; +import com.jetbrains.edu.learning.intellij.generation.EduCourseModuleBuilder; +import org.jdom.JDOMException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import javax.swing.text.JTextComponent; +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.function.Function; + +class EduCCModuleBuilder extends EduCourseModuleBuilder { + private CCNewProjectPanel myPanel = new CCNewProjectPanel(); + private ComboBox myLanguageComboBox = new ComboBox(); + private static final Logger LOG = Logger.getInstance(EduCCModuleBuilder.class); + + @Nullable + @Override + public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) { + ModuleWizardStep javaSettingsStep = + ProjectWizardStepFactory.getInstance().createJavaSettingsStep(settingsStep, this, Conditions.alwaysTrue()); + Function getValue = JTextComponent::getText; + getWizardInputField("ccname", "", "Name:", myPanel.getNameField(), getValue).addToSettings(settingsStep); + getWizardInputField("ccauthor", "", "Author:", myPanel.getAuthorField(), getValue).addToSettings(settingsStep); + + LanguageExtensionPoint[] extensions = new ExtensionPointName(EduCourseConfigurator.EP_NAME).getExtensions(); + + myLanguageComboBox.removeAllItems(); + for (LanguageExtensionPoint extension : extensions) { + String languageId = extension.getKey(); + Language language = Language.findLanguageByID(languageId); + if (language == null) { + LOG.info("Language with id " + languageId + " not found"); + } + myLanguageComboBox.addItem(new LanguageWrapper(language)); + } + getWizardInputField("cclang", "", "Language:", myLanguageComboBox, comboBox -> (String)comboBox.getSelectedItem()) + .addToSettings(settingsStep); + getWizardInputField("ccdescr", "", "Description:", myPanel.getDescriptionField(), JTextArea::getText).addToSettings(settingsStep); + return javaSettingsStep; + } + + @Override + public void setupRootModel(ModifiableRootModel rootModel) throws ConfigurationException { + setSourcePaths(Collections.emptyList()); + super.setupRootModel(rootModel); + } + + + @NotNull + @Override + public Module createModule(@NotNull ModifiableModuleModel moduleModel) + throws InvalidDataException, IOException, ModuleWithNameAlreadyExists, + JDOMException, ConfigurationException { + Module module = super.createModule(moduleModel); + Project project = module.getProject(); + final Course course = new Course(); + course.setName(myPanel.getName()); + course.setAuthorsAsString(myPanel.getAuthors()); + course.setDescription(myPanel.getDescription()); + LanguageWrapper wrapper = (LanguageWrapper)myLanguageComboBox.getSelectedItem(); + course.setLanguage(wrapper.getLanguage().getID()); + course.setCourseMode(CCUtils.COURSE_MODE); + File courseDir = new File(StudyProjectGenerator.OUR_COURSES_DIR, myPanel.getName() + "-" + project.getName()); + course.setCourseDirectory(courseDir.getPath()); + Lesson lesson = new Lesson(); + Task task = new Task(); + task.setName("task1"); + lesson.addTask(task); + lesson.setName("lesson1"); + course.addLesson(lesson); + course.initCourse(false); + StudyTaskManager.getInstance(project).setCourse(course); + EduCourseConfigurator configurator = EduCourseConfigurator.INSTANCE.forLanguage(wrapper.getLanguage()); + if (configurator == null) { + LOG.error("EduCourseConfigurator for language " + wrapper.getLanguage().getDisplayName() + " not found"); + return module; + } + configurator.configureModule(module); + configurator.createCourseModuleContent(moduleModel, project, course, getModuleFileDirectory()); + return module; + } + + @NotNull + private WizardInputField getWizardInputField(String id, + String defaultValue, + String label, + T component, + Function getValue) { + return new WizardInputField(id, defaultValue) { + @Override + public String getLabel() { + return label; + } + + @Override + public T getComponent() { + return component; + } + + @Override + public String getValue() { + return getValue.apply(component); + } + }; + } + + + private class LanguageWrapper { + private final Language myLanguage; + + LanguageWrapper(Language language) { + myLanguage = language; + } + + Language getLanguage() { + return myLanguage; + } + + @Override + public String toString() { + return myLanguage.getDisplayName(); + } + } +} diff --git a/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/intellij/EduCCProjectTemplate.java b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/intellij/EduCCProjectTemplate.java new file mode 100644 index 000000000000..3e6170c92f57 --- /dev/null +++ b/python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/intellij/EduCCProjectTemplate.java @@ -0,0 +1,41 @@ +package com.jetbrains.edu.coursecreator.intellij; + +import com.intellij.icons.AllIcons; +import com.intellij.ide.util.projectWizard.AbstractModuleBuilder; +import com.intellij.openapi.ui.ValidationInfo; +import com.jetbrains.edu.learning.intellij.EduIntelliJProjectTemplate; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; + +public class EduCCProjectTemplate implements EduIntelliJProjectTemplate { + @NotNull + @Override + public String getName() { + return "Create a new course"; + } + + @Nullable + @Override + public String getDescription() { + return "Assists in course creation"; + } + + @Override + public Icon getIcon() { + return AllIcons.Modules.Types.UserDefined; + } + + @NotNull + @Override + public AbstractModuleBuilder createModuleBuilder() { + return new EduCCModuleBuilder(); + } + + @Nullable + @Override + public ValidationInfo validateSettings() { + return null; + } +} diff --git a/python/educational-core/gradle.properties b/python/educational-core/gradle.properties index 47aa41bf7ea2..51ed727c2c73 100644 --- a/python/educational-core/gradle.properties +++ b/python/educational-core/gradle.properties @@ -1,6 +1,6 @@ ideaVersion IC-LATEST-TRUNK-SNAPSHOT downloadIdeaSources false -version 3.5.0 -buildNumber 162.1121.10 +version 4.0 +buildNumber 171 javaVersion 1.8 updateBuildNumber false \ No newline at end of file diff --git a/python/educational-core/student/resources/META-INF/android-dependencies.xml b/python/educational-core/student/resources/META-INF/android-dependencies.xml new file mode 100644 index 000000000000..6f04cfb24556 --- /dev/null +++ b/python/educational-core/student/resources/META-INF/android-dependencies.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/python/educational-core/student/resources/META-INF/edu-intellij.xml b/python/educational-core/student/resources/META-INF/edu-intellij.xml new file mode 100644 index 000000000000..4430d18b2802 --- /dev/null +++ b/python/educational-core/student/resources/META-INF/edu-intellij.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/python/educational-core/student/resources/META-INF/plugin.xml b/python/educational-core/student/resources/META-INF/plugin.xml index e66e65581561..ec049f945827 100644 --- a/python/educational-core/student/resources/META-INF/plugin.xml +++ b/python/educational-core/student/resources/META-INF/plugin.xml @@ -20,6 +20,8 @@ on how to target different products --> com.intellij.modules.lang + com.intellij.modules.androidstudio + com.intellij.modules.java @@ -35,6 +37,10 @@ + + + + diff --git a/python/educational-core/student/resources/fileTemplates/internal/EduTestRunner.java.ft b/python/educational-core/student/resources/fileTemplates/internal/EduTestRunner.java.ft new file mode 100644 index 000000000000..3d99c65140bd --- /dev/null +++ b/python/educational-core/student/resources/fileTemplates/internal/EduTestRunner.java.ft @@ -0,0 +1,18 @@ +import org.junit.runner.Description; +import org.junit.runner.JUnitCore; +import org.junit.runner.notification.Failure; +import org.junit.runner.notification.RunListener; + +public class EduTestRunner { + public static void main(String[] args) throws ClassNotFoundException { + Class testClass = EduTestRunner.class.getClassLoader().loadClass(args[0]); + JUnitCore runner = new JUnitCore(); + runner.addListener(new RunListener() { + @Override + public void testFailure(Failure failure) throws Exception { + System.out.println("#educational_plugin FAILED + " + failure.getMessage()); + } + }); + runner.run(testClass); + } +} \ No newline at end of file diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/EduCourseConfigurator.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/EduCourseConfigurator.java new file mode 100644 index 000000000000..8085c552e2a9 --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/EduCourseConfigurator.java @@ -0,0 +1,33 @@ +package com.jetbrains.edu.learning.intellij; + +import com.intellij.lang.LanguageExtension; +import com.intellij.openapi.module.ModifiableModuleModel; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.project.Project; +import com.jetbrains.edu.learning.courseFormat.Course; +import com.jetbrains.edu.learning.courseGeneration.StudyProjectGenerator; +import com.jetbrains.edu.learning.stepic.CourseInfo; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@SuppressWarnings("unused") //used in other educational plugins that are stored in separate repository +public interface EduCourseConfigurator { + String EP_NAME = "Edu.courseConfigurator"; + LanguageExtension INSTANCE = new LanguageExtension<>(EP_NAME); + + default void configureModule(@NotNull Module module) { + } + + default void createCourseFromCourseInfo(@NotNull ModifiableModuleModel moduleModel, + @NotNull Project project, + @NotNull StudyProjectGenerator generator, + @NotNull CourseInfo selectedCourse, + @Nullable String moduleDir) { + } + + default void createCourseModuleContent(@NotNull ModifiableModuleModel moduleModel, + @NotNull Project project, + @NotNull Course course, + @Nullable String moduleDir) { + } +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/EduIntelliJProjectTemplate.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/EduIntelliJProjectTemplate.java new file mode 100644 index 000000000000..bff27ad415c1 --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/EduIntelliJProjectTemplate.java @@ -0,0 +1,9 @@ +package com.jetbrains.edu.learning.intellij; + +import com.intellij.openapi.extensions.ExtensionPointName; +import com.intellij.platform.ProjectTemplate; + +public interface EduIntelliJProjectTemplate extends ProjectTemplate { + ExtensionPointName EP_NAME = + ExtensionPointName.create("Edu.eduIntelliJProjectTemplate"); +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/EduIntelliJTemplateFactory.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/EduIntelliJTemplateFactory.java new file mode 100644 index 000000000000..48e9ce41923b --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/EduIntelliJTemplateFactory.java @@ -0,0 +1,33 @@ +package com.jetbrains.edu.learning.intellij; + +import com.intellij.icons.AllIcons; +import com.intellij.ide.util.projectWizard.WizardContext; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.platform.ProjectTemplate; +import com.intellij.platform.ProjectTemplatesFactory; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; + +@SuppressWarnings("unused") //used in other educational plugins that are stored in separate repository +public class EduIntelliJTemplateFactory extends ProjectTemplatesFactory { + private static final String GROUP_NAME = "Education"; + + @NotNull + @Override + public String[] getGroups() { + return new String[]{GROUP_NAME}; + } + + @NotNull + @Override + public ProjectTemplate[] createTemplates(@Nullable String group, WizardContext context) { + return ApplicationManager.getApplication().getExtensions(EduIntelliJProjectTemplate.EP_NAME); + } + + @Override + public Icon getGroupIcon(String group) { + return AllIcons.Modules.Types.UserDefined; + } +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/android/EduSelectCourseProjectWizard.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/android/EduSelectCourseProjectWizard.java new file mode 100644 index 000000000000..bf580ac678e1 --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/android/EduSelectCourseProjectWizard.java @@ -0,0 +1,61 @@ +package com.jetbrains.edu.learning.intellij.android; + +import com.intellij.ide.projectWizard.ProjectSettingsStep; +import com.intellij.ide.projectWizard.ProjectTemplateList; +import com.intellij.ide.util.newProjectWizard.AbstractProjectWizard; +import com.intellij.ide.util.newProjectWizard.StepSequence; +import com.intellij.ide.util.projectWizard.ModuleWizardStep; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.roots.ui.configuration.ModulesProvider; +import com.intellij.platform.ProjectTemplate; +import com.jetbrains.edu.learning.intellij.EduIntelliJProjectTemplate; + +import javax.swing.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +class EduSelectCourseProjectWizard extends AbstractProjectWizard { + + private StepSequence mySequence = new StepSequence(); + + EduSelectCourseProjectWizard() { + super("New Course", null, (String)null); + init(); + } + + protected void init() { + myWizardContext.setModulesProvider(ModulesProvider.EMPTY_MODULES_PROVIDER); + MyChooseCourseStep step = new MyChooseCourseStep(); + mySequence.addCommonStep(step); + mySequence.addCommonFinishingStep(new ProjectSettingsStep(myWizardContext), null); + mySequence.getAllSteps().forEach(this::addStep); + super.init(); + } + + @Override + public StepSequence getSequence() { + return mySequence; + } + + private class MyChooseCourseStep extends ModuleWizardStep { + private ProjectTemplateList myTemplateList = new ProjectTemplateList(); + + @Override + public JComponent getComponent() { + return myTemplateList; + } + + @Override + public void updateDataModel() { + myWizardContext.setProjectTemplate(myTemplateList.getSelectedTemplate()); + } + + @Override + public void updateStep() { + List templates = new ArrayList<>(); + Collections.addAll(templates, ApplicationManager.getApplication().getExtensions(EduIntelliJProjectTemplate.EP_NAME)); + myTemplateList.setTemplates(templates, false); + } + } +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/android/EduStartLearningAction.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/android/EduStartLearningAction.java new file mode 100644 index 000000000000..f0ac7a088d4f --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/android/EduStartLearningAction.java @@ -0,0 +1,28 @@ +package com.jetbrains.edu.learning.intellij.android; + +import com.intellij.icons.AllIcons; +import com.intellij.ide.impl.NewProjectUtil; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.application.ApplicationManager; +import com.jetbrains.edu.learning.intellij.EduIntelliJProjectTemplate; + +public class EduStartLearningAction extends AnAction { + + public EduStartLearningAction() { + super(AllIcons.Modules.Types.UserDefined); + } + + @Override + public void actionPerformed(AnActionEvent e) { + EduSelectCourseProjectWizard wizard = new EduSelectCourseProjectWizard(); + NewProjectUtil.createNewProject(AnAction.getEventProject(e), wizard); + } + + @Override + public void update(AnActionEvent e) { + if (ApplicationManager.getApplication().getExtensions(EduIntelliJProjectTemplate.EP_NAME).length < 1) { + e.getPresentation().setEnabledAndVisible(false); + } + } +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/generation/EduCourseModuleBuilder.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/generation/EduCourseModuleBuilder.java new file mode 100644 index 000000000000..bf4ee029deb6 --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/generation/EduCourseModuleBuilder.java @@ -0,0 +1,16 @@ +package com.jetbrains.edu.learning.intellij.generation; + +import com.intellij.ide.util.projectWizard.JavaModuleBuilder; +import com.intellij.openapi.options.ConfigurationException; +import com.intellij.openapi.roots.ModifiableRootModel; + +import java.util.Collections; + +public class EduCourseModuleBuilder extends JavaModuleBuilder { + + @Override + public void setupRootModel(ModifiableRootModel rootModel) throws ConfigurationException { + setSourcePaths(Collections.emptyList()); + super.setupRootModel(rootModel); + } +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/generation/EduProjectGenerator.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/generation/EduProjectGenerator.java new file mode 100644 index 000000000000..fe98b766ea7a --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/generation/EduProjectGenerator.java @@ -0,0 +1,26 @@ +package com.jetbrains.edu.learning.intellij.generation; + +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import com.jetbrains.edu.learning.StudyTaskManager; +import com.jetbrains.edu.learning.courseFormat.Course; +import com.jetbrains.edu.learning.courseGeneration.StudyProjectGenerator; +import org.jetbrains.annotations.NotNull; + +import java.io.File; + +public class EduProjectGenerator extends StudyProjectGenerator { + private static final Logger LOG = Logger.getInstance(EduProjectGenerator.class); + + @Override + public void generateProject(@NotNull Project project, @NotNull VirtualFile baseDir) { + final Course course = getCourse(project); + if (course == null) { + LOG.warn("Failed to get course"); + return; + } + StudyTaskManager.getInstance(project).setCourse(course); + course.setCourseDirectory(new File(OUR_COURSES_DIR, mySelectedCourseInfo.getName()).getAbsolutePath()); + } +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduCustomCourseModuleBuilder.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduCustomCourseModuleBuilder.java new file mode 100644 index 000000000000..ebd6ee738a33 --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduCustomCourseModuleBuilder.java @@ -0,0 +1,106 @@ +package com.jetbrains.edu.learning.intellij.localCourses; + +import com.intellij.ide.util.projectWizard.*; +import com.intellij.lang.Language; +import com.intellij.openapi.module.ModifiableModuleModel; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleWithNameAlreadyExists; +import com.intellij.openapi.options.ConfigurationException; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.roots.ui.configuration.ModulesProvider; +import com.intellij.openapi.util.Conditions; +import com.intellij.openapi.util.InvalidDataException; +import com.jetbrains.edu.learning.courseGeneration.StudyProjectGenerator; +import com.jetbrains.edu.learning.intellij.EduCourseConfigurator; +import com.jetbrains.edu.learning.intellij.generation.EduProjectGenerator; +import com.jetbrains.edu.learning.stepic.CourseInfo; +import org.jdom.JDOMException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.io.IOException; + +class EduCustomCourseModuleBuilder extends JavaModuleBuilder { + private EduProjectGenerator myGenerator = new EduProjectGenerator(); + private CourseInfo mySelectedCourse; + + @Nullable + @Override + public Module commitModule(@NotNull Project project, @Nullable ModifiableModuleModel model) { + Module module = super.commitModule(project, model); + if (module == null) { + return null; + } + String type = mySelectedCourse.getType(); + String languageName = type.substring("pycharm ".length()); + Language language = Language.findLanguageByID(languageName); + if (language != null) { + EduCourseConfigurator configurator = EduCourseConfigurator.INSTANCE.forLanguage(language); + if (configurator != null) { + configurator.configureModule(module); + } + } + return module; + } + + + @Nullable + @Override + public String getBuilderId() { + return "custom.course.builder"; + } + + @Override + public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull ModulesProvider modulesProvider) { + return new ModuleWizardStep[]{new EduCourseSelectionSettingsStep(myGenerator)}; + } + + + private class EduCourseSelectionSettingsStep extends ModuleWizardStep { + + private final StudyProjectGenerator myGenerator; + + EduCourseSelectionSettingsStep(StudyProjectGenerator generator) { + myGenerator = generator; + } + + @Override + public JComponent getComponent() { + return new EduLocalCoursePanel(myGenerator, EduCustomCourseModuleBuilder.this).getContentPanel(); + } + + @Override + public void updateDataModel() { + } + } + + @Nullable + @Override + public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) { + return ProjectWizardStepFactory.getInstance().createJavaSettingsStep(settingsStep, this, Conditions.alwaysTrue()); + } + + void setSelectedCourse(CourseInfo selectedCourse) { + mySelectedCourse = selectedCourse; + } + + @NotNull + @Override + public Module createModule(@NotNull ModifiableModuleModel moduleModel) + throws InvalidDataException, IOException, ModuleWithNameAlreadyExists, JDOMException, ConfigurationException { + Module baseModule = super.createModule(moduleModel); + if (mySelectedCourse != null) { + String type = mySelectedCourse.getType(); + String languageName = type.substring("pycharm ".length()); + Language language = Language.findLanguageByID(languageName); + if (language != null) { + EduCourseConfigurator configurator = EduCourseConfigurator.INSTANCE.forLanguage(language); + if (configurator != null) { + configurator.createCourseFromCourseInfo(moduleModel, baseModule.getProject(), myGenerator, mySelectedCourse, getModuleFileDirectory()); + } + } + } + return baseModule; + } +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduCustomCourseProjectTemplate.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduCustomCourseProjectTemplate.java new file mode 100644 index 000000000000..c80e8f4bc686 --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduCustomCourseProjectTemplate.java @@ -0,0 +1,41 @@ +package com.jetbrains.edu.learning.intellij.localCourses; + +import com.intellij.icons.AllIcons; +import com.intellij.ide.util.projectWizard.AbstractModuleBuilder; +import com.intellij.openapi.ui.ValidationInfo; +import com.jetbrains.edu.learning.intellij.EduIntelliJProjectTemplate; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; + +class EduCustomCourseProjectTemplate implements EduIntelliJProjectTemplate { + @NotNull + @Override + public String getName() { + return "Load an existing course"; + } + + @Nullable + @Override + public String getDescription() { + return "Custom Course Addition"; + } + + @Override + public Icon getIcon() { + return AllIcons.General.SecondaryGroup; + } + + @NotNull + @Override + public AbstractModuleBuilder createModuleBuilder() { + return new EduCustomCourseModuleBuilder(); + } + + @Nullable + @Override + public ValidationInfo validateSettings() { + return null; + } +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduLocalCoursePanel.form b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduLocalCoursePanel.form new file mode 100644 index 000000000000..19b885d3a4c6 --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduLocalCoursePanel.form @@ -0,0 +1,53 @@ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduLocalCoursePanel.java b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduLocalCoursePanel.java new file mode 100644 index 000000000000..f078b7b4c1ab --- /dev/null +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/intellij/localCourses/EduLocalCoursePanel.java @@ -0,0 +1,51 @@ +package com.jetbrains.edu.learning.intellij.localCourses; + +import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; +import com.intellij.openapi.ui.TextFieldWithBrowseButton; +import com.jetbrains.edu.learning.courseGeneration.StudyProjectGenerator; +import com.jetbrains.edu.learning.stepic.CourseInfo; +import com.jetbrains.edu.learning.ui.StudyNewProjectPanel; + +import javax.swing.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public class EduLocalCoursePanel { + private final StudyProjectGenerator myGenerator; + private EduCustomCourseModuleBuilder myBuilder; + private JPanel myContentPanel; + private JPanel myInfoPanel; + private TextFieldWithBrowseButton myCourseArchivePath; + private StudyNewProjectPanel myStudyPanel; + + public EduLocalCoursePanel(final StudyProjectGenerator generator, EduCustomCourseModuleBuilder builder) { + myGenerator = generator; + myBuilder = builder; + myCourseArchivePath.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent actionEvent) { + String coursePath = myCourseArchivePath.getText(); + CourseInfo courseInfo = generator.addLocalCourse(coursePath); + if (courseInfo != null) { + myBuilder.setSelectedCourse(courseInfo); + myGenerator.setSelectedCourse(courseInfo); + myStudyPanel.updateInfoPanel(courseInfo); + } + else { + //TODO: implement validation + } + } + }); + myCourseArchivePath.addBrowseFolderListener("Select Course Archive", null, null, + FileChooserDescriptorFactory.createSingleFileDescriptor()); + } + + public JPanel getContentPanel() { + return myContentPanel; + } + + private void createUIComponents() { + myStudyPanel = new StudyNewProjectPanel(myGenerator); + myInfoPanel = myStudyPanel.getInfoPanel(); + } +} diff --git a/python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyNewProjectPanel.java b/python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyNewProjectPanel.java index a645efb8b353..9691c630d114 100644 --- a/python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyNewProjectPanel.java +++ b/python/educational-core/student/src/com/jetbrains/edu/learning/ui/StudyNewProjectPanel.java @@ -123,8 +123,7 @@ public class StudyNewProjectPanel extends JPanel implements PanelWithAnchor { addCoursesToCombobox(myAvailableCourses); final CourseInfo selectedCourse = StudyUtils.getFirst(myAvailableCourses); if (selectedCourse == null) return; - final String authorsString = Course.getAuthorsString(selectedCourse.getAuthors()); - myAuthorLabel.setText(!StringUtil.isEmptyOrSpaces(authorsString) ? "Author: " + authorsString : ""); + setAuthors(selectedCourse); myDescriptionPane.setText(selectedCourse.getDescription()); myDescriptionPane.setEditable(false); //setting the first course in list as selected @@ -251,6 +250,11 @@ public class StudyNewProjectPanel extends JPanel implements PanelWithAnchor { myAnchor = anchor; } + public void updateInfoPanel(@NotNull CourseInfo selectedCourseInfo) { + setAuthors(selectedCourseInfo); + myDescriptionPane.setText(selectedCourseInfo.getDescription()); + } + /** * Handles refreshing courses * Old courses added to new courses only if their @@ -307,10 +311,8 @@ public class StudyNewProjectPanel extends JPanel implements PanelWithAnchor { setError(INVALID_COURSE); return; } - final String authorsString = Course.getAuthorsString(selectedCourse.getAuthors()); - myAuthorLabel.setText(!StringUtil.isEmptyOrSpaces(authorsString) ? "Author: " + authorsString : ""); + updateInfoPanel(selectedCourse); myCoursesComboBox.removeItem(CourseInfo.INVALID_COURSE); - myDescriptionPane.setText(selectedCourse.getDescription()); myGenerator.setSelectedCourse(selectedCourse); setOK(); @@ -322,6 +324,11 @@ public class StudyNewProjectPanel extends JPanel implements PanelWithAnchor { } } + private void setAuthors(CourseInfo selectedCourse) { + final String authorsString = Course.getAuthorsString(selectedCourse.getAuthors()); + myAuthorLabel.setText(!StringUtil.isEmptyOrSpaces(authorsString) ? "Author: " + authorsString : ""); + } + public JComboBox getCoursesComboBox() { return myCoursesComboBox; } diff --git a/python/educational-core/student/student.iml b/python/educational-core/student/student.iml index 054fd550f453..29d9b096e528 100644 --- a/python/educational-core/student/student.iml +++ b/python/educational-core/student/student.iml @@ -37,5 +37,7 @@
+ + \ No newline at end of file diff --git a/python/educational-python/build.gradle b/python/educational-python/build.gradle index 219b24d03391..3d37b40359c5 100644 --- a/python/educational-python/build.gradle +++ b/python/educational-python/build.gradle @@ -82,9 +82,13 @@ project(':student-python') { } dependencies { - compile project(':educational-core:student') { + compile project(':educational-core:course-creator') { dependencies { - compile fileTree(dir: 'lib', include: ['*.jar']) + compile project(':educational-core:student') { + dependencies { + compile fileTree(dir: 'lib', include: ['*.jar']) + } + } } } } @@ -102,29 +106,4 @@ project(':student-python') { } } -} - - -project(':course-creator-python') { - - dependencies { - compile project(':student-python') - - compile project(':educational-core:course-creator') { - dependencies { - compile project(':educational-core:student') - } - } - } - - intellij { - pluginName 'course-creator-python' - } - - afterEvaluate { - tasks.getByName('buildPlugin') { - archiveName = "$intellij.pluginName-$version-${pycharmVersion}.zip" - } - } - } \ No newline at end of file diff --git a/python/educational-python/build/plugin-list.txt b/python/educational-python/build/plugin-list.txt index c635ee001828..4d446d0893e4 100644 --- a/python/educational-python/build/plugin-list.txt +++ b/python/educational-python/build/plugin-list.txt @@ -5,6 +5,5 @@ github student student-python course-creator -course-creator-python hg4idea ipnb \ No newline at end of file diff --git a/python/educational-python/course-creator-python/course-creator-python.iml b/python/educational-python/course-creator-python/course-creator-python.iml deleted file mode 100644 index ba637201f6dc..000000000000 --- a/python/educational-python/course-creator-python/course-creator-python.iml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/python/educational-python/course-creator-python/src/icons/CourseCreatorPythonIcons.java b/python/educational-python/course-creator-python/src/icons/CourseCreatorPythonIcons.java deleted file mode 100644 index b4bcd501ad76..000000000000 --- a/python/educational-python/course-creator-python/src/icons/CourseCreatorPythonIcons.java +++ /dev/null @@ -1,17 +0,0 @@ -package icons; - -import com.intellij.openapi.util.IconLoader; - -import javax.swing.*; - -/** - * NOTE THIS FILE IS AUTO-GENERATED - * DO NOT EDIT IT BY HAND, run build/scripts/icons.gant instead - */ -public class CourseCreatorPythonIcons { - private static Icon load(String path) { - return IconLoader.getIcon(path, CourseCreatorPythonIcons.class); - } - - public static final Icon CourseCreationProjectType = load("/icons/CourseCreationProjectType.png"); // 16x16 -} diff --git a/python/educational-python/gradle.properties b/python/educational-python/gradle.properties index 983784030bbb..3bfc09315f62 100644 --- a/python/educational-python/gradle.properties +++ b/python/educational-python/gradle.properties @@ -1,7 +1,7 @@ -ideaVersion IC-LATEST-TRUNK-SNAPSHOT +ideaVersion IC-171-SNAPSHOT downloadIdeaSources false -version 2.0.5 -buildNumber 162.1121.10 +version 4.0 +buildNumber 171 javaVersion 1.8 -pycharmVersion 162.75 +pycharmVersion 172.199 updateBuildNumber false \ No newline at end of file diff --git a/python/educational-python/main_pycharm_edu.iml b/python/educational-python/main_pycharm_edu.iml index c2e9e1eff290..465313c7319f 100644 --- a/python/educational-python/main_pycharm_edu.iml +++ b/python/educational-python/main_pycharm_edu.iml @@ -16,7 +16,6 @@ - diff --git a/python/educational-python/course-creator-python/resources/fileTemplates/internal/task.html.ft b/python/educational-python/resources/fileTemplates/internal/task.html.ft similarity index 100% rename from python/educational-python/course-creator-python/resources/fileTemplates/internal/task.html.ft rename to python/educational-python/resources/fileTemplates/internal/task.html.ft diff --git a/python/educational-python/course-creator-python/resources/fileTemplates/internal/task.md.ft b/python/educational-python/resources/fileTemplates/internal/task.md.ft similarity index 100% rename from python/educational-python/course-creator-python/resources/fileTemplates/internal/task.md.ft rename to python/educational-python/resources/fileTemplates/internal/task.md.ft diff --git a/python/educational-python/course-creator-python/resources/fileTemplates/internal/task.py.ft b/python/educational-python/resources/fileTemplates/internal/task.py.ft similarity index 100% rename from python/educational-python/course-creator-python/resources/fileTemplates/internal/task.py.ft rename to python/educational-python/resources/fileTemplates/internal/task.py.ft diff --git a/python/educational-python/course-creator-python/resources/fileTemplates/internal/tests.py.ft b/python/educational-python/resources/fileTemplates/internal/tests.py.ft similarity index 100% rename from python/educational-python/course-creator-python/resources/fileTemplates/internal/tests.py.ft rename to python/educational-python/resources/fileTemplates/internal/tests.py.ft diff --git a/python/educational-python/settings.gradle b/python/educational-python/settings.gradle index 6d6892e70100..82402e08e86e 100644 --- a/python/educational-python/settings.gradle +++ b/python/educational-python/settings.gradle @@ -1,4 +1,4 @@ -include 'student-python', 'course-creator-python' +include 'student-python' include "educational-core:student" project(":educational-core:student").projectDir = new File(rootDir, "../educational-core/student") include "educational-core:course-creator" diff --git a/python/educational-python/course-creator-python/resources/META-INF/plugin.xml b/python/educational-python/student-python/resources/META-INF/course-creator.xml similarity index 60% rename from python/educational-python/course-creator-python/resources/META-INF/plugin.xml rename to python/educational-python/student-python/resources/META-INF/course-creator.xml index 85ec939dd37e..29d74733ee4e 100644 --- a/python/educational-python/course-creator-python/resources/META-INF/plugin.xml +++ b/python/educational-python/student-python/resources/META-INF/course-creator.xml @@ -1,23 +1,4 @@ - com.jetbrains.edu.coursecreator.python - Course Creator for PyCharm Edu - 2.0.3 - - . - ]]> - JetBrains - - - - - com.intellij.modules.platform - com.intellij.modules.python - com.jetbrains.edu.coursecreator - com.jetbrains.edu.interactivelearning - com.jetbrains.python.edu.interactivelearning.python - diff --git a/python/educational-python/student-python/resources/META-INF/plugin.xml b/python/educational-python/student-python/resources/META-INF/plugin.xml index ad55873def45..2a5a9bd21263 100644 --- a/python/educational-python/student-python/resources/META-INF/plugin.xml +++ b/python/educational-python/student-python/resources/META-INF/plugin.xml @@ -18,6 +18,7 @@ com.intellij.modules.lang com.intellij.modules.python com.jetbrains.edu.interactivelearning + com.jetbrains.edu.coursecreator diff --git a/python/educational-python/course-creator-python/resources/icons/CourseCreationProjectType.png b/python/educational-python/student-python/resources/icons/com/jetbrains/edu/learning/CourseCreationProjectType.png similarity index 100% rename from python/educational-python/course-creator-python/resources/icons/CourseCreationProjectType.png rename to python/educational-python/student-python/resources/icons/com/jetbrains/edu/learning/CourseCreationProjectType.png diff --git a/python/educational-python/course-creator-python/resources/icons/CourseCreationProjectType@2x.png b/python/educational-python/student-python/resources/icons/com/jetbrains/edu/learning/CourseCreationProjectType@2x.png similarity index 100% rename from python/educational-python/course-creator-python/resources/icons/CourseCreationProjectType@2x.png rename to python/educational-python/student-python/resources/icons/com/jetbrains/edu/learning/CourseCreationProjectType@2x.png diff --git a/python/educational-python/course-creator-python/resources/icons/CourseCreationProjectType@2x_dark.png b/python/educational-python/student-python/resources/icons/com/jetbrains/edu/learning/CourseCreationProjectType@2x_dark.png similarity index 100% rename from python/educational-python/course-creator-python/resources/icons/CourseCreationProjectType@2x_dark.png rename to python/educational-python/student-python/resources/icons/com/jetbrains/edu/learning/CourseCreationProjectType@2x_dark.png diff --git a/python/educational-python/course-creator-python/resources/icons/CourseCreationProjectType_dark.png b/python/educational-python/student-python/resources/icons/com/jetbrains/edu/learning/CourseCreationProjectType_dark.png similarity index 100% rename from python/educational-python/course-creator-python/resources/icons/CourseCreationProjectType_dark.png rename to python/educational-python/student-python/resources/icons/com/jetbrains/edu/learning/CourseCreationProjectType_dark.png diff --git a/python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/CreateFromArchiveProjectStep.java b/python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/CreateFromArchiveProjectStep.java similarity index 100% rename from python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/CreateFromArchiveProjectStep.java rename to python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/CreateFromArchiveProjectStep.java diff --git a/python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/PyCCChangeCourseInfo.java b/python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/PyCCChangeCourseInfo.java similarity index 100% rename from python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/PyCCChangeCourseInfo.java rename to python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/PyCCChangeCourseInfo.java diff --git a/python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/PyCCCreateProjectFromArchive.java b/python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/PyCCCreateProjectFromArchive.java similarity index 100% rename from python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/PyCCCreateProjectFromArchive.java rename to python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/PyCCCreateProjectFromArchive.java diff --git a/python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/PyCCLanguageManager.java b/python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/PyCCLanguageManager.java similarity index 100% rename from python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/PyCCLanguageManager.java rename to python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/PyCCLanguageManager.java diff --git a/python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/PyCCProjectGenerator.java b/python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/PyCCProjectGenerator.java similarity index 97% rename from python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/PyCCProjectGenerator.java rename to python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/PyCCProjectGenerator.java index 351a8807898c..08b023c7d613 100644 --- a/python/educational-python/course-creator-python/src/com/jetbrains/edu/coursecreator/PyCCProjectGenerator.java +++ b/python/educational-python/student-python/src/com/jetbrains/edu/coursecreator/PyCCProjectGenerator.java @@ -27,7 +27,7 @@ import com.jetbrains.python.PythonLanguage; import com.jetbrains.python.newProject.PyNewProjectSettings; import com.jetbrains.python.newProject.PythonProjectGenerator; import com.jetbrains.python.remote.PyProjectSynchronizer; -import icons.CourseCreatorPythonIcons; +import icons.InteractiveLearningPythonIcons; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -52,7 +52,7 @@ public class PyCCProjectGenerator extends PythonProjectGenerator + \ No newline at end of file diff --git a/python/ipnb/src/org/jetbrains/plugins/ipnb/configuration/IpnbConfigurable.java b/python/ipnb/src/org/jetbrains/plugins/ipnb/configuration/IpnbConfigurable.java index 378bc399a6a1..5325e21f1442 100644 --- a/python/ipnb/src/org/jetbrains/plugins/ipnb/configuration/IpnbConfigurable.java +++ b/python/ipnb/src/org/jetbrains/plugins/ipnb/configuration/IpnbConfigurable.java @@ -144,7 +144,7 @@ public class IpnbConfigurable implements SearchableConfigurable { private void createUIComponents() { // TODO: remove this hack - int gap = SystemInfo.isWindows ? 1 : 2; + int gap = SystemInfo.isWindows ? 4 : SystemInfo.isMac ? 8 : 16; mySpecificNotebookSettingsPanel = PlatformUtils.isPyCharmPro() ? new SettingsPanelPro() : new LocalSettingsPanel(true, 0, gap); } @@ -171,7 +171,7 @@ public class IpnbConfigurable implements SearchableConfigurable { myRemote = createModeRadioButton("Remote"); myRemoteSettingsPanel = new RemoteSettingsPanel(isRemote); - myLocalSettingsPanel = new LocalSettingsPanel(!isRemote, DEFAULT_PADDING, 1); + myLocalSettingsPanel = new LocalSettingsPanel(!isRemote, DEFAULT_PADDING, 2); final ButtonGroup group = new ButtonGroup(); myLocal.setSelected(!isRemote); @@ -280,8 +280,8 @@ public class IpnbConfigurable implements SearchableConfigurable { myAdditionalOptions.addFocusListener(createInitialTextFocusAdapter(myAdditionalOptions, DEFAULT_PARAMETERS_TEXT)); initFields(); - setLayout(new MigLayout("insets 0", leftPadding + "unrel[]" + gap + "unrel[grow]", "[][]")); - add(myParametersLabel); + setLayout(new MigLayout("insets 0", leftPadding + "unrel[][grow]", "[][]")); + add(myParametersLabel, "gapafter " + gap); add(myAdditionalOptions, "growx"); if (enabled) { enablePanel(); @@ -351,8 +351,8 @@ public class IpnbConfigurable implements SearchableConfigurable { myInterpreterSetupLinkLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); createNavigateToInterpreterSettingsListener().installOn(myInterpreterSetupLinkLabel); - - setLayout(new MigLayout("insets 0", DEFAULT_PADDING + "unrel[]5unrel[grow]", "[][][]")); + int gap = SystemInfo.isMac ? 6 : 5; + setLayout(new MigLayout("insets 0", DEFAULT_PADDING + "unrel[]" + gap + "unrel[grow]", "[][][]")); myUsernameLabel = new JBLabel("Username:"); myUsernameField = new JBTextField(); myUsernameField.addFocusListener(createInitialTextFocusAdapter(myUsernameField, DEFAULT_USERNAME_TEXT)); diff --git a/resources/src/META-INF/IdeaPlugin.xml b/resources/src/META-INF/IdeaPlugin.xml index 469681d20260..498f0adae99a 100644 --- a/resources/src/META-INF/IdeaPlugin.xml +++ b/resources/src/META-INF/IdeaPlugin.xml @@ -1905,6 +1905,8 @@ + + @@ -1926,6 +1928,10 @@ + + + + diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/DomCollectionControl.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/DomCollectionControl.java index 22b426101d59..81687c9694b5 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/ui/DomCollectionControl.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/DomCollectionControl.java @@ -145,7 +145,7 @@ public class DomCollectionControl extends DomUIControl imp } } - @Nullable + @Nullable @NonNls protected String getHelpId() { return null; }