Merge remote-tracking branch 'origin/master'

This commit is contained in:
Mikhail Golubev
2015-02-25 15:01:13 +03:00
152 changed files with 2591 additions and 2847 deletions
-2
View File
@@ -6,8 +6,6 @@
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/lib/src/velocity-1.7-src.zip!/java" />
<root url="jar://$PROJECT_DIR$/lib/src/commons-collections-3.2.1-src.zip!/commons-collections-3.2.1-src/src/java" />
<root url="jar://$PROJECT_DIR$/lib/src/commons-lang-2.4-sources.jar!/" />
</SOURCES>
</library>
</component>
+1 -1
View File
@@ -151,7 +151,7 @@ if [ "$IS_EAP" = "true" ]; then
OS_NAME=`echo $OS_TYPE | "$TR" '[:upper:]' '[:lower:]'`
AGENT_LIB="yjpagent-$OS_NAME$BITS"
if [ -r "$IDE_BIN_HOME/lib$AGENT_LIB.so" ]; then
AGENT="-agentlib:$AGENT_LIB=disablej2ee,disablealloc,delay=10000,sessionname=@@system_selector@@"
AGENT="-agentlib:$AGENT_LIB=disablealloc,delay=10000,sessionname=@@system_selector@@"
fi
fi
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -1017,7 +1017,7 @@ public class BuildManager implements ApplicationComponent{
}
if (isProfilingMode) {
cmdLine.addParameter("-agentlib:yjpagent=disablej2ee,disablealloc,delay=10000,sessionname=ExternalBuild");
cmdLine.addParameter("-agentlib:yjpagent=disablealloc,delay=10000,sessionname=ExternalBuild");
}
// debugging
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -78,7 +78,7 @@ public class AddToWatchActionHandler extends DebuggerActionHandler {
if(session == null) {
return;
}
final MainWatchPanel watchPanel = DebuggerPanelsManager.getInstance(debuggerContext.getProject()).getWatchPanel();
final MainWatchPanel watchPanel = null;// DebuggerPanelsManager.getInstance(debuggerContext.getProject()).getWatchPanel();
if(watchPanel == null) {
return;
@@ -1,143 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Class EvaluateAction
* @author Jeka
*/
package com.intellij.debugger.actions;
import com.intellij.debugger.DebuggerInvocationUtil;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.engine.events.DebuggerContextCommandImpl;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.ExpressionEvaluationDialog;
import com.intellij.debugger.ui.StatementEvaluationDialog;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeExpression;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl;
import com.intellij.debugger.ui.impl.watch.WatchItemDescriptor;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.xdebugger.impl.actions.DebuggerActionHandler;
import org.jetbrains.annotations.NotNull;
public class EvaluateActionHandler extends DebuggerActionHandler {
public boolean isEnabled(@NotNull final Project project, final AnActionEvent event) {
DebuggerContextImpl context = DebuggerAction.getDebuggerContext(event.getDataContext());
if(context != null) {
DebuggerSession debuggerSession = context.getDebuggerSession();
return debuggerSession != null && debuggerSession.isPaused();
}
return false;
}
public void perform(@NotNull final Project project, final AnActionEvent event) {
final DataContext dataContext = event.getDataContext();
final DebuggerContextImpl context = DebuggerAction.getDebuggerContext(dataContext);
if(context == null) {
return;
}
final Editor editor = event.getData(DataKeys.EDITOR);
TextWithImports editorText = DebuggerUtilsEx.getEditorText(editor);
if (editorText == null) {
final DebuggerTreeNodeImpl selectedNode = DebuggerAction.getSelectedNode(dataContext);
final String actionName = event.getPresentation().getText();
if (selectedNode != null && selectedNode.getDescriptor() instanceof ValueDescriptorImpl) {
context.getDebugProcess().getManagerThread().schedule(new DebuggerContextCommandImpl(context) {
public void threadAction() {
try {
final TextWithImports evaluationText = DebuggerTreeNodeExpression.createEvaluationText(selectedNode, context);
DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() {
public void run() {
showEvaluationDialog(project, evaluationText);
}
});
}
catch (final EvaluateException e1) {
DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() {
public void run() {
Messages.showErrorDialog(project, e1.getMessage(), actionName);
}
});
}
}
protected void commandCancelled() {
DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() {
public void run() {
if(selectedNode.getDescriptor() instanceof WatchItemDescriptor) {
try {
TextWithImports editorText = DebuggerTreeNodeExpression.createEvaluationText(selectedNode, context);
showEvaluationDialog(project, editorText);
}
catch (EvaluateException e1) {
Messages.showErrorDialog(project, e1.getMessage(), actionName);
}
}
}
});
}
});
return;
}
}
showEvaluationDialog(project, editorText);
}
public static void showEvaluationDialog(Project project, TextWithImports defaultExpression, String dialogType) {
if(defaultExpression == null) {
defaultExpression = new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, "");
}
CodeFragmentKind kind = DebuggerSettings.EVALUATE_FRAGMENT.equals(dialogType) ? CodeFragmentKind.CODE_BLOCK : CodeFragmentKind.EXPRESSION;
DebuggerSettings.getInstance().EVALUATION_DIALOG_TYPE = dialogType;
TextWithImportsImpl text = new TextWithImportsImpl(kind, defaultExpression.getText(), defaultExpression.getImports(), defaultExpression.getFileType());
final DialogWrapper dialog;
if(DebuggerSettings.EVALUATE_FRAGMENT.equals(dialogType)) {
dialog = new StatementEvaluationDialog(project, text);
}
else {
dialog = new ExpressionEvaluationDialog(project, text);
}
dialog.show();
}
public static void showEvaluationDialog(Project project, TextWithImports text) {
showEvaluationDialog(project, text, DebuggerSettings.getInstance().EVALUATION_DIALOG_TYPE);
}
}
@@ -1,42 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.actions;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerStateManager;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.debugger.ui.DebuggerPanelsManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.project.Project;
/**
* User: lex
* Date: Sep 26, 2003
* Time: 7:45:21 PM
*/
public class ShowFrameAction extends GotoFrameSourceAction {
public void actionPerformed(AnActionEvent e) {
super.actionPerformed(e);
DebuggerStateManager stateManager = getContextManager(e.getDataContext());
DebuggerContextImpl context = stateManager.getContext();
if(context != null) {
DebuggerPanelsManager.getInstance(context.getProject()).showFramePanel();
}
}
}
@@ -27,8 +27,8 @@ import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.events.DebuggerCommandImpl;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.debugger.ui.DebuggerSessionTab;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
@@ -70,7 +70,7 @@ public class ThreadDumpAction extends AnAction implements AnAction.TransparentUp
public void run() {
XDebugSession xSession = session.getXDebugSession();
if (xSession != null) {
DebuggerSessionTab.addThreadDump(project, threads, xSession.getUI(), session);
DebuggerUtilsEx.addThreadDump(project, threads, xSession.getUI(), session);
}
}
}, ModalityState.NON_MODAL);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,7 +27,6 @@ import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.debugger.requests.Requestor;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.ui.DebuggerPanelsManager;
import com.intellij.debugger.ui.breakpoints.Breakpoint;
import com.intellij.debugger.ui.breakpoints.LineBreakpoint;
import com.intellij.execution.configurations.RemoteConnection;
@@ -452,7 +451,6 @@ public class DebugProcessEvents extends DebugProcessImpl {
DebuggerInvocationUtil.invokeAndWait(getProject(), new Runnable() {
@Override
public void run() {
DebuggerPanelsManager.getInstance(getProject()).toFront(mySession);
final String displayName = requestor instanceof Breakpoint? ((Breakpoint)requestor).getDisplayName() : requestor.getClass().getSimpleName();
final String message = DebuggerBundle.message("error.evaluating.breakpoint.condition.or.action", displayName, ex.getMessage());
considerRequestHit[0] = Messages.showYesNoDialog(getProject(), message, ex.getTitle(), Messages.getQuestionIcon()) == Messages.YES;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -1098,7 +1098,7 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb
throw (RuntimeException)exception[0];
}
else {
LOG.assertTrue(false);
LOG.error("Unexpected exception " + exception[0]);
}
}
@@ -33,7 +33,14 @@ import com.intellij.debugger.requests.Requestor;
import com.intellij.debugger.ui.CompletionEditor;
import com.intellij.debugger.ui.breakpoints.Breakpoint;
import com.intellij.debugger.ui.tree.DebuggerTreeNode;
import com.intellij.execution.filters.ExceptionFilters;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.RunnerLayoutUi;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
@@ -47,6 +54,9 @@ import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.ui.classFilter.ClassFilter;
import com.intellij.ui.content.Content;
import com.intellij.unscramble.ThreadDumpPanel;
import com.intellij.unscramble.ThreadState;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.xdebugger.XSourcePosition;
@@ -399,6 +409,43 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
return null;
}
private static int myThreadDumpsCount = 0;
private static int myCurrentThreadDumpId = 1;
private static final String THREAD_DUMP_CONTENT_PREFIX = "Dump";
public static void addThreadDump(Project project, List<ThreadState> threads, final RunnerLayoutUi ui, DebuggerSession session) {
final TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
consoleBuilder.filters(ExceptionFilters.getFilters(session.getSearchScope()));
final ConsoleView consoleView = consoleBuilder.getConsole();
final DefaultActionGroup toolbarActions = new DefaultActionGroup();
consoleView.allowHeavyFilters();
final ThreadDumpPanel panel = new ThreadDumpPanel(project, consoleView, toolbarActions, threads);
final String id = THREAD_DUMP_CONTENT_PREFIX + " #" + myCurrentThreadDumpId;
final Content content = ui.createContent(id, panel, id, null, null);
content.setCloseable(true);
content.setDescription("Thread Dump");
ui.addContent(content);
ui.selectAndFocus(content, true, true);
myThreadDumpsCount++;
myCurrentThreadDumpId++;
Disposer.register(content, new Disposable() {
@Override
public void dispose() {
myThreadDumpsCount--;
if (myThreadDumpsCount == 0) {
myCurrentThreadDumpId = 1;
}
}
});
Disposer.register(content, consoleView);
ui.selectAndFocus(content, true, false);
if (threads.size() > 0) {
panel.selectStackFrame(0);
}
}
public abstract DebuggerTreeNode getSelectedNode (DataContext context);
public abstract EvaluatorBuilder getEvaluatorBuilder();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -84,6 +84,22 @@ public class StackFrameProxyImpl extends JdiProxy implements StackFrameProxy {
throw new EvaluateException(error.getMessage(), error);
}
@Override
public boolean isValid() {
DebuggerManagerThreadImpl.assertIsManagerThread();
if (!super.isValid()) {
return false;
}
try {
if (myStackFrame != null) {
myStackFrame.location(); //extra check if jdi frame is valid
}
return true;
} catch (InvalidStackFrameException e) {
return false;
}
}
@Override
protected void clearCaches() {
DebuggerManagerThreadImpl.assertIsManagerThread();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,10 +24,8 @@ import com.intellij.debugger.engine.JavaDebugProcess;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.debugger.impl.DebuggerStateManager;
import com.intellij.debugger.ui.impl.MainWatchPanel;
import com.intellij.debugger.ui.tree.render.BatchEvaluator;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.RemoteConnection;
import com.intellij.execution.configurations.RunProfileState;
@@ -39,9 +37,8 @@ import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.RunContentManager;
import com.intellij.execution.ui.RunContentWithExecutorListener;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.xdebugger.XDebugProcess;
import com.intellij.xdebugger.XDebugProcessStarter;
import com.intellij.xdebugger.XDebugSession;
@@ -50,43 +47,10 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class DebuggerPanelsManager implements ProjectComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.DebuggerPanelsManager");
private final Project myProject;
private final ExecutionManager myExecutionManager;
//private final PositionHighlighter myEditorManager;
//private final HashMap<ProcessHandler, DebuggerSessionTab> mySessionTabs = new HashMap<ProcessHandler, DebuggerSessionTab>();
public DebuggerPanelsManager(Project project, final EditorColorsManager colorsManager, ExecutionManager executionManager) {
public DebuggerPanelsManager(Project project) {
myProject = project;
myExecutionManager = executionManager;
//myEditorManager = new PositionHighlighter(myProject, getContextManager());
//
//final EditorColorsListener myColorsListener = new EditorColorsListener() {
// public void globalSchemeChange(EditorColorsScheme scheme) {
// myEditorManager.updateContextPointDescription();
// }
//};
//colorsManager.addEditorColorsListener(myColorsListener);
//Disposer.register(project, new Disposable() {
// public void dispose() {
// colorsManager.removeEditorColorsListener(myColorsListener);
// }
//});
//
//getContextManager().addListener(new DebuggerContextListener() {
// public void changeEvent(final DebuggerContextImpl newContext, int event) {
// if (event == DebuggerSession.EVENT_PAUSE) {
// DebuggerInvocationUtil.invokeLater(myProject, new Runnable() {
// public void run() {
// toFront(newContext.getDebuggerSession());
// }
// });
// }
// }
//});
}
private DebuggerStateManager getContextManager() {
@@ -195,48 +159,12 @@ public class DebuggerPanelsManager implements ProjectComponent {
return project.getComponent(DebuggerPanelsManager.class);
}
@Nullable
public MainWatchPanel getWatchPanel() {
DebuggerSessionTab sessionTab = getSessionTab();
return sessionTab != null ? sessionTab.getWatchPanel() : null;
}
@Nullable
public DebuggerSessionTab getSessionTab() {
DebuggerContextImpl context = DebuggerManagerEx.getInstanceEx(myProject).getContext();
return getSessionTab(context.getDebuggerSession());
}
public void showFramePanel() {
DebuggerSessionTab sessionTab = getSessionTab();
if (sessionTab != null) {
sessionTab.showFramePanel();
}
}
public void toFront(DebuggerSession session) {
DebuggerSessionTab sessionTab = getSessionTab(session);
if (sessionTab != null) {
sessionTab.toFront(true, null);
}
}
private static DebuggerSession getSession(Project project, RunContentDescriptor descriptor) {
for (XDebugSession session : XDebuggerManager.getInstance(project).getDebugSessions()) {
if (session.getRunContentDescriptor().equals(descriptor)) {
XDebugProcess process = session.getDebugProcess();
if (process instanceof JavaDebugProcess) {
return ((JavaDebugProcess)process).getDebuggerSession();
}
for (JavaDebugProcess process : XDebuggerManager.getInstance(project).getDebugProcesses(JavaDebugProcess.class)) {
if (Comparing.equal(process.getProcessHandler(), descriptor.getProcessHandler())) {
return process.getDebuggerSession();
}
}
return null;
}
@Nullable
private DebuggerSessionTab getSessionTab(DebuggerSession session) {
//return session != null ? getSessionTab(session.getProcess().getExecutionResult().getProcessHandler()) : null;
return null;
}
}
@@ -36,12 +36,8 @@ import com.intellij.execution.ExecutionManager;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.filters.ExceptionFilters;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ExecutionConsoleEx;
import com.intellij.execution.ui.RunnerLayoutUi;
import com.intellij.execution.ui.layout.PlaceInGrid;
import com.intellij.icons.AllIcons;
import com.intellij.idea.ActionsBundle;
@@ -56,8 +52,6 @@ import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManagerAdapter;
import com.intellij.ui.content.ContentManagerEvent;
import com.intellij.ui.content.tabs.PinToolwindowTabAction;
import com.intellij.unscramble.ThreadDumpPanel;
import com.intellij.unscramble.ThreadState;
import com.intellij.xdebugger.XDebuggerBundle;
import com.intellij.xdebugger.impl.actions.XDebuggerActions;
import com.intellij.xdebugger.impl.settings.XDebuggerSettingsManager;
@@ -68,7 +62,6 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.util.List;
public class DebuggerSessionTab extends DebuggerSessionTabBase implements Disposable {
private static final Logger LOG = Logger.getInstance(DebuggerSessionTab.class);
@@ -84,7 +77,6 @@ public class DebuggerSessionTab extends DebuggerSessionTabBase implements Dispos
private final DebugUIEnvironment myDebugUIEnvironment;
private final ThreadsPanel myThreadsPanel;
private static final String THREAD_DUMP_CONTENT_PREFIX = "Dump";
public DebuggerSessionTab(final Project project, final String sessionName, @NotNull final DebugUIEnvironment environment,
@NotNull DebuggerSession debuggerSession) {
@@ -447,51 +439,6 @@ public class DebuggerSessionTab extends DebuggerSessionTabBase implements Dispos
myUi.selectAndFocus(myUi.findContent(DebuggerContentInfo.FRAME_CONTENT), true, false);
}
private static int myThreadDumpsCount = 0;
private static int myCurrentThreadDumpId = 1;
public static void addThreadDump(Project project, List<ThreadState> threads, final RunnerLayoutUi ui, DebuggerSession session) {
final TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
consoleBuilder.filters(ExceptionFilters.getFilters(session.getSearchScope()));
final ConsoleView consoleView = consoleBuilder.getConsole();
final DefaultActionGroup toolbarActions = new DefaultActionGroup();
consoleView.allowHeavyFilters();
final ThreadDumpPanel panel = new ThreadDumpPanel(project, consoleView, toolbarActions, threads);
final String id = createThreadDumpContentId();
final Content content = ui.createContent(id, panel, id, null, null);
content.setCloseable(true);
content.setDescription("Thread Dump");
ui.addContent(content);
ui.selectAndFocus(content, true, true);
myThreadDumpsCount += 1;
myCurrentThreadDumpId += 1;
//Disposer.register(this, new Disposable() {
// @Override
// public void dispose() {
// ui.removeContent(content, true);
// }
//});
Disposer.register(content, new Disposable() {
@Override
public void dispose() {
myThreadDumpsCount -= 1;
if (myThreadDumpsCount == 0) {
myCurrentThreadDumpId = 1;
}
}
});
Disposer.register(content, consoleView);
ui.selectAndFocus(content, true, false);
if (threads.size() > 0) {
panel.selectStackFrame(0);
}
}
private static String createThreadDumpContentId() {
return THREAD_DUMP_CONTENT_PREFIX + " #" + myCurrentThreadDumpId;
}
private class MyDebuggerStateManager extends DebuggerStateManager {
@Override
public void fireStateChanged(DebuggerContextImpl newContext, int event) {
@@ -1,190 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.ui;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerInvocationUtil;
import com.intellij.debugger.HelpID;
import com.intellij.debugger.actions.EvaluateActionHandler;
import com.intellij.debugger.engine.evaluation.CodeFragmentFactory;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.impl.PositionUtil;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ex.AbstractDelegatingToRootTraversalPolicy;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class ExpressionEvaluationDialog extends EvaluationDialog {
public ExpressionEvaluationDialog(Project project, TextWithImports defaultExpression) {
super(project, defaultExpression);
setTitle(DebuggerBundle.message("evaluate.expression.dialog.title"));
final KeyStroke expressionStroke = KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.ALT_MASK);
final KeyStroke resultStroke = KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.ALT_MASK);
final JRootPane rootPane = getRootPane();
final AnAction anAction = new AnAction() {
public void actionPerformed(AnActionEvent e) {
getExpressionCombo().requestFocus();
}
};
anAction.registerCustomShortcutSet(new CustomShortcutSet(expressionStroke), rootPane);
addDisposeRunnable(new Runnable() {
public void run() {
anAction.unregisterCustomShortcutSet(rootPane);
}
});
final AnAction anAction2 = new AnAction() {
public void actionPerformed(AnActionEvent e) {
getEvaluationPanel().getWatchTree().requestFocus();
}
};
anAction2.registerCustomShortcutSet(new CustomShortcutSet(resultStroke), rootPane);
addDisposeRunnable(new Runnable() {
public void run() {
anAction2.unregisterCustomShortcutSet(rootPane);
}
});
init();
}
protected DebuggerExpressionComboBox createEditor(final CodeFragmentFactory factory) {
return new DebuggerExpressionComboBox(getProject(), PositionUtil.getContextElement(getDebuggerContext()), "evaluation", factory);
}
protected JComponent createCenterPanel() {
final JPanel panel = new JPanel(new BorderLayout());
final JPanel exprPanel = new JPanel(new BorderLayout(UIUtil.DEFAULT_HGAP, 0));
exprPanel.add(new JLabel(DebuggerBundle.message("label.evaluate.dialog.expression")), BorderLayout.WEST);
exprPanel.add(getExpressionCombo(), BorderLayout.CENTER);
final JBLabel help = new JBLabel("Press Enter to Evaluate or Control+Enter to evaluate and add to the Watches", SwingConstants.RIGHT);
help.setBorder(IdeBorderFactory.createEmptyBorder(2,0,6,0));
help.setComponentStyle(UIUtil.ComponentStyle.SMALL);
help.setFontColor(UIUtil.FontColor.BRIGHTER);
exprPanel.add(help, BorderLayout.SOUTH);
final JPanel resultPanel = new JPanel(new BorderLayout());
//resultPanel.add(new JLabel(DebuggerBundle.message("label.evaluate.dialog.result")), BorderLayout.NORTH);
resultPanel.add(getEvaluationPanel(), BorderLayout.CENTER);
panel.add(exprPanel, BorderLayout.NORTH);
panel.add(resultPanel, BorderLayout.CENTER);
panel.setFocusTraversalPolicyProvider(true);
panel.setFocusTraversalPolicy(new AbstractDelegatingToRootTraversalPolicy() {
@Override
public Component getComponentBefore(Container aContainer, Component aComponent) {
boolean focusExpressionCombo = isParent(aComponent, getEvaluationPanel());
return focusExpressionCombo ? getExpressionCombo().getEditorComponent() : super.getComponentBefore(aContainer, aComponent);
}
@Override
public Component getComponentAfter(Container aContainer, Component aComponent) {
boolean focusEvaluationPanel = isParent(aComponent, exprPanel);
return focusEvaluationPanel ? getEvaluationPanel().getTree() : super.getComponentAfter(aContainer, aComponent);
}
private boolean isParent(@NotNull Component component, @NotNull Container parent) {
for (Component c = component; c != null; c = c.getParent()) {
if (c == parent) {
return true;
}
}
return false;
}
});
return panel;
}
protected void initDialogData(TextWithImports text) {
super.initDialogData(text);
getExpressionCombo().selectAll();
}
private DebuggerExpressionComboBox getExpressionCombo() {
return (DebuggerExpressionComboBox)getEditor();
}
@NotNull
protected Action[] createActions() {
return new Action[] { getOKAction(), getCancelAction(), new SwitchAction(), getHelpAction() } ;
}
@Override
protected void createDefaultActions() {
super.createDefaultActions();
myOKAction = new OkAction(){
@Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
if ((e.getModifiers() & InputEvent.CTRL_MASK) != 0) {
addCurrentExpressionToWatches();
}
}
};
}
private void addCurrentExpressionToWatches() {
final DebuggerSessionTab tab = DebuggerPanelsManager.getInstance(getProject()).getSessionTab();
if (tab != null) {
final TextWithImports evaluate = getCodeToEvaluate();
if (evaluate != null) {
tab.getWatchPanel().getWatchTree().addWatch(evaluate, null);
}
}
}
protected void doHelpAction() {
HelpManager.getInstance().invokeHelp(HelpID.EVALUATE);
}
private class SwitchAction extends AbstractAction {
public SwitchAction() {
putValue(Action.NAME, DebuggerBundle.message("action.evaluate.expression.dialog.switch.mode.description"));
}
public void actionPerformed(ActionEvent e) {
final TextWithImports text = getEditor().getText();
doCancelAction();
DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() {
public void run() {
EvaluateActionHandler.showEvaluationDialog(getProject(), text, DebuggerSettings.EVALUATE_FRAGMENT);
}
});
}
}
}
@@ -1,221 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.ui;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerInvocationUtil;
import com.intellij.debugger.HelpID;
import com.intellij.debugger.actions.EvaluateActionHandler;
import com.intellij.debugger.engine.evaluation.CodeFragmentFactory;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.impl.PositionUtil;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.DimensionService;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* @author lex
*/
public class StatementEvaluationDialog extends EvaluationDialog{
private final JPanel myPanel;
private final Action mySwitchAction = new SwitchAction();
private static final @NonNls String STATEMENT_EDITOR_DIMENSION_KEY = "#com.intellij.debugger.ui.StatementEvaluationDialog.StatementEditor";
private static final @NonNls String EVALUATION_PANEL_DIMENSION_KEY = "#com.intellij.debugger.ui.StatementEvaluationDialog.EvaluationPanel";
public StatementEvaluationDialog(final Project project, TextWithImports text) {
super(project, text);
setTitle(DebuggerBundle.message("evaluate.statement.dialog.title"));
myPanel = new JPanel(new BorderLayout());
final Splitter splitter = new Splitter(true);
splitter.setHonorComponentsMinimumSize(true);
final JPanel editorPanel = new JPanel(new GridBagLayout());
final JLabel statementsLabel = new JLabel(DebuggerBundle.message("label.evaluation.dialog.statements"));
editorPanel.add(statementsLabel, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 0, 0), 0, 0));
editorPanel.add(getStatementEditor(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 2, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 0, 0, 0), 0, 0));
splitter.setFirstComponent(editorPanel);
final MyEvaluationPanel evaluationPanel = getEvaluationPanel();
final JPanel ep = new JPanel(new BorderLayout());
//final JLabel resultLabel = new JLabel(DebuggerBundle.message("label.evaluate.dialog.result"));
//ep.add(resultLabel, BorderLayout.NORTH);
ep.add(evaluationPanel, BorderLayout.CENTER);
splitter.setSecondComponent(ep);
final Dimension statementSize = DimensionService.getInstance().getSize(STATEMENT_EDITOR_DIMENSION_KEY, project);
final Dimension evaluationSize = DimensionService.getInstance().getSize(EVALUATION_PANEL_DIMENSION_KEY, project);
if (statementSize != null && evaluationSize != null) {
final float proportion = (float)statementSize.height / (float)(statementSize.height + evaluationSize.height);
splitter.setProportion(proportion);
}
myPanel.add(splitter, BorderLayout.CENTER);
setDebuggerContext(getDebuggerContext());
final KeyStroke codeFragment = KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.ALT_MASK);
final KeyStroke resultStroke = KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.ALT_MASK);
final KeyStroke altEnter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK);
final JRootPane rootPane = getRootPane();
final AnAction toStatementAction = new AnAction() {
public void actionPerformed(AnActionEvent e) {
getStatementEditor().requestFocus();
}
};
toStatementAction.registerCustomShortcutSet(new CustomShortcutSet(codeFragment), rootPane);
addDisposeRunnable(new Runnable() {
public void run() {
toStatementAction.unregisterCustomShortcutSet(rootPane);
}
});
final AnAction toEvaluationAction = new AnAction() {
public void actionPerformed(AnActionEvent e) {
getEvaluationPanel().getWatchTree().requestFocus();
}
};
toEvaluationAction.registerCustomShortcutSet(new CustomShortcutSet(resultStroke), rootPane);
addDisposeRunnable(new Runnable() {
public void run() {
toEvaluationAction.unregisterCustomShortcutSet(rootPane);
}
});
final AnAction okAction = new AnAction() {
public void actionPerformed(AnActionEvent e) {
doOKAction();
}
};
okAction.registerCustomShortcutSet(new CustomShortcutSet(altEnter), rootPane);
addDisposeRunnable(new Runnable() {
public void run() {
okAction.unregisterCustomShortcutSet(rootPane);
}
});
final DebuggerEditorImpl editor = getEditor();
final DocumentAdapter docListener = new DocumentAdapter() {
public void documentChanged(final DocumentEvent e) {
DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() {
public void run() {
updateSwitchButton(e.getDocument());
}
});
}
};
editor.addDocumentListener(docListener);
addDisposeRunnable(new Runnable() {
public void run() {
editor.removeDocumentListener(docListener);
}
});
init();
}
private void updateSwitchButton(Document document) {
PsiDocumentManager.getInstance(getProject()).commitDocument(document);
PsiFile psiFile = PsiDocumentManager.getInstance(getProject()).getPsiFile(document);
if (psiFile == null) {
return;
}
PsiElement[] children = psiFile.getChildren();
int nonWhite = 0;
for (PsiElement child : children) {
if (!(child instanceof PsiWhiteSpace)) {
nonWhite++;
if (nonWhite > 1) {
mySwitchAction.setEnabled(false);
return;
}
}
}
mySwitchAction.setEnabled(true);
}
@NotNull
protected Action[] createActions(){
return new Action[]{getOKAction(), getCancelAction(), mySwitchAction, getHelpAction() };
}
protected void doHelpAction() {
HelpManager.getInstance().invokeHelp(HelpID.EVALUATE);
}
protected DebuggerEditorImpl createEditor(final CodeFragmentFactory factory) {
return new DebuggerStatementEditor(getProject(), PositionUtil.getContextElement(getDebuggerContext()), "evaluation", factory);
}
public void dispose() {
try {
final DebuggerEditorImpl editor = getEditor();
final DimensionService dimensionService = DimensionService.getInstance();
dimensionService.setSize(STATEMENT_EDITOR_DIMENSION_KEY, editor.getSize(null), getProject());
dimensionService.setSize(EVALUATION_PANEL_DIMENSION_KEY, getEvaluationPanel().getSize(), getProject());
}
finally {
super.dispose();
}
}
protected JComponent createCenterPanel() {
return myPanel;
}
private DebuggerStatementEditor getStatementEditor() {
return (DebuggerStatementEditor)getEditor();
}
private class SwitchAction extends AbstractAction {
public SwitchAction() {
putValue(NAME, DebuggerBundle.message("action.evaluate.statement.dialog.switch.mode.description"));
}
public void actionPerformed(ActionEvent e) {
final TextWithImports text = getEditor().getText();
doCancelAction();
DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() {
public void run() {
EvaluateActionHandler.showEvaluationDialog(getProject(), text, DebuggerSettings.EVALUATE_EXPRESSION);
}
});
}
}
}
@@ -1,53 +0,0 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* User: anna
* Date: 25-Jan-2008
*/
package com.intellij.codeEditor.printing;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.impl.LineMarkersPass;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MethodSeparatorProvider extends FileSeparatorProvider {
@Override
public List<LineMarkerInfo> getFileSeparators(final PsiFile file, final Document document, @Nullable final Editor editor) {
final List<LineMarkerInfo> result = new ArrayList<LineMarkerInfo>();
LineMarkersPass pass = new LineMarkersPass(file.getProject(), file, editor, document, file.getTextRange());
for (LineMarkerInfo lineMarkerInfo : pass.queryLineMarkers()) {
if (lineMarkerInfo.separatorColor != null) {
result.add(lineMarkerInfo);
}
}
Collections.sort(result, new Comparator<LineMarkerInfo>() {
public int compare(final LineMarkerInfo i1, final LineMarkerInfo i2) {
return i1.startOffset - i2.startOffset;
}
});
return result;
}
}
@@ -17,19 +17,18 @@ package com.intellij.psi;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.util.*;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
/**
* User: anna
*/
public class PsiMethodReferenceUtil {
public static final Logger LOG = Logger.getInstance("#" + PsiMethodReferenceUtil.class.getName());
public static boolean hasReceiver(PsiType[] parameterTypes, QualifierResolveResult qualifierResolveResult, PsiMethodReferenceExpression methodRef) {
public static boolean isSecondSearchPossible(PsiType[] parameterTypes,
QualifierResolveResult qualifierResolveResult,
PsiMethodReferenceExpression methodRef) {
if (parameterTypes.length > 0 &&
!methodRef.isConstructor() &&
isStaticallyReferenced(methodRef) &&
@@ -39,38 +38,19 @@ public class PsiMethodReferenceUtil {
return false;
}
public static String checkReturnType(PsiMethodReferenceExpression expression, JavaResolveResult result, PsiType functionalInterfaceType) {
final PsiElement resolve = result.getElement();
if (resolve instanceof PsiMethod) {
final PsiClass containingClass = ((PsiMethod)resolve).getContainingClass();
LOG.assertTrue(containingClass != null);
PsiSubstitutor subst = result.getSubstitutor();
PsiClass qContainingClass = getQualifierResolveResult(expression).getContainingClass();
if (qContainingClass != null && isReceiverType(getFirstParameterType(functionalInterfaceType, expression), qContainingClass, subst)) {
subst = TypeConversionUtil.getClassSubstitutor(containingClass, qContainingClass, subst);
LOG.assertTrue(subst != null);
}
final PsiType interfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(functionalInterfaceType);
PsiType returnType = PsiTypesUtil.patchMethodGetClassReturnType(expression, expression,
(PsiMethod)resolve, null,
PsiUtil.getLanguageLevel(expression));
if (returnType == null) {
returnType = ((PsiMethod)resolve).getReturnType();
}
PsiType methodReturnType = subst.substitute(returnType);
if (interfaceReturnType != null && interfaceReturnType != PsiType.VOID) {
if (methodReturnType == null) {
methodReturnType = JavaPsiFacade.getElementFactory(expression.getProject()).createType(containingClass, subst);
}
if (!TypeConversionUtil.isAssignable(interfaceReturnType, methodReturnType, false)) {
return "Bad return type in method reference: cannot convert " + methodReturnType.getCanonicalText() + " to " + interfaceReturnType.getCanonicalText();
}
}
public static boolean isResolvedBySecondSearch(@NotNull PsiMethodReferenceExpression methodRef,
@Nullable MethodSignature signature,
boolean varArgs,
boolean isStatic,
int parametersCount) {
if (signature == null) {
return false;
}
return null;
final QualifierResolveResult qualifierResolveResult = getQualifierResolveResult(methodRef);
final PsiType[] functionalMethodParameterTypes = signature.getParameterTypes();
return (parametersCount + 1 == functionalMethodParameterTypes.length && !varArgs ||
varArgs && functionalMethodParameterTypes.length > 0 && !isStatic) &&
isSecondSearchPossible(functionalMethodParameterTypes, qualifierResolveResult, methodRef);
}
public static boolean isCorrectAssignment(PsiType[] parameterTypes,
@@ -163,7 +143,7 @@ public class PsiMethodReferenceUtil {
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
final PsiExpression expression = methodReferenceExpression.getQualifierExpression();
if (expression != null) {
final PsiType expressionType = getExpandedType(expression.getType(), expression);
final PsiType expressionType = replaceArrayType(expression.getType(), expression);
PsiClassType.ClassResolveResult result = PsiUtil.resolveGenericsClassInType(expressionType);
containingClass = result.getElement();
if (containingClass != null) {
@@ -182,7 +162,7 @@ public class PsiMethodReferenceUtil {
else {
final PsiTypeElement typeElement = methodReferenceExpression.getQualifierType();
if (typeElement != null) {
PsiType type = getExpandedType(typeElement.getType(), typeElement);
PsiType type = replaceArrayType(typeElement.getType(), typeElement);
PsiClassType.ClassResolveResult result = PsiUtil.resolveGenericsClassInType(type);
containingClass = result.getElement();
if (containingClass != null) {
@@ -209,7 +189,7 @@ public class PsiMethodReferenceUtil {
return false;
}
return TypeConversionUtil.isAssignable(JavaPsiFacade.getElementFactory(containingClass.getProject()).createType(containingClass, psiSubstitutor),
getExpandedType(receiverType, containingClass));
replaceArrayType(receiverType, containingClass));
}
public static PsiType getFirstParameterType(PsiType functionalInterfaceType, PsiElement context) {
@@ -225,10 +205,10 @@ public class PsiMethodReferenceUtil {
return null;
}
private static PsiType getExpandedType(PsiType type, @NotNull PsiElement typeElement) {
private static PsiType replaceArrayType(PsiType type, @NotNull PsiElement context) {
if (type instanceof PsiArrayType) {
type = JavaPsiFacade.getElementFactory(typeElement.getProject())
.getArrayClassType(((PsiArrayType)type).getComponentType(), PsiUtil.getLanguageLevel(typeElement));
type = JavaPsiFacade.getElementFactory(context.getProject())
.getArrayClassType(((PsiArrayType)type).getComponentType(), PsiUtil.getLanguageLevel(context));
}
return type;
}
@@ -256,8 +236,15 @@ public class PsiMethodReferenceUtil {
isMethodStatic = method.hasModifierProperty(PsiModifier.STATIC);
isConstructor = method.isConstructor();
receiverReferenced = hasReceiver(methodRef, method, functionalInterfaceType);
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult);
receiverReferenced = isResolvedBySecondSearch(methodRef,
interfaceMethod != null ? interfaceMethod.getSignature(LambdaUtil.getSubstitutor(interfaceMethod, resolveResult)) : null,
method.isVarArgs(),
isMethodStatic,
method.getParameterList().getParametersCount());
if (method.hasModifierProperty(PsiModifier.ABSTRACT) && qualifier instanceof PsiSuperExpression) {
return "Abstract method '" + method.getName() + "' cannot be accessed directly";
}
@@ -296,27 +283,6 @@ public class PsiMethodReferenceUtil {
return null;
}
public static boolean hasReceiver(@NotNull PsiMethodReferenceExpression methodRef,
@NotNull PsiMethod method) {
return hasReceiver(methodRef, method, methodRef.getFunctionalInterfaceType());
}
private static boolean hasReceiver(@NotNull PsiMethodReferenceExpression methodRef,
@NotNull PsiMethod method,
PsiType functionalInterfaceType) {
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(resolveResult);
final MethodSignature signature = interfaceMethod != null ? interfaceMethod.getSignature(LambdaUtil.getSubstitutor(interfaceMethod, resolveResult)) : null;
if (signature == null) {
return false;
}
final PsiType[] parameterTypes = signature.getParameterTypes();
final QualifierResolveResult qualifierResolveResult = getQualifierResolveResult(methodRef);
return (method.getParameterList().getParametersCount() + 1 == parameterTypes.length ||
method.isVarArgs() && parameterTypes.length > 0 && !method.hasModifierProperty(PsiModifier.STATIC)) &&
hasReceiver(parameterTypes, qualifierResolveResult, methodRef);
}
public static String checkTypeArguments(PsiTypeElement qualifier, PsiType psiType) {
if (psiType instanceof PsiClassType) {
final PsiJavaCodeReferenceElement referenceElement = qualifier.getInnermostComponentReferenceElement();
@@ -331,4 +297,38 @@ public class PsiMethodReferenceUtil {
}
return null;
}
public static String checkReturnType(PsiMethodReferenceExpression expression, JavaResolveResult result, PsiType functionalInterfaceType) {
final PsiElement resolve = result.getElement();
if (resolve instanceof PsiMethod) {
final PsiClass containingClass = ((PsiMethod)resolve).getContainingClass();
LOG.assertTrue(containingClass != null);
PsiSubstitutor subst = result.getSubstitutor();
PsiClass qContainingClass = getQualifierResolveResult(expression).getContainingClass();
if (qContainingClass != null && isReceiverType(getFirstParameterType(functionalInterfaceType, expression), qContainingClass, subst)) {
subst = TypeConversionUtil.getClassSubstitutor(containingClass, qContainingClass, subst);
LOG.assertTrue(subst != null);
}
final PsiType interfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(functionalInterfaceType);
PsiType returnType = PsiTypesUtil.patchMethodGetClassReturnType(expression, expression,
(PsiMethod)resolve, null,
PsiUtil.getLanguageLevel(expression));
if (returnType == null) {
returnType = ((PsiMethod)resolve).getReturnType();
}
PsiType methodReturnType = subst.substitute(returnType);
if (interfaceReturnType != null && interfaceReturnType != PsiType.VOID) {
if (methodReturnType == null) {
methodReturnType = JavaPsiFacade.getElementFactory(expression.getProject()).createType(containingClass, subst);
}
if (!TypeConversionUtil.isAssignable(interfaceReturnType, methodReturnType, false)) {
return "Bad return type in method reference: cannot convert " + methodReturnType.getCanonicalText() + " to " + interfaceReturnType.getCanonicalText();
}
}
}
return null;
}
}
@@ -116,48 +116,36 @@ public class MethodCandidateInfo extends CandidateInfo{
return getApplicabilityLevel();
}
@ApplicabilityLevelConstant int level;
Integer boxedLevel = ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() {
@Override
public Integer compute() {
if (PsiUtil.isLanguageLevel8OrHigher(myArgumentList)) {
PsiSubstitutor substitutor = getSubstitutor(false);
Map<PsiElement, CurrentCandidateProperties> map = CURRENT_CANDIDATE.get();
if (map == null) {
map = ContainerUtil.createConcurrentWeakMap();
CURRENT_CANDIDATE.set(map);
}
final PsiMethod method = getElement();
final CurrentCandidateProperties properties = new CurrentCandidateProperties(method, substitutor, isVarargs(), true);
final CurrentCandidateProperties alreadyThere = map.put(getMarkerList(), properties);
try {
PsiType[] argumentTypes = getArgumentTypes();
if (argumentTypes == null) {
return ApplicabilityLevel.NOT_APPLICABLE;
}
final int applicabilityLevel = PsiUtil.getApplicabilityLevel(method, substitutor, argumentTypes, myLanguageLevel);
if (!isVarargs() && applicabilityLevel < ApplicabilityLevel.FIXED_ARITY) {
return ApplicabilityLevel.NOT_APPLICABLE;
}
return applicabilityLevel;
}
finally {
if (alreadyThere == null) {
map.remove(getMarkerList());
} else {
map.put(getMarkerList(), alreadyThere);
}
}
}
return getApplicabilityLevelInner();
PsiSubstitutor substitutor = getSubstitutor(false);
Map<PsiElement, CurrentCandidateProperties> map = CURRENT_CANDIDATE.get();
if (map == null) {
map = ContainerUtil.createConcurrentWeakMap();
CURRENT_CANDIDATE.set(map);
}
final PsiMethod method = getElement();
final CurrentCandidateProperties properties = new CurrentCandidateProperties(method, substitutor, isVarargs(), true);
final CurrentCandidateProperties alreadyThere = map.put(getMarkerList(), properties);
try {
PsiType[] argumentTypes = getArgumentTypes();
if (argumentTypes == null) {
return ApplicabilityLevel.NOT_APPLICABLE;
}
});
if (boxedLevel == null) {
return getApplicabilityLevel();
level = PsiUtil.getApplicabilityLevel(method, substitutor, argumentTypes, myLanguageLevel);
if (!isVarargs() && level < ApplicabilityLevel.FIXED_ARITY) {
return ApplicabilityLevel.NOT_APPLICABLE;
}
}
finally {
if (alreadyThere == null) {
map.remove(getMarkerList());
} else {
map.put(getMarkerList(), alreadyThere);
}
}
if (level > ApplicabilityLevel.NOT_APPLICABLE && !isTypeArgumentsApplicable(false)) {
level = ApplicabilityLevel.NOT_APPLICABLE;
}
level = boxedLevel;
if (level > ApplicabilityLevel.NOT_APPLICABLE && !isTypeArgumentsApplicable(false)) level = ApplicabilityLevel.NOT_APPLICABLE;
return level;
}
@@ -396,8 +396,17 @@ public class PsiDiamondTypeImpl extends PsiDiamondType {
return parent instanceof PsiNewExpression ? ((PsiNewExpression)parent).getArgumentList() : super.getMarkerList();
}
};
if (!varargs && staticFactoryMethod.isVarArgs() && staticFactoryCandidateInfo.getPertinentApplicabilityLevel() < MethodCandidateInfo.ApplicabilityLevel.FIXED_ARITY) {
return inferTypeParametersForStaticFactory(staticFactoryMethod, expression, parent, true);
if (!varargs && staticFactoryMethod.isVarArgs()) {
final Computable<Integer> computable = new Computable<Integer>() {
@Override
public Integer compute() {
return staticFactoryCandidateInfo.getPertinentApplicabilityLevel();
}
};
final Integer applicability = MethodCandidateInfo.ourOverloadGuard.doPreventingRecursion(expression, true, computable);
if ((applicability != null ? applicability : staticFactoryCandidateInfo.getApplicabilityLevel()) < MethodCandidateInfo.ApplicabilityLevel.FIXED_ARITY) {
return inferTypeParametersForStaticFactory(staticFactoryMethod, expression, parent, true);
}
}
return staticFactoryCandidateInfo.getSubstitutor();
}
@@ -1223,8 +1223,7 @@ public class InferenceSession {
PsiImplUtil.normalizeWildcardTypeByPosition(pType, reference)));
}
}
else if (parameters.length + 1 == functionalMethodParameters.length && !varargs ||
!isStatic && varargs && functionalMethodParameters.length > 0 && PsiMethodReferenceUtil.hasReceiver(reference, method)) { //instance methods
else if (PsiMethodReferenceUtil.isResolvedBySecondSearch(reference, signature, varargs, isStatic, parameters.length)) { //instance methods
initBounds(containingClass.getTypeParameters());
final PsiType pType = signature.getParameterTypes()[0];
@@ -16,10 +16,10 @@
package com.intellij.psi.impl.source.tree.java;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.ParameterTypeInferencePolicy;
import com.intellij.psi.impl.source.resolve.ResolveCache;
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.infos.ClassCandidateInfo;
@@ -38,7 +38,6 @@ import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MethodReferenceResolver implements ResolveCache.PolyVariantContextResolver<PsiMethodReferenceExpressionImpl> {
private static final Logger LOG = Logger.getInstance("#" + MethodReferenceResolver.class.getName());
@@ -214,14 +213,14 @@ public class MethodReferenceResolver implements ResolveCache.PolyVariantContextR
@Nullable
@Override
public CandidateInfo resolveConflict(@NotNull List<CandidateInfo> conflicts) {
protected CandidateInfo guardedOverloadResolution(@NotNull List<CandidateInfo> conflicts) {
if (mySignature == null) return null;
if (conflicts.size() > 1) checkSameSignatures(conflicts);
if (conflicts.size() > 1) checkAccessStaticLevels(conflicts, true);
final PsiType[] argTypes = mySignature.getParameterTypes();
boolean hasReceiver = PsiMethodReferenceUtil.hasReceiver(argTypes, myQualifierResolveResult, myReferenceExpression);
boolean hasReceiver = PsiMethodReferenceUtil.isSecondSearchPossible(argTypes, myQualifierResolveResult, myReferenceExpression);
final List<CandidateInfo> firstCandidates = new ArrayList<CandidateInfo>();
final List<CandidateInfo> secondCandidates = new ArrayList<CandidateInfo>();
@@ -20,6 +20,7 @@ import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.JavaVersionService;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Computable;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiSuperMethodImplUtil;
@@ -68,7 +69,17 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{
}
@Override
public CandidateInfo resolveConflict(@NotNull List<CandidateInfo> conflicts){
public final CandidateInfo resolveConflict(@NotNull final List<CandidateInfo> conflicts){
return MethodCandidateInfo.ourOverloadGuard.doPreventingRecursion(myArgumentsList, true, new Computable<CandidateInfo>() {
@Override
public CandidateInfo compute() {
return guardedOverloadResolution(conflicts);
}
});
}
@Nullable
protected CandidateInfo guardedOverloadResolution(@NotNull List<CandidateInfo> conflicts) {
if (conflicts.isEmpty()) return null;
if (conflicts.size() == 1) return conflicts.get(0);
@@ -0,0 +1,19 @@
import java.util.function.Function;
import java.util.stream.Stream;
class Test {
public Long getKey() {
return 0L;
}
public static void main(Stream<Test> stream) {
stream.map(s -> Inner.of(Test::getKey, s));
}
public static final class Inner<K> {
public static <T> Inner<T> of(final Object key, final Test value) {return null;}
public static <T> Inner<T> of(final Function< T, Long> keyMapper, final Test value) {return null;}
}
}
@@ -0,0 +1,19 @@
import java.util.function.Function;
import java.util.stream.Stream;
class Test {
public Long getKey() {
return 0L;
}
public static void main(Stream<Test> stream) {
stream.map(s -> Inner.of(Test::get<ref>Key, s));
}
public static final class Inner<K> {
public static <T> Inner<T> of(final Object key, final Test value) {return null;}
public static <T> Inner<T> of(final Function< T, Long> keyMapper, final Test value) {return null;}
}
}
@@ -17,14 +17,13 @@ package com.intellij.codeInsight.daemon.lambda;
import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection;
import com.intellij.idea.Bombed;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.testFramework.IdeaTestUtil;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.jetbrains.annotations.NonNls;
import java.util.Calendar;
public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase {
@NonNls static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/lambda/newLambda";
@@ -178,6 +177,10 @@ public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
public void testIDEA136759() throws Exception {
doTest();
}
private void doTest() {
doTest(false);
}
@@ -194,7 +197,7 @@ public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase {
/*
public static Test suite() {
final TestSuite suite = new TestSuite();
for (int i = 0; i < 100; i++) {
for (int i = 0; i < 1000; i++) {
suite.addTestSuite(NewLambdaHighlightingTest.class);
}
return suite;
@@ -32,11 +32,15 @@ public class TypeInference18Test extends ResolveTestCase {
}
public void testSecondConflictResolution() throws Exception {
doTestMethodCall();
}
public void testCachedSubstitutionDuringOverloadResolution() throws Exception {
PsiReference ref = configureByFile("/codeInsight/daemonCodeAnalyzer/lambda/resolve/" + getTestName(false) + ".java");
assertNotNull(ref);
PsiMethodCallExpression methodCallExpression = PsiTreeUtil.getParentOfType(ref.getElement(), PsiMethodCallExpression.class);
PsiMethodReferenceExpression methodCallExpression = PsiTreeUtil.getParentOfType(ref.getElement(), PsiMethodReferenceExpression.class, false);
assertNotNull(methodCallExpression);
assertNotNull(methodCallExpression.resolveMethod());
assertNotNull(methodCallExpression.resolve());
}
private LanguageLevel myOldLanguageLevel;
@@ -55,6 +59,14 @@ public class TypeInference18Test extends ResolveTestCase {
super.tearDown();
}
private void doTestMethodCall() throws Exception {
PsiReference ref = configureByFile("/codeInsight/daemonCodeAnalyzer/lambda/resolve/" + getTestName(false) + ".java");
assertNotNull(ref);
PsiMethodCallExpression methodCallExpression = PsiTreeUtil.getParentOfType(ref.getElement(), PsiMethodCallExpression.class);
assertNotNull(methodCallExpression);
assertNotNull(methodCallExpression.resolveMethod());
}
private void doTest() throws Exception {
PsiReference ref = configureByFile("/codeInsight/daemonCodeAnalyzer/lambda/resolve/" + getTestName(false) + ".java");
assertNotNull(ref);
@@ -165,7 +165,7 @@ class JavaPredefinedConfigurations {
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.typed.symbol"),"'Symbol <'_GenericArgument+>", GENERICS_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.generic.casts"),"( '_Type <'_GenericArgument+> ) '_Expr", GENERICS_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.type.var.substitutions.in.intanceof.with.generic.types"),"'_Expr instanceof '_Type <'Substitutions+> ", GENERICS_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.variables.of.generic.types"),"'_Type <'_GenericArgument+> 'Var = 'Init?;", GENERICS_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.variables.of.generic.types"),"'_Type <'_GenericArgument+> 'Var = '_Init?;", GENERICS_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.diamond.operators"), "new 'ClassName<>('_Argument*)", GENERICS_TYPE),
// Add comments and metadata
@@ -226,7 +226,7 @@ class JavaPredefinedConfigurations {
" public void ejbRemove();\n" +
"}", J2EE_TYPE),
createSearchTemplateInfoSimple(SSRBundle.message("predefined.configuration.ejb.interface"),"interface 'EjbInterface extends EJBObject {\n" +
" 'Type+ 'Method+('ParamType* 'ParamName*);\n" +
" '_Type+ '_Method+('_ParamType* '_ParamName*);\n" +
"}", J2EE_TYPE),
createSearchTemplateInfoSimple(SSRBundle.message("predefined.configuration.servlets"),"public class 'Servlet extends '_ParentClass:*HttpServlet {\n" +
" public void '_InitServletMethod?:init ();\n" +
@@ -243,19 +243,19 @@ class JavaPredefinedConfigurations {
// Misc types
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.serializable.classes.and.their.serialization.implementation"),
"class '_Class implements '_Serializable:*Serializable {\n" +
" static final long 'VersionField?:serialVersionUID = '_VersionFieldInit?;\n" +
"class 'Class implements '_Serializable:*Serializable {\n" +
" static final long '_VersionField?:serialVersionUID = '_VersionFieldInit?;\n" +
" private static final ObjectStreamField[] '_persistentFields?:serialPersistentFields = '_persistentFieldInitial?; \n" +
" private void 'SerializationWriteHandler?:writeObject (ObjectOutputStream '_stream) throws IOException;\n" +
" private void 'SerializationReadHandler?:readObject (ObjectInputStream '_stream2) throws IOException, ClassNotFoundException;\n" +
" Object 'SpecialSerializationReadHandler?:readResolve () throws ObjectStreamException;\n" +
" Object 'SpecialSerializationWriteHandler?:writeReplace () throws ObjectStreamException;\n" +
" private void '_SerializationWriteHandler?:writeObject (ObjectOutputStream '_stream) throws IOException;\n" +
" private void '_SerializationReadHandler?:readObject (ObjectInputStream '_stream2) throws IOException, ClassNotFoundException;\n" +
" Object '_SpecialSerializationReadHandler?:readResolve () throws ObjectStreamException;\n" +
" Object '_SpecialSerializationWriteHandler?:writeReplace () throws ObjectStreamException;\n" +
"}",MISC_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.cloneable.implementations"),
"class '_Class implements '_Interface:*Cloneable {\n" +
" Object 'CloningMethod:*clone ();\n" +
"}",MISC_TYPE),
createSearchTemplateInfoSimple(SSRBundle.message("predefined.configuration.]junit.test.cases"),"public class 'TestCase extends 'TestCaseClazz:*TestCase {\n" +
createSearchTemplateInfoSimple(SSRBundle.message("predefined.configuration.]junit.test.cases"),"public class 'TestCase extends '_TestCaseClazz:*TestCase {\n" +
" public void '_testMethod+:test.* ();\n" +
"}", MISC_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.singletons"),"class 'Class {\n" +
@@ -285,7 +285,7 @@ class JavaPredefinedConfigurations {
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.symbol"),"'Symbol",INTERESTING_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.fields.variables.read"),"'Symbol:[read]",INTERESTING_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.fields_variables.with.given.name.pattern.updated"),"'Symbol:[regex( name ) && write]",INTERESTING_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.usage.of.derived.type.in.cast"),"('CastType:*Base ) 'Expr",INTERESTING_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.usage.of.derived.type.in.cast"),"('CastType:*[regex( Base )]) '_Expr",INTERESTING_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.boxing.in.declarations"),"'_Type:Object|Integer|Boolean|Long|Character|Short|Byte 'Var = '_Value:[exprtype( int|boolean|long|char|short|byte )]",INTERESTING_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.unboxing.in.declarations"),"'_Type:int|boolean|long|char|short|byte 'Var = '_Value:[exprtype( Integer|Boolean|Long|Character|Short|Byte )]",INTERESTING_TYPE),
createSearchTemplateInfo(SSRBundle.message("predefined.configuration.boxing.in.method.calls"),"'_Instance?.'Call('_BeforeParam*,'_Param:[ exprtype( int|boolean|long|char|short|byte ) && formal( Object|Integer|Boolean|Long|Character|Short|Byte )],'_AfterParam*)",INTERESTING_TYPE),
@@ -1,6 +1,7 @@
package com.intellij.refactoring.typeMigration;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiExpression;
@@ -65,7 +66,9 @@ public class TypeConversionDescriptor extends TypeConversionDescriptorBase {
if (getExpression() != null) expression = getExpression();
final Project project = expression.getProject();
final ReplaceOptions options = new ReplaceOptions();
options.setMatchOptions(new MatchOptions());
final MatchOptions matchOptions = new MatchOptions();
matchOptions.setFileType(StdFileTypes.JAVA);
options.setMatchOptions(matchOptions);
final Replacer replacer = new Replacer(project, null);
try {
final String replacement = replacer.testReplace(expression.getText(), getStringToReplace(), getReplaceByString(), options);
Binary file not shown.
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,7 +36,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
/**
@@ -47,7 +46,7 @@ public class ProblemsHolder {
private final InspectionManager myManager;
private final PsiFile myFile;
private final boolean myOnTheFly;
private MyList<ProblemDescriptor> myProblems = new MyList<ProblemDescriptor>();
private final List<ProblemDescriptor> myProblems = new ArrayList<ProblemDescriptor>();
public ProblemsHolder(@NotNull InspectionManager manager, @NotNull PsiFile file, boolean onTheFly) {
myManager = manager;
@@ -126,8 +125,9 @@ public class ProblemsHolder {
ProblemHighlightType highlightType,
String descriptionTemplate,
LocalQuickFix... fixes) {
registerProblem(myManager.createProblemDescriptor(reference.getElement(), reference.getRangeInElement(), descriptionTemplate, highlightType,
myOnTheFly, fixes));
ProblemDescriptor descriptor = myManager.createProblemDescriptor(reference.getElement(), reference.getRangeInElement(), descriptionTemplate, highlightType,
myOnTheFly, fixes);
registerProblem(descriptor);
}
public void registerProblem(@NotNull PsiReference reference) {
@@ -183,10 +183,7 @@ public class ProblemsHolder {
@NotNull
public List<ProblemDescriptor> getResults() {
MyList<ProblemDescriptor> problems = myProblems;
problems.allowModifications(false);
myProblems = new MyList<ProblemDescriptor>();
return problems;
return myProblems;
}
@NotNull
@@ -221,17 +218,4 @@ public class ProblemsHolder {
public final Project getProject() {
return myManager.getProject();
}
private static class MyList<T> extends ArrayList<T> {
private volatile boolean readOnly;
@Override
public boolean add(T o) {
if (readOnly) throw new ConcurrentModificationException();
return super.add(o);
}
private void allowModifications(boolean v) {
readOnly = !v;
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -73,14 +73,15 @@ public abstract class InspectionToolWrapper<T extends InspectionProfileEntry, E
@NotNull
public T getTool() {
if (myTool == null) {
T tool = myTool;
if (tool == null) {
//noinspection unchecked
myTool = (T)myEP.instantiateTool();
if (!myTool.getShortName().equals(myEP.getShortName())) {
LOG.error("Short name not matched for " + myTool.getClass() + ": getShortName() = " + myTool.getShortName() + "; ep.shortName = " + myEP.getShortName());
myTool = tool = (T)myEP.instantiateTool();
if (!tool.getShortName().equals(myEP.getShortName())) {
LOG.error("Short name not matched for " + tool.getClass() + ": getShortName() = " + tool.getShortName() + "; ep.shortName = " + myEP.getShortName());
}
}
return myTool;
return tool;
}
public boolean isInitialized() {
@@ -28,6 +28,7 @@ import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
@@ -37,7 +38,7 @@ import java.util.Set;
public class InspectionToolRegistrar {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionToolRegistrar");
private final List<Factory<InspectionToolWrapper>> myInspectionToolFactories = new ArrayList<Factory<InspectionToolWrapper>>();
private final List<Factory<InspectionToolWrapper>> myInspectionToolFactories = ContainerUtil.createLockFreeCopyOnWriteList();
private boolean myInspectionComponentsLoaded = false;
@@ -47,9 +48,10 @@ public class InspectionToolRegistrar {
Set<InspectionToolProvider> providers = new THashSet<InspectionToolProvider>();
ContainerUtil.addAll(providers, ApplicationManager.getApplication().getComponents(InspectionToolProvider.class));
ContainerUtil.addAll(providers, Extensions.getExtensions(InspectionToolProvider.EXTENSION_POINT_NAME));
registerTools(providers.toArray(new InspectionToolProvider[providers.size()]));
List<Factory<InspectionToolWrapper>> factories = new ArrayList<Factory<InspectionToolWrapper>>();
registerTools(providers, factories);
for (final LocalInspectionEP ep : Extensions.getExtensions(LocalInspectionEP.LOCAL_INSPECTION)) {
myInspectionToolFactories.add(new Factory<InspectionToolWrapper>() {
factories.add(new Factory<InspectionToolWrapper>() {
@Override
public InspectionToolWrapper create() {
return new LocalInspectionToolWrapper(ep);
@@ -57,7 +59,7 @@ public class InspectionToolRegistrar {
});
}
for (final InspectionEP ep : Extensions.getExtensions(InspectionEP.GLOBAL_INSPECTION)) {
myInspectionToolFactories.add(new Factory<InspectionToolWrapper>() {
factories.add(new Factory<InspectionToolWrapper>() {
@Override
public InspectionToolWrapper create() {
return new GlobalInspectionToolWrapper(ep);
@@ -66,7 +68,7 @@ public class InspectionToolRegistrar {
}
for (InspectionToolsFactory factory : Extensions.getExtensions(InspectionToolsFactory.EXTENSION_POINT_NAME)) {
for (final InspectionProfileEntry profileEntry : factory.createTools()) {
myInspectionToolFactories.add(new Factory<InspectionToolWrapper>() {
factories.add(new Factory<InspectionToolWrapper>() {
@Override
public InspectionToolWrapper create() {
return wrapTool(profileEntry);
@@ -74,6 +76,7 @@ public class InspectionToolRegistrar {
});
}
}
myInspectionToolFactories.addAll(factories);
}
}
@@ -88,66 +91,31 @@ public class InspectionToolRegistrar {
throw new RuntimeException("unknown inspection class: " + profileEntry + "; "+profileEntry.getClass());
}
private void registerTools(@NotNull InspectionToolProvider[] providers) {
private static void registerTools(@NotNull Collection<InspectionToolProvider> providers,
@NotNull List<Factory<InspectionToolWrapper>> factories) {
for (InspectionToolProvider provider : providers) {
Class[] classes = provider.getInspectionClasses();
for (Class aClass : classes) {
registerInspectionTool(aClass);
for (final Class aClass : classes) {
Factory<InspectionToolWrapper> factory = new Factory<InspectionToolWrapper>() {
@Override
public InspectionToolWrapper create() {
return wrapTool((InspectionProfileEntry)InspectionToolsRegistrarCore.instantiateTool(aClass));
}
};
factories.add(factory);
}
}
}
@NotNull
private Factory<InspectionToolWrapper> registerInspectionTool(@NotNull final Class aClass) {
if (LocalInspectionTool.class.isAssignableFrom(aClass)) {
return registerLocalInspection(aClass, true);
}
if (GlobalInspectionTool.class.isAssignableFrom(aClass)) {
return registerGlobalInspection(aClass, true);
}
throw new RuntimeException("unknown inspection class: " + aClass);
}
public static InspectionToolRegistrar getInstance() {
return ServiceManager.getService(InspectionToolRegistrar.class);
}
/**
* make sure that it is not too late
*/
@NotNull
private Factory<InspectionToolWrapper> registerInspectionToolFactory(@NotNull Factory<InspectionToolWrapper> factory, boolean store) {
if (store) {
myInspectionToolFactories.add(factory);
}
return factory;
}
@NotNull
private Factory<InspectionToolWrapper> registerLocalInspection(final Class toolClass, boolean store) {
return registerInspectionToolFactory(new Factory<InspectionToolWrapper>() {
@Override
public InspectionToolWrapper create() {
return new LocalInspectionToolWrapper((LocalInspectionTool)InspectionToolsRegistrarCore.instantiateTool(toolClass));
}
}, store);
}
@NotNull
private Factory<InspectionToolWrapper> registerGlobalInspection(@NotNull final Class aClass, boolean store) {
return registerInspectionToolFactory(new Factory<InspectionToolWrapper>() {
@Override
public InspectionToolWrapper create() {
return new GlobalInspectionToolWrapper((GlobalInspectionTool) InspectionToolsRegistrarCore.instantiateTool(aClass));
}
}, store);
}
@NotNull
public List<InspectionToolWrapper> createTools() {
ensureInitialized();
final List<InspectionToolWrapper> tools = ContainerUtil.newArrayListWithCapacity(myInspectionToolFactories.size());
final List<InspectionToolWrapper> tools = new ArrayList<InspectionToolWrapper>(myInspectionToolFactories.size());
for (final Factory<InspectionToolWrapper> factory : myInspectionToolFactories) {
ProgressManager.checkCanceled();
final InspectionToolWrapper toolWrapper = factory.create();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,49 +15,119 @@
*/
package com.intellij.openapi.fileEditor;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.SavingRequestor;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Tracks the correspondence between {@link VirtualFile} instances and corresponding {@link Document} instances.
* Manages the saving of changes to disk.
*/
public abstract class FileDocumentManager implements SavingRequestor {
@NotNull
public static FileDocumentManager getInstance() {
return ApplicationManager.getApplication().getComponent(FileDocumentManager.class);
}
/**
* Returns the document for the specified virtual file.<p/>
*
* Documents are cached on weak or strong references, depending on the nature of the virtual file. If the document for the given virtual file is not yet cached,
* the file's contents are read from VFS and loaded into heap memory. An appropriate encoding is used. All line separators are converted to <code>\n</code>.<p/>
*
* Should be invoked in a read action.
*
* @param file the file for which the document is requested.
* @return the document, or null if the file represents a directory, or is binary without an associated decompiler,
* or is too large.
* @see VirtualFile#contentsToByteArray()
* @see Application#runReadAction(Computable)
*/
@Nullable
public abstract Document getDocument(@NotNull VirtualFile file);
/**
* Returns the document for the specified file which has already been loaded into memory.<p/>
*
* Client code shouldn't normally use this method, because it's unpredictable and any garbage collection can result in it returning null.
*
* @param file the file for which the document is requested.
* @return the document, or null if the specified virtual file hasn't been loaded into memory.
*/
@Nullable
public abstract Document getCachedDocument(@NotNull VirtualFile file);
/**
* Returns the virtual file corresponding to the specified document.
*
* @param document the document for which the virtual file is requested.
* @return the file, or null if the document wasn't created from a virtual file.
*/
@Nullable
public abstract VirtualFile getFile(@NotNull Document document);
/**
* This operation can modify documents that will be saved (due to 'Trip trailing spaces on Save' functionality).
* Saves all unsaved documents to disk. This operation can modify documents that will be saved
* (due to 'Strip trailing spaces on Save' functionality). When saving, <code>\n</code> line separators are converted into
* the ones used normally on the system, or the ones explicitly specified by the user. Encoding settings are honored.<p/>
*
* Should be invoked in a write action.
*/
public abstract void saveAllDocuments();
/**
* This operation can modify the document (due to 'Trip trailing spaces on Save' functionality).
* Saves the specified document to disk. This operation can modify the document (due to 'Strip
* trailing spaces on Save' functionality). When saving, <code>\n</code> line separators are converted into
* the ones used normally on the system, or the ones explicitly specified by the user. Encoding settings are honored.<p/>
*
* Should be invoked in a write action.
* @param document the document to save.
*/
public abstract void saveDocument(@NotNull Document document);
/**
* Saves the document without stripping the trailing spaces or adding a blank line in the end of the file.
* Saves the document without stripping the trailing spaces or adding a blank line in the end of the file.<p/>
*
* Should be invoked in a write action.
*
* @param document the document to save.
*/
public abstract void saveDocumentAsIs(@NotNull Document document);
/**
* Returns all documents that have unsaved changes.
* @return the documents that have unsaved changes.
*/
@NotNull
public abstract Document[] getUnsavedDocuments();
/**
* Checks if the document has unsaved changes.
*
* @param document the document to check.
* @return true if the document has unsaved changes, false otherwise.
*/
public abstract boolean isDocumentUnsaved(@NotNull Document document);
/**
* Checks if the document corresponding to the specified file has unsaved changes.
*
* @param file the file to check.
* @return true if the file has unsaved changes, false otherwise.
*/
public abstract boolean isFileModified(@NotNull VirtualFile file);
/**
* Discards unsaved changes for the specified document and reloads it from disk.
*
* @param document the document to reload.
*/
public abstract void reloadFromDisk(@NotNull Document document);
@NotNull
@@ -77,5 +147,10 @@ public abstract class FileDocumentManager implements SavingRequestor {
return getInstance().requestWriting(document, project);
}
/**
* Discards unsaved changes for the specified files.
*
* @param files the files to discard the changes for.
*/
public abstract void reloadFiles(@NotNull VirtualFile... files);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,6 +29,13 @@ import java.util.EventListener;
* Manages the relationship between documents and PSI trees.
*/
public abstract class PsiDocumentManager {
/**
* Checks if the PSI tree for the specified document is up to date (its state reflects the latest changes made
* to the document content).
*
* @param document the document to check.
* @return true if the PSI tree for the document is up to date, false otherwise.
*/
public abstract boolean isCommitted(@NotNull Document document);
/**
@@ -206,8 +213,22 @@ public abstract class PsiDocumentManager {
*/
public abstract void removeListener(@NotNull Listener listener);
/**
* Checks if the PSI tree corresponding to the specified document has been modified and the changes have not
* yet been applied to the document. Documents in that state cannot be modified directly, because such changes
* would conflict with the pending PSI changes. Changes made through PSI are always applied in the end of a write action,
* and can be applied in the middle of a write action by calling {@link #doPostponedOperationsAndUnblockDocument}.
*
* @param doc the document to check.
* @return true if the corresponding PSI has changes that haven't been applied to the document.
*/
public abstract boolean isDocumentBlockedByPsi(@NotNull Document doc);
/**
* Applies pending changes made through the PSI to the specified document.
*
* @param doc the document to apply the changes to.
*/
public abstract void doPostponedOperationsAndUnblockDocument(@NotNull Document doc);
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ import com.intellij.lang.FileASTNode;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A PSI element representing a file.
@@ -101,5 +100,9 @@ public interface PsiFile extends PsiFileSystemItem {
@Override
FileASTNode getNode();
/**
* Called by the PSI framework when the contents of the file changes. Can be used to invalidate
* file-level caches. If you override this method, you <b>must</b> call the base class implementation.
*/
void subtreeChanged();
}
@@ -44,7 +44,7 @@ public class ErrorDiffTool implements FrameDiffTool {
@NotNull
@Override
public String getName() {
return "Error Viewer";
return "Error viewer";
}
private static class MyViewer implements DiffViewer {
@@ -37,6 +37,6 @@ public class BinaryDiffTool implements FrameDiffTool {
@NotNull
@Override
public String getName() {
return "Binary File Viewer";
return "Binary file viewer";
}
}
@@ -38,6 +38,6 @@ public class DirDiffTool implements FrameDiffTool {
@NotNull
@Override
public String getName() {
return "Directory Viewer";
return "Directory viewer";
}
}
@@ -37,6 +37,6 @@ public class OnesideDiffTool implements FrameDiffTool {
@NotNull
@Override
public String getName() {
return "Oneside Viewer";
return "Oneside viewer";
}
}
@@ -38,6 +38,6 @@ public class SimpleDiffTool implements FrameDiffTool {
@NotNull
@Override
public String getName() {
return "Default Viewer";
return "Default viewer";
}
}
@@ -18,10 +18,10 @@ package com.intellij.diff.tools.util.base;
import org.jetbrains.annotations.NotNull;
public enum HighlightPolicy {
DO_NOT_HIGHLIGHT("Do Not Highlight"),
BY_LINE("By Line"),
BY_WORD("By Word"),
BY_WORD_SPLIT("By Word In Chunks");
DO_NOT_HIGHLIGHT("Do not highlight"),
BY_LINE("Highlight words"),
BY_WORD("Highlight lines"),
BY_WORD_SPLIT("Highlight split changes");
@NotNull private final String myText;
@@ -19,10 +19,10 @@ import com.intellij.diff.comparison.ComparisonPolicy;
import org.jetbrains.annotations.NotNull;
public enum IgnorePolicy {
DEFAULT("Do Not Ignore"),
TRIM_WHITESPACES("Trim Whitespaces"),
IGNORE_WHITESPACES("Ignore Whitespaces"),
IGNORE_WHITESPACES_CHUNKS("Ignore Whitespaces And Empty Lines");
DEFAULT("Do not ignore"),
TRIM_WHITESPACES("Trim whitespaces"),
IGNORE_WHITESPACES("Ignore whitespaces"),
IGNORE_WHITESPACES_CHUNKS("Ignore whitespaces and empty lines");
@NotNull private final String myText;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package com.intellij.dvcs;
import com.intellij.ide.SaveAndSyncHandler;
import com.intellij.ide.SaveAndSyncHandlerImpl;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.application.ApplicationManager;
@@ -133,7 +132,7 @@ public abstract class DvcsPlatformFacadeImpl implements DvcsPlatformFacade {
@NotNull
@Override
public SaveAndSyncHandler getSaveAndSyncHandler() {
return SaveAndSyncHandlerImpl.getInstance();
return SaveAndSyncHandler.getInstance();
}
@Override
@@ -40,12 +40,23 @@ public abstract class AbstractExternalProjectSettingsControl<S extends ExternalP
@NotNull private S myInitialSettings;
@Nullable
private JBCheckBox myUseAutoImportBox;
@Nullable
private JBCheckBox myCreateEmptyContentRootDirectoriesBox;
private boolean myHideUseAutoImportBox;
@NotNull
private ExternalSystemSettingsControlCustomizer myCustomizer;
protected AbstractExternalProjectSettingsControl(@NotNull S initialSettings) {
this(null, initialSettings, null);
}
protected AbstractExternalProjectSettingsControl(@Nullable Project project,
@NotNull S initialSettings,
@Nullable ExternalSystemSettingsControlCustomizer controlCustomizer) {
myProject = project;
myInitialSettings = initialSettings;
myCustomizer = controlCustomizer == null ? new ExternalSystemSettingsControlCustomizer() : controlCustomizer;
}
@NotNull
@@ -53,27 +64,31 @@ public abstract class AbstractExternalProjectSettingsControl<S extends ExternalP
return myInitialSettings;
}
public void hideUseAutoImportBox() {
myHideUseAutoImportBox = true;
}
@Override
public void fillUi(@NotNull PaintAwarePanel canvas, int indentLevel) {
myUseAutoImportBox = new JBCheckBox(ExternalSystemBundle.message("settings.label.use.auto.import"));
myUseAutoImportBox.setVisible(!myHideUseAutoImportBox);
canvas.add(myUseAutoImportBox, ExternalSystemUiUtil.getFillLineConstraints(indentLevel));
myCreateEmptyContentRootDirectoriesBox =
new JBCheckBox(ExternalSystemBundle.message("settings.label.create.empty.content.root.directories"));
canvas.add(myCreateEmptyContentRootDirectoriesBox, ExternalSystemUiUtil.getFillLineConstraints(indentLevel));
if (!myCustomizer.isUseAutoImportBoxHidden()) {
myUseAutoImportBox = new JBCheckBox(ExternalSystemBundle.message("settings.label.use.auto.import"));
canvas.add(myUseAutoImportBox, ExternalSystemUiUtil.getFillLineConstraints(indentLevel));
}
if (!myCustomizer.isCreateEmptyContentRootDirectoriesBoxHidden()) {
myCreateEmptyContentRootDirectoriesBox =
new JBCheckBox(ExternalSystemBundle.message("settings.label.create.empty.content.root.directories"));
canvas.add(myCreateEmptyContentRootDirectoriesBox, ExternalSystemUiUtil.getFillLineConstraints(indentLevel));
}
fillExtraControls(canvas, indentLevel);
}
protected abstract void fillExtraControls(@NotNull PaintAwarePanel content, int indentLevel);
public boolean isModified() {
return myUseAutoImportBox.isSelected() != getInitialSettings().isUseAutoImport()
|| myCreateEmptyContentRootDirectoriesBox.isSelected() != getInitialSettings().isCreateEmptyContentRootDirectories()
|| isExtraSettingModified();
boolean result = false;
if (!myCustomizer.isUseAutoImportBoxHidden() && myUseAutoImportBox != null) {
result = myUseAutoImportBox.isSelected() != getInitialSettings().isUseAutoImport();
}
if (!myCustomizer.isCreateEmptyContentRootDirectoriesBoxHidden() && myCreateEmptyContentRootDirectoriesBox != null) {
result = result || myCreateEmptyContentRootDirectoriesBox.isSelected() != getInitialSettings().isCreateEmptyContentRootDirectories();
}
return result || isExtraSettingModified();
}
protected abstract boolean isExtraSettingModified();
@@ -83,8 +98,12 @@ public abstract class AbstractExternalProjectSettingsControl<S extends ExternalP
}
public void reset(boolean isDefaultModuleCreation) {
myUseAutoImportBox.setSelected(getInitialSettings().isUseAutoImport());
myCreateEmptyContentRootDirectoriesBox.setSelected(getInitialSettings().isCreateEmptyContentRootDirectories());
if (!myCustomizer.isUseAutoImportBoxHidden() && myUseAutoImportBox != null) {
myUseAutoImportBox.setSelected(getInitialSettings().isUseAutoImport());
}
if (!myCustomizer.isCreateEmptyContentRootDirectoriesBoxHidden() && myCreateEmptyContentRootDirectoriesBox != null) {
myCreateEmptyContentRootDirectoriesBox.setSelected(getInitialSettings().isCreateEmptyContentRootDirectories());
}
resetExtraSettings(isDefaultModuleCreation);
}
@@ -92,8 +111,13 @@ public abstract class AbstractExternalProjectSettingsControl<S extends ExternalP
@Override
public void apply(@NotNull S settings) {
settings.setUseAutoImport(myUseAutoImportBox.isSelected());
settings.setCreateEmptyContentRootDirectories(myCreateEmptyContentRootDirectoriesBox.isSelected());
if (!myCustomizer.isUseAutoImportBoxHidden() && myUseAutoImportBox != null) {
settings.setUseAutoImport(myUseAutoImportBox.isSelected());
}
if (!myCustomizer.isCreateEmptyContentRootDirectoriesBoxHidden() && myCreateEmptyContentRootDirectoriesBox != null) {
settings.setCreateEmptyContentRootDirectories(myCreateEmptyContentRootDirectoriesBox.isSelected());
}
if (myInitialSettings.getExternalProjectPath() != null) {
settings.setExternalProjectPath(myInitialSettings.getExternalProjectPath());
}
@@ -112,8 +136,13 @@ public abstract class AbstractExternalProjectSettingsControl<S extends ExternalP
}
public void updateInitialSettings() {
myInitialSettings.setUseAutoImport(myUseAutoImportBox.isSelected());
myInitialSettings.setCreateEmptyContentRootDirectories(myCreateEmptyContentRootDirectoriesBox.isSelected());
if (!myCustomizer.isUseAutoImportBoxHidden() && myUseAutoImportBox != null) {
myInitialSettings.setUseAutoImport(myUseAutoImportBox.isSelected());
}
if (!myCustomizer.isCreateEmptyContentRootDirectoriesBoxHidden() && myCreateEmptyContentRootDirectoriesBox != null) {
myInitialSettings.setCreateEmptyContentRootDirectories(myCreateEmptyContentRootDirectoriesBox.isSelected());
}
updateInitialExtraSettings();
}
@@ -0,0 +1,42 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.externalSystem.service.settings;
/**
* @author Vladislav.Soroka
* @since 2/24/2015
*/
public class ExternalSystemSettingsControlCustomizer {
private boolean hideUseAutoImportBox;
private boolean hideCreateEmptyContentRootDirectoriesBox;
public ExternalSystemSettingsControlCustomizer() {
}
public ExternalSystemSettingsControlCustomizer(boolean hideUseAutoImportBox, boolean hideCreateEmptyContentRootDirectoriesBox) {
this.hideUseAutoImportBox = hideUseAutoImportBox;
this.hideCreateEmptyContentRootDirectoriesBox = hideCreateEmptyContentRootDirectoriesBox;
}
public boolean isUseAutoImportBoxHidden() {
return hideUseAutoImportBox;
}
public boolean isCreateEmptyContentRootDirectoriesBoxHidden() {
return hideCreateEmptyContentRootDirectoriesBox;
}
}
@@ -92,6 +92,7 @@ public class ExternalSystemJdkComboBox extends ComboBoxWithWidePopup {
myProject = project;
}
@NotNull
public ExternalSystemJdkComboBox withoutJre() {
suggestJre = false;
return this;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import com.intellij.CommonBundle;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.extensions.Extensions;
@@ -130,32 +131,39 @@ class ExportToHTMLManager {
}
}
private static boolean exportPsiFile(final PsiFile psiFile, String outputDirectoryName, Project project, HashMap<PsiFile, PsiFile> filesMap) {
ExportToHTMLSettings exportToHTMLSettings = ExportToHTMLSettings.getInstance(project);
private static boolean exportPsiFile(final PsiFile psiFile,
final String outputDirectoryName,
final Project project,
final HashMap<PsiFile, PsiFile> filesMap) {
final ExportToHTMLSettings exportToHTMLSettings = ExportToHTMLSettings.getInstance(project);
if (psiFile instanceof PsiBinaryFile) {
return true;
}
TreeMap<Integer, PsiReference> refMap = null;
for (PrintOption printOption : Extensions.getExtensions(PrintOption.EP_NAME)) {
final TreeMap<Integer, PsiReference> map = printOption.collectReferences(psiFile, filesMap);
if (map != null) {
refMap = new TreeMap<Integer, PsiReference>();
refMap.putAll(map);
}
}
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
TreeMap<Integer, PsiReference> refMap = null;
for (PrintOption printOption : Extensions.getExtensions(PrintOption.EP_NAME)) {
final TreeMap<Integer, PsiReference> map = printOption.collectReferences(psiFile, filesMap);
if (map != null) {
refMap = new TreeMap<Integer, PsiReference>();
refMap.putAll(map);
}
}
String dirName = constructOutputDirectory(psiFile, outputDirectoryName);
HTMLTextPainter textPainter = new HTMLTextPainter(psiFile, project, dirName, exportToHTMLSettings.PRINT_LINE_NUMBERS);
try {
textPainter.paint(refMap, psiFile.getFileType());
}
catch (FileNotFoundException e) {
myLastException = e;
return false;
}
return true;
String dirName = constructOutputDirectory(psiFile, outputDirectoryName);
HTMLTextPainter textPainter = new HTMLTextPainter(psiFile, project, dirName, exportToHTMLSettings.PRINT_LINE_NUMBERS);
try {
textPainter.paint(refMap, psiFile.getFileType());
}
catch (FileNotFoundException e) {
myLastException = e;
}
}
});
return myLastException == null;
}
private static String constructOutputDirectory(PsiFile psiFile, String outputDirectoryName) {
@@ -241,11 +249,18 @@ class ExportToHTMLManager {
final ArrayList<PsiFile> filesList = new ArrayList<PsiFile>();
final boolean isRecursive = myExportToHTMLSettings.isIncludeSubdirectories();
try {
addToPsiFileList(myPsiDirectory, filesList, isRecursive, myOutputDirectoryName);
}
catch (FileNotFoundException e) {
myLastException = e;
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
try {
addToPsiFileList(myPsiDirectory, filesList, isRecursive, myOutputDirectoryName);
}
catch (FileNotFoundException e) {
myLastException = e;
}
}
});
if (myLastException != null) {
return;
}
HashMap<PsiFile, PsiFile> filesMap = new HashMap<PsiFile, PsiFile>();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,21 +21,32 @@
package com.intellij.codeEditor.printing;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.codeInsight.daemon.impl.LineMarkersPass;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class FileSeparatorProvider {
public static FileSeparatorProvider getInstance() {
return ServiceManager.getService(FileSeparatorProvider.class);
}
@Nullable
public List<LineMarkerInfo> getFileSeparators(PsiFile file, final Document document, @Nullable final Editor editor) {
return null;
public static List<LineMarkerInfo> getFileSeparators(PsiFile file, final Document document) {
final List<LineMarkerInfo> result = new ArrayList<LineMarkerInfo>();
LineMarkersPass pass = new LineMarkersPass(file.getProject(), file, null, document, file.getTextRange());
for (LineMarkerInfo lineMarkerInfo : pass.queryLineMarkers()) {
if (lineMarkerInfo.separatorColor != null) {
result.add(lineMarkerInfo);
}
}
Collections.sort(result, new Comparator<LineMarkerInfo>() {
public int compare(final LineMarkerInfo i1, final LineMarkerInfo i2) {
return i1.startOffset - i2.startOffset;
}
});
return result;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,7 +35,6 @@ import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.impl.file.PsiDirectoryFactory;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.ui.JBColor;
import org.jetbrains.annotations.NonNls;
@@ -86,8 +85,7 @@ class HTMLTextPainter {
ArrayList<LineMarkerInfo> methodSeparators = new ArrayList<LineMarkerInfo>();
if (document != null) {
final List<LineMarkerInfo> separators = FileSeparatorProvider.getInstance().getFileSeparators(psiFile, document,
PsiUtilBase.findEditor(psiFile));
final List<LineMarkerInfo> separators = FileSeparatorProvider.getFileSeparators(psiFile, document);
if (separators != null) {
methodSeparators.addAll(separators);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -100,7 +100,7 @@ class TextPainter extends BasePainter {
FileType fileType,
Editor editor) {
this(editorDocument, highlighter, fullFileName, shortFileName, psiFile.getProject(), fileType,
FileSeparatorProvider.getInstance().getFileSeparators(psiFile, editorDocument, editor));
FileSeparatorProvider.getFileSeparators(psiFile, editorDocument));
}
public TextPainter(@NotNull DocumentEx editorDocument,
@@ -109,7 +109,7 @@ public class LineMarkersPass extends TextEditorHighlightingPass implements LineM
myMarkers = mergeLineMarkers(lineMarkers, myEditor);
}
static List<LineMarkerInfo> mergeLineMarkers(@NotNull List<LineMarkerInfo> markers, Editor editor) {
static List<LineMarkerInfo> mergeLineMarkers(@NotNull List<LineMarkerInfo> markers, @Nullable Editor editor) {
List<MergeableLineMarkerInfo> forMerge = new ArrayList<MergeableLineMarkerInfo>();
final Iterator<LineMarkerInfo> iterator = markers.iterator();
while (iterator.hasNext()) {
@@ -285,7 +285,7 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass
PsiElementVisitor visitor = InspectionEngine.createVisitorAndAcceptElements(tool, holder, isOnTheFly, session, elements, languages);
synchronized (init) {
init.add(new InspectionContext(toolWrapper, holder, visitor, languages));
init.add(new InspectionContext(toolWrapper, holder, holder.getResultCount(), visitor, languages));
}
advanceProgress(1);
@@ -311,7 +311,9 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass
context.tool.getTool().inspectionFinished(session, context.holder);
if (context.holder.hasResults()) {
appendDescriptors(myFile, context.holder.getResults(), context.tool);
List<ProblemDescriptor> allProblems = context.holder.getResults();
List<ProblemDescriptor> restProblems = allProblems.subList(context.problemsSize, allProblems.size());
appendDescriptors(myFile, restProblems, context.tool);
}
return true;
}
@@ -698,8 +700,8 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass
}
private static class InspectionResult {
@NotNull public final LocalInspectionToolWrapper tool;
@NotNull public final List<ProblemDescriptor> foundProblems;
@NotNull private final LocalInspectionToolWrapper tool;
@NotNull private final List<ProblemDescriptor> foundProblems;
private InspectionResult(@NotNull LocalInspectionToolWrapper tool, @NotNull List<ProblemDescriptor> foundProblems) {
this.tool = tool;
@@ -710,17 +712,20 @@ public class LocalInspectionsPass extends ProgressableTextEditorHighlightingPass
private static class InspectionContext {
private InspectionContext(@NotNull LocalInspectionToolWrapper tool,
@NotNull ProblemsHolder holder,
int problemsSize, // need this to diff between found problems in visible part and the rest
@NotNull PsiElementVisitor visitor,
@Nullable Collection<String> languageIds) {
this.tool = tool;
this.holder = holder;
this.problemsSize = problemsSize;
this.visitor = visitor;
this.languageIds = languageIds;
}
@NotNull final LocalInspectionToolWrapper tool;
@NotNull final ProblemsHolder holder;
@NotNull final PsiElementVisitor visitor;
@Nullable final Collection<String> languageIds;
@NotNull private final LocalInspectionToolWrapper tool;
@NotNull private final ProblemsHolder holder;
private final int problemsSize;
@NotNull private final PsiElementVisitor visitor;
@Nullable private final Collection<String> languageIds;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,6 +40,7 @@ import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.actions.EditorActionUtil;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProgressIndicator;
@@ -78,7 +79,8 @@ public class ShowIntentionsPass extends TextEditorHighlightingPass {
@NotNull
public static List<HighlightInfo.IntentionActionDescriptor> getAvailableActions(@NotNull final Editor editor, @NotNull final PsiFile file, final int passId) {
final int offset = editor.getCaretModel().getOffset();
final Integer expectedCaretOffset = editor.getUserData(EditorActionUtil.EXPECTED_CARET_OFFSET);
final int offset = expectedCaretOffset != null ? expectedCaretOffset : editor.getCaretModel().getOffset();
final Project project = file.getProject();
final List<HighlightInfo.IntentionActionDescriptor> result = new ArrayList<HighlightInfo.IntentionActionDescriptor>();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -384,12 +384,12 @@ public class GlobalInspectionContextImpl extends GlobalInspectionContextBase imp
JobLauncher.getInstance().invokeConcurrentlyUnderProgress(tools, myProgressIndicator, false, new Processor<GlobalInspectionToolWrapper>() {
@Override
public boolean process(GlobalInspectionToolWrapper toolWrapper) {
GlobalSimpleInspectionTool tool = (GlobalSimpleInspectionTool)toolWrapper.getTool();
ProblemsHolder problemsHolder = new ProblemsHolder(inspectionManager, file, false);
ProblemDescriptionsProcessor problemDescriptionProcessor = getProblemDescriptionProcessor(toolWrapper, wrappersMap);
tool.checkFile(file, inspectionManager, problemsHolder, GlobalInspectionContextImpl.this, problemDescriptionProcessor);
InspectionToolPresentation toolPresentation = getPresentation(toolWrapper);
LocalDescriptorsUtil.addProblemDescriptors(problemsHolder.getResults(), false, GlobalInspectionContextImpl.this, null,
GlobalSimpleInspectionTool tool = (GlobalSimpleInspectionTool)toolWrapper.getTool();
ProblemsHolder holder = new ProblemsHolder(inspectionManager, file, false);
ProblemDescriptionsProcessor problemDescriptionProcessor = getProblemDescriptionProcessor(toolWrapper, wrappersMap);
tool.checkFile(file, inspectionManager, holder, GlobalInspectionContextImpl.this, problemDescriptionProcessor);
InspectionToolPresentation toolPresentation = getPresentation(toolWrapper);
LocalDescriptorsUtil.addProblemDescriptors(holder.getResults(), false, GlobalInspectionContextImpl.this, null,
CONVERT, toolPresentation);
return true;
}
@@ -22,62 +22,46 @@ import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.ui.SizedIcon;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class RunConfigurationsComboBoxAction extends ComboBoxAction implements DumbAware {
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.actions.RunConfigurationAction");
private static final Key<ComboBoxButton> BUTTON_KEY = Key.create("COMBOBOX_BUTTON");
public static final Icon CHECKED_ICON = new SizedIcon(AllIcons.Actions.Checked, 16, 16);
public static final Icon CHECKED_SELECTED_ICON = new SizedIcon(AllIcons.Actions.Checked_selected, 16, 16);
public static final Icon EMPTY_ICON = EmptyIcon.ICON_16;
@Override
public void actionPerformed(final AnActionEvent e) {
final IdeFrame ideFrame = findFrame(e.getData(PlatformDataKeys.CONTEXT_COMPONENT));
final ComboBoxButton button = (ComboBoxButton)ideFrame.getComponent().getRootPane().getClientProperty(BUTTON_KEY);
public void actionPerformed(AnActionEvent e) {
ComboBoxButton button = (ComboBoxButton)e.getPresentation().getClientProperty(CUSTOM_COMPONENT_PROPERTY);
if (button == null || !button.isShowing()) return;
button.showPopup();
}
private static IdeFrame findFrame(final Component component) {
return UIUtil.getParentOfType(IdeFrame.class, component);
}
@Override
public void update(final AnActionEvent e) {
final Presentation presentation = e.getPresentation();
final Project project = e.getData(CommonDataKeys.PROJECT);
public void update(AnActionEvent e) {
Presentation presentation = e.getPresentation();
ComboBoxButton button = (ComboBoxButton)presentation.getClientProperty(CUSTOM_COMPONENT_PROPERTY);
Project project = e.getData(CommonDataKeys.PROJECT);
if (ActionPlaces.isMainMenuOrActionSearch(e.getPlace())) {
presentation.setDescription(ExecutionBundle.message("choose.run.configuration.action.description"));
presentation.setEnabled(findFrame(e.getData(PlatformDataKeys.CONTEXT_COMPONENT)) != null);
presentation.setEnabled(button != null);
return;
}
try {
if (project == null || project.isDisposed() || !project.isInitialized()) {
//if (ProjectManager.getInstance().getOpenProjects().length > 0) {
// // do nothing if frame is not active
// return;
//}
updateButton(null, null, null, presentation);
presentation.setEnabled(false);
}
@@ -135,31 +119,9 @@ public class RunConfigurationsComboBoxAction extends ComboBoxAction implements D
@Override
public JComponent createCustomComponent(final Presentation presentation) {
final ComboBoxButton comboBoxButton = new ComboBoxButton(presentation) {
@Override
public void addNotify() {
super.addNotify(); //To change body of overriden methods use Options | File Templates.;
final IdeFrame frame = findFrame(this);
LOG.assertTrue(frame != null);
frame.getComponent().getRootPane().putClientProperty(BUTTON_KEY, this);
}
@Override
public void removeNotify() {
final IdeFrame frame = findFrame(this);
LOG.assertTrue(frame != null);
frame.getComponent().getRootPane().putClientProperty(BUTTON_KEY, null);
presentation.setIcon(null);
setIcon(null);
super.removeNotify();
}
};
final JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2));
panel.add(comboBoxButton);
panel.setOpaque(false);
return panel;
ComboBoxButton button = new ComboBoxButton(presentation);
button.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2));
return button;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@ import com.intellij.execution.runners.ProgramRunner;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.RunContentManager;
import com.intellij.execution.ui.RunContentManagerImpl;
import com.intellij.ide.SaveAndSyncHandler;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
@@ -45,7 +46,6 @@ import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.ui.docking.DockManager;
import com.intellij.util.Alarm;
import com.intellij.util.SmartList;
@@ -548,7 +548,8 @@ public class ExecutionManagerImpl extends ExecutionManager implements Disposable
if (myProject.isDisposed()) return;
myProject.getMessageBus().syncPublisher(EXECUTION_TOPIC).processTerminated(myProfile, myProcessHandler);
VirtualFileManager.getInstance().asyncRefresh(null);
SaveAndSyncHandler.getInstance().scheduleRefresh();
}
@Override
@@ -1055,8 +1055,6 @@ public class ShowUsagesAction extends AnAction implements PopupAction {
window.validate();
window.repaint();
table.revalidate();
table.repaint();
}
private static Rectangle fitToScreen(@NotNull Dimension newDim, @NotNull RelativePoint popupPosition, JTable table) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,7 +22,6 @@ import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.OptionTag;
import com.intellij.util.xmlb.annotations.Transient;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import java.beans.PropertyChangeListener;
@@ -37,7 +36,7 @@ public class GeneralSettings implements PersistentStateComponent<GeneralSettings
public static final int OPEN_PROJECT_NEW_WINDOW = 0;
public static final int OPEN_PROJECT_SAME_WINDOW = 1;
@NonNls public static final String PROP_INACTIVE_TIMEOUT = "inactiveTimeout";
public static final String PROP_INACTIVE_TIMEOUT = "inactiveTimeout";
private String myBrowserPath = BrowserUtil.getDefaultAlternativeBrowserPath();
private boolean myShowTipsOnStartup = true;
@@ -0,0 +1,37 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide;
import com.intellij.openapi.application.ApplicationManager;
/**
* @author Kirill Likhodedov
*/
public abstract class SaveAndSyncHandler {
public static SaveAndSyncHandler getInstance() {
return ApplicationManager.getApplication().getComponent(SaveAndSyncHandler.class);
}
public abstract void saveProjectsAndDocuments();
public abstract void scheduleRefresh();
public abstract void refreshOpenFiles();
public abstract void blockSaveOnFrameDeactivation();
public abstract void unblockSaveOnFrameDeactivation();
public abstract void blockSyncOnFrameActivation();
public abstract void unblockSyncOnFrameActivation();
}
@@ -1,30 +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 com.intellij.ide;
/**
* @author Kirill Likhodedov
*/
public interface SaveAndSyncHandler {
void blockSaveOnFrameDeactivation();
void unblockSaveOnFrameDeactivation();
void blockSyncOnFrameActivation();
void unblockSyncOnFrameActivation();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,47 +46,35 @@ import java.util.concurrent.atomic.AtomicInteger;
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public class SaveAndSyncHandlerImpl implements ApplicationComponent, SaveAndSyncHandler {
public class SaveAndSyncHandlerImpl extends SaveAndSyncHandler implements ApplicationComponent {
private static final Logger LOG = Logger.getInstance(SaveAndSyncHandler.class);
private final Runnable myIdleListener;
private final PropertyChangeListener myGeneralSettingsListener;
private final GeneralSettings mySettings;
private final ProgressManager myProgressManager;
private final SingleAlarm myRefreshDelayAlarm;
private final AtomicInteger myBlockSaveOnFrameDeactivationCount = new AtomicInteger();
private final AtomicInteger myBlockSyncOnFrameActivationCount = new AtomicInteger();
private final SingleAlarm myRefreshDelayAlarm = new SingleAlarm(new Runnable() {
@Override
public void run() {
if (canSyncOrSave()) {
refreshOpenFiles();
}
maybeRefresh(ModalityState.NON_MODAL);
}
}, 300);
private volatile long myRefreshSessionId = 0;
private long myRefreshSessionId = 0;
public static SaveAndSyncHandlerImpl getInstance() {
return (SaveAndSyncHandlerImpl)ApplicationManager.getApplication().getComponent(SaveAndSyncHandler.class);
}
public SaveAndSyncHandlerImpl(@NotNull FrameStateManager frameStateManager,
@NotNull final FileDocumentManager fileDocumentManager,
@NotNull final GeneralSettings generalSettings,
@NotNull ProgressManager progressManager) {
public SaveAndSyncHandlerImpl(@NotNull GeneralSettings generalSettings,
@NotNull ProgressManager progressManager,
@NotNull FrameStateManager frameStateManager,
@NotNull final FileDocumentManager fileDocumentManager) {
mySettings = generalSettings;
myProgressManager = progressManager;
myIdleListener = new Runnable() {
@Override
public void run() {
if (generalSettings.isAutoSaveIfInactive() && canSyncOrSave()) {
if (mySettings.isAutoSaveIfInactive() && canSyncOrSave()) {
((FileDocumentManagerImpl)fileDocumentManager).saveAllDocuments(false);
}
}
};
IdeEventQueue.getInstance().addIdleListener(myIdleListener, generalSettings.getInactiveTimeout() * 1000);
IdeEventQueue.getInstance().addIdleListener(myIdleListener, mySettings.getInactiveTimeout() * 1000);
myGeneralSettingsListener = new PropertyChangeListener() {
@Override
@@ -99,8 +87,17 @@ public class SaveAndSyncHandlerImpl implements ApplicationComponent, SaveAndSync
}
}
};
mySettings.addPropertyChangeListener(myGeneralSettingsListener);
generalSettings.addPropertyChangeListener(myGeneralSettingsListener);
myRefreshDelayAlarm = new SingleAlarm(new Runnable() {
@Override
public void run() {
if (canSyncOrSave()) {
refreshOpenFiles();
}
maybeRefresh(ModalityState.NON_MODAL);
}
}, 300);
frameStateManager.addListener(new FrameStateListener() {
@Override
@@ -112,13 +109,9 @@ public class SaveAndSyncHandlerImpl implements ApplicationComponent, SaveAndSync
@Override
public void onFrameActivated() {
if (ApplicationManager.getApplication().isDisposed() || !generalSettings.isSyncOnFrameActivation()) {
return;
if (!ApplicationManager.getApplication().isDisposed() && mySettings.isSyncOnFrameActivation()) {
scheduleRefresh();
}
LOG.debug("enter: refreshFiles()");
myRefreshDelayAlarm.cancelAndRequest();
LOG.debug("exit: refreshFiles()");
}
});
}
@@ -130,12 +123,13 @@ public class SaveAndSyncHandlerImpl implements ApplicationComponent, SaveAndSync
}
@Override
public void initComponent() {
}
public void initComponent() { }
@Override
public void disposeComponent() {
GeneralSettings.getInstance().removePropertyChangeListener(myGeneralSettingsListener);
myRefreshDelayAlarm.cancel();
RefreshQueue.getInstance().cancelSession(myRefreshSessionId);
mySettings.removePropertyChangeListener(myGeneralSettingsListener);
IdeEventQueue.getInstance().removeIdleListener(myIdleListener);
}
@@ -143,37 +137,34 @@ public class SaveAndSyncHandlerImpl implements ApplicationComponent, SaveAndSync
return !LaterInvocator.isInModalContext() && !myProgressManager.hasModalProgressIndicator();
}
// made public for tests
@Override
public void saveProjectsAndDocuments() {
if (LOG.isDebugEnabled()) {
LOG.debug("enter: save()");
}
if (ApplicationManager.getApplication().isDisposed()) return;
LOG.debug("enter: save()");
if (myBlockSaveOnFrameDeactivationCount.get() == 0 && GeneralSettings.getInstance().isSaveOnFrameDeactivation()) {
if (!ApplicationManager.getApplication().isDisposed() &&
mySettings.isSaveOnFrameDeactivation() &&
myBlockSaveOnFrameDeactivationCount.get() == 0) {
FileDocumentManager.getInstance().saveAllDocuments();
Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects();
for (Project project : openProjects) {
if (LOG.isDebugEnabled()) {
LOG.debug("save project: " + project);
}
for (Project project : ProjectManagerEx.getInstanceEx().getOpenProjects()) {
if (LOG.isDebugEnabled()) LOG.debug("saving project: " + project);
project.save();
}
if (LOG.isDebugEnabled()) {
LOG.debug("save application settings");
}
LOG.debug("saving application settings");
ApplicationManagerEx.getApplicationEx().saveSettings();
if (LOG.isDebugEnabled()) {
LOG.debug("exit: save()");
}
LOG.debug("exit: save()");
}
}
public void maybeRefresh(@NotNull ModalityState modalityState) {
if (myBlockSyncOnFrameActivationCount.get() == 0 && GeneralSettings.getInstance().isSyncOnFrameActivation()) {
LOG.debug("VFS refresh started");
@Override
public void scheduleRefresh() {
myRefreshDelayAlarm.cancelAndRequest();
}
public void maybeRefresh(@NotNull ModalityState modalityState) {
if (myBlockSyncOnFrameActivationCount.get() == 0 && mySettings.isSyncOnFrameActivation()) {
RefreshQueue queue = RefreshQueue.getInstance();
queue.cancelSession(myRefreshSessionId);
@@ -181,16 +172,15 @@ public class SaveAndSyncHandlerImpl implements ApplicationComponent, SaveAndSync
session.addAllFiles(ManagingFS.getInstance().getLocalRoots());
myRefreshSessionId = session.getId();
session.launch();
LOG.debug("VFS refresh finished");
}
}
public static void refreshOpenFiles() {
@Override
public void refreshOpenFiles() {
List<VirtualFile> files = ContainerUtil.newArrayList();
for (Project project : ProjectManager.getInstance().getOpenProjects()) {
VirtualFile[] projectFiles = FileEditorManager.getInstance(project).getSelectedFiles();
for (VirtualFile file : projectFiles) {
for (VirtualFile file : FileEditorManager.getInstance(project).getSelectedFiles()) {
if (file instanceof NewVirtualFile) {
files.add(file);
}
@@ -15,7 +15,7 @@
*/
package com.intellij.ide.actions;
import com.intellij.ide.SaveAndSyncHandlerImpl;
import com.intellij.ide.SaveAndSyncHandler;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileEditor.FileDocumentManager;
@@ -26,9 +26,7 @@ public class SynchronizeAction extends AnAction implements DumbAware {
@Override
public void actionPerformed(AnActionEvent e) {
FileDocumentManager.getInstance().saveAllDocuments();
SaveAndSyncHandlerImpl.refreshOpenFiles();
SaveAndSyncHandler.getInstance().refreshOpenFiles();
VirtualFileManager.getInstance().refreshWithoutFileWatcher(true);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
@@ -59,7 +60,7 @@ public class InstalledPluginsState {
public boolean hasNewerVersion(@NotNull PluginId id) {
synchronized (myLock) {
return !wasUpdated(id) && myUpdateSettings.myOutdatedPlugins.contains(id.getIdString());
return !wasUpdated(id) && myUpdateSettings.getOutdatedPlugins().contains(id.getIdString());
}
}
@@ -89,13 +90,14 @@ public class InstalledPluginsState {
String idString = id.getIdString();
synchronized (myLock) {
List<String> outdatedPlugins = myUpdateSettings.getOutdatedPlugins();
if (newer) {
if (!myUpdateSettings.myOutdatedPlugins.contains(idString)) {
myUpdateSettings.myOutdatedPlugins.add(idString);
if (!outdatedPlugins.contains(idString)) {
outdatedPlugins.add(idString);
}
}
else {
myUpdateSettings.myOutdatedPlugins.remove(idString);
outdatedPlugins.remove(idString);
}
}
}
@@ -108,7 +110,7 @@ public class InstalledPluginsState {
boolean existing = PluginManager.isPluginInstalled(id);
synchronized (myLock) {
myUpdateSettings.myOutdatedPlugins.remove(id.getIdString());
myUpdateSettings.getOutdatedPlugins().remove(id.getIdString());
if (existing) {
myUpdatedPlugins.put(id, descriptor);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -67,13 +67,13 @@ public class PluginHostsConfigurable extends BaseConfigurable {
public void apply() throws ConfigurationException {
UpdateSettings settings = UpdateSettings.getInstance();
settings.myPluginHosts.clear();
settings.myPluginHosts.addAll(myUpdatesSettingsPanel.getPluginsHosts());
settings.getStoredPluginHosts().clear();
settings.getStoredPluginHosts().addAll(myUpdatesSettingsPanel.getPluginsHosts());
}
@Override
public void reset() {
myUpdatesSettingsPanel.setPluginHosts(UpdateSettings.getInstance().myPluginHosts);
myUpdatesSettingsPanel.setPluginHosts(UpdateSettings.getInstance().getStoredPluginHosts());
}
@Override
@@ -82,7 +82,7 @@ public class PluginHostsConfigurable extends BaseConfigurable {
return false;
}
//noinspection EqualsBetweenInconvertibleTypes
return !UpdateSettings.getInstance().myPluginHosts.equals(myUpdatesSettingsPanel.getPluginsHosts());
return !UpdateSettings.getInstance().getStoredPluginHosts().equals(myUpdatesSettingsPanel.getPluginsHosts());
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -1352,8 +1352,10 @@ public class ApplicationImpl extends PlatformComponentManagerImpl implements App
myDispatcher.getMulticaster().writeActionFinished(action);
}
// public for testing purposes
public void _saveSettings() {
@Override
public void saveSettings() {
if (myDoNotSave) return;
if (mySaveSettingsIsInProgress.compareAndSet(false, true)) {
try {
StoreUtil.save(getStateStore(), null);
@@ -1364,12 +1366,6 @@ public class ApplicationImpl extends PlatformComponentManagerImpl implements App
}
}
@Override
public void saveSettings() {
if (myDoNotSave) return;
_saveSettings();
}
@Override
public void saveAll() {
if (myDoNotSave) return;
@@ -63,19 +63,6 @@ public class EditorComponentImpl extends JComponent implements Scrollable, DataP
return myEditor.visualPositionToXY(magnificationPosition);
}
});
putClientProperty("sun.lwawt.macosx.CInputMethod.selectPreviousGlyph.callback", new Runnable() {
@Override
public void run() {
// This is supposed to be called from sun.lwawt.macosx.CInputMethod class of a custom JDK,
// built for IntelliJ platform running on MacOS.
// This is required to support input of accented characters using press-and-hold method (http://support.apple.com/kb/PH11264).
// Non-patched JDK supports this functionality only for TextComponent/JTextComponent descendants.
int caretOffset = myEditor.getCaretModel().getOffset();
if (caretOffset > 0) {
myEditor.getSelectionModel().setSelection(caretOffset - 1, caretOffset);
}
}
});
myApplication = (ApplicationImpl)ApplicationManager.getApplication();
}
@@ -308,6 +308,9 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
public final boolean myUseNewRendering = Registry.is("editor.new.rendering");
final EditorView myView;
private boolean myCharKeyPressed;
private boolean myNeedToSelectPreviousChar;
private final TIntFunction myLineNumberAreaWidthFunction = new TIntFunction() {
@Override
public int execute(int lineNumber) {
@@ -902,9 +905,10 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
myPanel.add(myScrollPane);
}
myEditorComponent.addKeyListener(new KeyAdapter() {
myEditorComponent.addKeyListener(new KeyListener() {
@Override
public void keyTyped(@NotNull KeyEvent event) {
myNeedToSelectPreviousChar = false;
if (event.isConsumed()) {
return;
}
@@ -912,6 +916,18 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
event.consume();
}
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() >= KeyEvent.VK_A && e.getKeyCode() <= KeyEvent.VK_Z) {
myCharKeyPressed = true;
}
}
@Override
public void keyReleased(KeyEvent e) {
myCharKeyPressed = false;
}
});
MyMouseAdapter mouseAdapter = new MyMouseAdapter();
@@ -5413,6 +5429,9 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
@Override
@Nullable
public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) {
if (myCharKeyPressed) {
myNeedToSelectPreviousChar = true;
}
String text = getSelectionModel().getSelectedText();
return text == null ? null : new AttributedString(text).getIterator();
}
@@ -5457,6 +5476,22 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
}
private void replaceInputMethodText(@NotNull InputMethodEvent e) {
if (myNeedToSelectPreviousChar && SystemInfo.isMac && Registry.is("ide.mac.pressAndHold.workaround")) {
// This is required to support input of accented characters using press-and-hold method (http://support.apple.com/kb/PH11264).
// JDK currently properly supports this functionality only for TextComponent/JTextComponent descendants.
// For our editor component we need this workaround.
myNeedToSelectPreviousChar = false;
getCaretModel().runForEachCaret(new CaretAction() {
@Override
public void perform(Caret caret) {
int caretOffset = caret.getOffset();
if (caretOffset > 0) {
caret.setSelection(caretOffset - 1, caretOffset);
}
}
});
}
int commitCount = e.getCommittedCharacterCount();
AttributedCharacterIterator text = e.getText();
@@ -17,6 +17,7 @@ package com.intellij.openapi.fileChooser.ex;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.SaveAndSyncHandler;
import com.intellij.ide.SaveAndSyncHandlerImpl;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.treeView.NodeRenderer;
@@ -356,7 +357,7 @@ public class FileChooserDialogImpl extends DialogWrapper implements FileChooserD
.subscribe(ApplicationActivationListener.TOPIC, new ApplicationActivationListener.Adapter() {
@Override
public void applicationActivated(IdeFrame ideFrame) {
SaveAndSyncHandlerImpl.getInstance().maybeRefresh(ModalityState.current());
((SaveAndSyncHandlerImpl)SaveAndSyncHandler.getInstance()).maybeRefresh(ModalityState.current());
}
});
@@ -166,6 +166,7 @@ public class FileDocumentManagerImpl extends FileDocumentManager implements Virt
@Override
@Nullable
public Document getDocument(@NotNull final VirtualFile file) {
ApplicationManager.getApplication().assertReadAccessAllowed();
DocumentEx document = (DocumentEx)getCachedDocument(file);
if (document == null) {
if (!file.isValid() || file.isDirectory() ||
@@ -174,7 +175,6 @@ public class FileDocumentManagerImpl extends FileDocumentManager implements Virt
return null;
}
ApplicationManager.getApplication().assertReadAccessAllowed();
final CharSequence text = LoadTextUtil.loadText(file);
synchronized (lock) {
document = (DocumentEx)getCachedDocument(file);
@@ -29,6 +29,7 @@ import com.intellij.openapi.ui.OnePixelDivider;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.OnePixelSplitter;
import com.intellij.ui.components.panels.VerticalLayout;
import com.intellij.ui.treeStructure.SimpleNode;
@@ -40,9 +41,7 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.event.*;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -235,7 +234,9 @@ final class SettingsEditor extends AbstractEditor implements DataProvider {
mySpotlightPainter = new SpotlightPainter(myEditor, this) {
void updateNow() {
Configurable configurable = myFilter.myContext.getCurrentConfigurable();
update(myFilter, configurable, myEditor.getContent(configurable));
if (myTreeView.myTree.hasFocus() || mySearch.getTextEditor().hasFocus()) {
update(myFilter, configurable, myEditor.getContent(configurable));
}
}
};
add(BorderLayout.CENTER, mySplitter);
@@ -250,6 +251,29 @@ final class SettingsEditor extends AbstractEditor implements DataProvider {
myFilter.update(filter, false, true);
myTreeView.select(configurable);
Disposer.register(this, myTreeView);
installSpotlightRemover();
}
private void installSpotlightRemover() {
final FocusAdapter spotlightRemover = new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
final Component comp = e.getOppositeComponent();
if (comp == mySearch.getTextEditor() || comp == myTreeView.myTree) {
return;
}
mySpotlightPainter.update(null, null, null);
}
@Override
public void focusGained(FocusEvent e) {
if (!StringUtil.isEmpty(mySearch.getText())) {
mySpotlightPainter.updateNow();
}
}
};
myTreeView.myTree.addFocusListener(spotlightRemover);
mySearch.getTextEditor().addFocusListener(spotlightRemover);
}
@Override
@@ -631,7 +631,7 @@ public final class UpdateChecker {
private static boolean ourHasFailedPlugins = false;
public static void checkForUpdate(IdeaLoggingEvent event) {
if (!ourHasFailedPlugins && UpdateSettings.getInstance().CHECK_NEEDED) {
if (!ourHasFailedPlugins && UpdateSettings.getInstance().isCheckNeeded()) {
final Throwable throwable = event.getThrowable();
final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(IdeErrorsDialog.findPluginId(throwable));
if (pluginDescriptor != null && !pluginDescriptor.isBundled()) {
@@ -25,6 +25,7 @@ import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginsAdvertiser;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Alarm;
import com.intellij.util.net.NetUtils;
@@ -54,12 +55,13 @@ public class UpdateCheckerComponent implements ApplicationComponent {
public UpdateCheckerComponent(@NotNull Application app, @NotNull UpdateSettings settings) {
mySettings = settings;
if (mySettings.SECURE_CONNECTION && !NetUtils.isSniEnabled()) {
if (mySettings.isSecureConnection() && !NetUtils.isSniEnabled()) {
app.invokeLater(new Runnable() {
@Override
public void run() {
String title = IdeBundle.message("update.notifications.title");
String message = IdeBundle.message("update.sni.disabled.notification");
boolean tooOld = !SystemInfo.isJavaVersionAtLeast("1.7");
String message = IdeBundle.message(tooOld ? "update.sni.not.available.notification" : "update.sni.disabled.notification");
UpdateChecker.NOTIFICATIONS.createNotification(title, message, NotificationType.ERROR, null).notify(null);
}
}, ModalityState.NON_MODAL);
@@ -74,7 +76,7 @@ public class UpdateCheckerComponent implements ApplicationComponent {
}
private void scheduleOnStartCheck(@NotNull Application app) {
if (!mySettings.CHECK_NEEDED || mySettings.SECURE_CONNECTION && !NetUtils.isSniEnabled()) {
if (!mySettings.isCheckNeeded() || mySettings.isSecureConnection() && !NetUtils.isSniEnabled()) {
return;
}
@@ -82,9 +84,9 @@ public class UpdateCheckerComponent implements ApplicationComponent {
@Override
public void appFrameCreated(String[] commandLineArgs, @NotNull Ref<Boolean> willOpenProject) {
String currentBuild = ApplicationInfo.getInstance().getBuild().asString();
long timeToNextCheck = mySettings.LAST_TIME_CHECKED + CHECK_INTERVAL - System.currentTimeMillis();
long timeToNextCheck = mySettings.getLastTimeChecked() + CHECK_INTERVAL - System.currentTimeMillis();
if (StringUtil.compareVersionNumbers(mySettings.LAST_BUILD_CHECKED, currentBuild) < 0 || timeToNextCheck <= 0) {
if (StringUtil.compareVersionNumbers(mySettings.getLasBuildChecked(), currentBuild) < 0 || timeToNextCheck <= 0) {
myCheckRunnable.run();
}
else {
@@ -18,15 +18,13 @@ package com.intellij.openapi.updateSettings.impl;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.DefaultJDOMExternalizer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizableStringList;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.net.NetUtils;
import org.jdom.Element;
import com.intellij.util.xmlb.annotations.CollectionBean;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
@@ -38,94 +36,128 @@ import java.util.List;
@Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml", deprecated = true)
}
)
public class UpdateSettings implements PersistentStateComponent<Element>, UserUpdateSettings {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.updateSettings.impl.UpdateSettings");
public JDOMExternalizableStringList myPluginHosts = new JDOMExternalizableStringList();
public JDOMExternalizableStringList myKnownUpdateChannels = new JDOMExternalizableStringList();
public JDOMExternalizableStringList myIgnoredBuildNumbers = new JDOMExternalizableStringList();
public JDOMExternalizableStringList myOutdatedPlugins = new JDOMExternalizableStringList();
public boolean CHECK_NEEDED = true;
public long LAST_TIME_CHECKED = 0;
public String LAST_BUILD_CHECKED = "";
public String UPDATE_CHANNEL_TYPE = ChannelStatus.RELEASE_CODE;
public boolean SECURE_CONNECTION = false;
public static UpdateSettings getInstance() {
return ServiceManager.getService(UpdateSettings.class);
}
public class UpdateSettings implements PersistentStateComponent<UpdateSettings.State>, UserUpdateSettings {
private State myState = new State();
public UpdateSettings() {
updateDefaultChannel();
}
public static UpdateSettings getInstance() {
return ServiceManager.getService(UpdateSettings.class);
}
static class State {
@CollectionBean
public final List<String> pluginHosts = new SmartList<String>();
@CollectionBean
public final List<String> knownUpdateChannels = new SmartList<String>();
@CollectionBean
public final List<String> ignoredBuildNumbers = new SmartList<String>();
@CollectionBean
public final List<String> outdatedPlugins = new SmartList<String>();
public boolean CHECK_NEEDED = true;
public long LAST_TIME_CHECKED = 0;
public String LAST_BUILD_CHECKED;
public String UPDATE_CHANNEL_TYPE = ChannelStatus.RELEASE_CODE;
public boolean SECURE_CONNECTION = false;
}
@Nullable
public String getLasBuildChecked() {
return myState.LAST_BUILD_CHECKED;
}
@NotNull
public List<String> getStoredPluginHosts() {
return myState.pluginHosts;
}
public boolean isCheckNeeded() {
return myState.CHECK_NEEDED;
}
public void setCheckNeeded(boolean value) {
myState.CHECK_NEEDED = value;
}
public boolean isSecureConnection() {
return myState.SECURE_CONNECTION;
}
public void setSecureConnection(boolean value) {
myState.SECURE_CONNECTION = value;
}
@NotNull
public String getUpdateChannelType() {
return myState.UPDATE_CHANNEL_TYPE;
}
public long getLastTimeChecked() {
return myState.LAST_TIME_CHECKED;
}
public void setUpdateChannelType(@NotNull String value) {
myState.UPDATE_CHANNEL_TYPE = value;
}
@NotNull
public List<String> getOutdatedPlugins() {
return myState.outdatedPlugins;
}
private void updateDefaultChannel() {
if (ApplicationInfoImpl.getShadowInstance().isEAP()) {
UPDATE_CHANNEL_TYPE = ChannelStatus.EAP_CODE;
myState.UPDATE_CHANNEL_TYPE = ChannelStatus.EAP_CODE;
}
}
@SuppressWarnings("deprecation")
@Override
public Element getState() {
Element element = new Element("state");
try {
DefaultJDOMExternalizer.writeExternal(this, element);
}
catch (WriteExternalException e) {
LOG.info(e);
}
return element;
public State getState() {
return myState;
}
@SuppressWarnings("deprecation")
@Override
public void loadState(Element state) {
try {
DefaultJDOMExternalizer.readExternal(this, state);
}
catch (InvalidDataException e) {
LOG.info(e);
}
public void loadState(State state) {
myState = state;
myState.LAST_BUILD_CHECKED = StringUtil.nullize(myState.LAST_BUILD_CHECKED);
updateDefaultChannel();
}
@NotNull
@Override
public List<String> getKnownChannelsIds() {
List<String> ids = new ArrayList<String>();
for (String channel : myKnownUpdateChannels) {
ids.add(channel);
}
return ids;
return new ArrayList<String>(myState.knownUpdateChannels);
}
@Override
public void setKnownChannelIds(@NotNull List<String> ids) {
myKnownUpdateChannels.clear();
myState.knownUpdateChannels.clear();
for (String id : ids) {
myKnownUpdateChannels.add(id);
myState.knownUpdateChannels.add(id);
}
}
public void forgetChannelId(String id) {
myKnownUpdateChannels.remove(id);
myState.knownUpdateChannels.remove(id);
}
@Override
public List<String> getIgnoredBuildNumbers() {
return myIgnoredBuildNumbers;
return myState.ignoredBuildNumbers;
}
@NotNull
@Override
public ChannelStatus getSelectedChannelStatus() {
return ChannelStatus.fromCode(UPDATE_CHANNEL_TYPE);
return ChannelStatus.fromCode(myState.UPDATE_CHANNEL_TYPE);
}
public List<String> getPluginHosts() {
List<String> hosts = new ArrayList<String>(myPluginHosts);
List<String> hosts = new ArrayList<String>(myState.pluginHosts);
String pluginHosts = System.getProperty("idea.plugin.hosts");
if (pluginHosts != null) {
ContainerUtil.addAll(hosts, pluginHosts.split(";"));
@@ -134,15 +166,15 @@ public class UpdateSettings implements PersistentStateComponent<Element>, UserUp
}
public void forceCheckForUpdateAfterRestart() {
LAST_TIME_CHECKED = 0;
myState.LAST_TIME_CHECKED = 0;
}
public void saveLastCheckedInfo() {
LAST_TIME_CHECKED = System.currentTimeMillis();
LAST_BUILD_CHECKED = ApplicationInfo.getInstance().getBuild().asString();
myState.LAST_TIME_CHECKED = System.currentTimeMillis();
myState.LAST_BUILD_CHECKED = ApplicationInfo.getInstance().getBuild().asString();
}
public boolean canUseSecureConnection() {
return SECURE_CONNECTION && NetUtils.isSniEnabled();
return myState.SECURE_CONNECTION && NetUtils.isSniEnabled();
}
}
}
@@ -25,6 +25,7 @@ import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.CollectionComboBoxModel;
import com.intellij.util.net.NetUtils;
import com.intellij.util.text.DateFormatUtil;
@@ -64,6 +65,7 @@ public class UpdateSettingsConfigurable extends BaseConfigurable implements Sear
return "preferences.updates";
}
@Override
@NotNull
public String getId() {
return getHelpTopic();
@@ -79,9 +81,9 @@ public class UpdateSettingsConfigurable extends BaseConfigurable implements Sear
public void apply() throws ConfigurationException {
UpdateSettings settings = UpdateSettings.getInstance();
boolean wasEnabled = settings.CHECK_NEEDED;
settings.CHECK_NEEDED = myUpdatesSettingsPanel.myCheckForUpdates.isSelected();
if (wasEnabled != settings.CHECK_NEEDED) {
boolean wasEnabled = settings.isCheckNeeded();
settings.setCheckNeeded(myUpdatesSettingsPanel.myCheckForUpdates.isSelected());
if (wasEnabled != settings.isCheckNeeded()) {
UpdateCheckerComponent checker = ApplicationManager.getApplication().getComponent(UpdateCheckerComponent.class);
if (checker != null) {
if (wasEnabled) {
@@ -93,27 +95,33 @@ public class UpdateSettingsConfigurable extends BaseConfigurable implements Sear
}
}
settings.UPDATE_CHANNEL_TYPE = myUpdatesSettingsPanel.getSelectedChannelType().getCode();
settings.SECURE_CONNECTION = myUpdatesSettingsPanel.myUseSecureConnection.isSelected();
settings.setUpdateChannelType(myUpdatesSettingsPanel.getSelectedChannelType().getCode());
settings.setSecureConnection(myUpdatesSettingsPanel.myUseSecureConnection.isSelected());
}
@Override
public void reset() {
UpdateSettings settings = UpdateSettings.getInstance();
myUpdatesSettingsPanel.myCheckForUpdates.setSelected(settings.CHECK_NEEDED);
myUpdatesSettingsPanel.myUseSecureConnection.setSelected(settings.SECURE_CONNECTION);
myUpdatesSettingsPanel.myCheckForUpdates.setSelected(settings.isCheckNeeded());
myUpdatesSettingsPanel.myUseSecureConnection.setSelected(settings.isSecureConnection());
myUpdatesSettingsPanel.updateLastCheckedLabel();
myUpdatesSettingsPanel.setSelectedChannelType(ChannelStatus.fromCode(settings.UPDATE_CHANNEL_TYPE));
myUpdatesSettingsPanel.setSelectedChannelType(ChannelStatus.fromCode(settings.getUpdateChannelType()));
}
@Override
public boolean isModified() {
if (myUpdatesSettingsPanel == null) return false;
if (myUpdatesSettingsPanel == null) {
return false;
}
UpdateSettings settings = UpdateSettings.getInstance();
if (settings.CHECK_NEEDED != myUpdatesSettingsPanel.myCheckForUpdates.isSelected()) return true;
if (settings.SECURE_CONNECTION != myUpdatesSettingsPanel.myUseSecureConnection.isSelected()) return true;
if (settings.isCheckNeeded() != myUpdatesSettingsPanel.myCheckForUpdates.isSelected() ||
settings.isSecureConnection() != myUpdatesSettingsPanel.myUseSecureConnection.isSelected()) {
return true;
}
Object channel = myUpdatesSettingsPanel.myUpdateChannels.getSelectedItem();
return channel != null && !channel.equals(ChannelStatus.fromCode(settings.UPDATE_CHANNEL_TYPE));
return channel != null && !channel.equals(ChannelStatus.fromCode(settings.getUpdateChannelType()));
}
@Override
@@ -148,12 +156,13 @@ public class UpdateSettingsConfigurable extends BaseConfigurable implements Sear
myBuildNumber.setText(appInfo.getBuild().asString());
myCheckNow.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myCheckNow));
UpdateSettings settings = new UpdateSettings();
settings.loadState(UpdateSettings.getInstance().getState());
settings.UPDATE_CHANNEL_TYPE = getSelectedChannelType().getCode();
settings.SECURE_CONNECTION = myUseSecureConnection.isSelected();
settings.setUpdateChannelType(getSelectedChannelType().getCode());
settings.setSecureConnection(myUseSecureConnection.isSelected());
UpdateChecker.updateAndShowResult(project, settings);
updateLastCheckedLabel();
}
@@ -163,16 +172,18 @@ public class UpdateSettingsConfigurable extends BaseConfigurable implements Sear
UpdateSettings settings = UpdateSettings.getInstance();
//noinspection unchecked
myUpdateChannels.setModel(new CollectionComboBoxModel(ChannelStatus.all(), ChannelStatus.fromCode(settings.UPDATE_CHANNEL_TYPE)));
myUpdateChannels.setModel(new CollectionComboBoxModel(ChannelStatus.all(), ChannelStatus.fromCode(settings.getUpdateChannelType())));
if (!NetUtils.isSniEnabled()) {
myUseSecureConnection.setEnabled(false);
myUseSecureConnection.setToolTipText(IdeBundle.message("update.sni.disabled.notification"));
boolean tooOld = !SystemInfo.isJavaVersionAtLeast("1.7");
String message = IdeBundle.message(tooOld ? "update.sni.not.available.notification" : "update.sni.disabled.notification");
myUseSecureConnection.setToolTipText(message);
}
}
private void updateLastCheckedLabel() {
long time = UpdateSettings.getInstance().LAST_TIME_CHECKED;
long time = UpdateSettings.getInstance().getLastTimeChecked();
myLastCheckedDate.setText(time == 0 ? IdeBundle.message("updates.last.check.never") : DateFormatUtil.formatPrettyDateTime(time));
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -220,7 +220,9 @@ public class PluginsAdvertiser implements StartupActivity {
@Override
public void runActivity(@NotNull final Project project) {
if (!UpdateSettings.getInstance().CHECK_NEEDED) return;
if (!UpdateSettings.getInstance().isCheckNeeded()) {
return;
}
final UnknownFeaturesCollector collectorSuggester = UnknownFeaturesCollector.getInstance(project);
final Set<UnknownFeature> unknownFeatures = collectorSuggester.getUnknownFeatures();
final KnownExtensions extensions = loadExtensions();
@@ -861,8 +861,8 @@ public class AbstractPopup implements JBPopup {
}
}
};
ListenerUtil.addMouseListener(myCaption, moveListener);
ListenerUtil.addMouseMotionListener(myCaption, moveListener);
myCaption.addMouseListener(moveListener);
myCaption.addMouseMotionListener(moveListener);
final MyContentPanel saved = myContent;
Disposer.register(this, new Disposable() {
@Override
@@ -283,7 +283,7 @@ goto.test.findUsages.subject.title=Test Subjects for {0}
goto.test.notFound=No test subjects found
incremental.search.tooltip.prefix=Search for:
goto.super.field.chooser.title=Choose super field
goto.super.property.chooser.title=Choose super property
goto.super.method.chooser.title=Choose super method
goto.super.method.of.chooser.title=Choose Super Method of {0}
goto.super.method.findUsages.title=Super methods of {0}
@@ -944,6 +944,7 @@ update.downloading.patch.error=Failed to download patch file:\n{0}
update.plugins.update.action=&Update
update.restart.plugins.update.action=&Update and Restart
update.shutdown.plugins.update.action=&Update and Shutdown
update.sni.not.available.notification=Secure update is not supported on Java 6. Sorry.
update.sni.disabled.notification=Secure update is impossible with SNI disabled
hierarchy.method.next.occurence.name=Go to next method
@@ -71,8 +71,6 @@
<refactoring.copyHandler implementation="com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler"/>
<refactoring.moveHandler implementation="com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesHandler" id="moveFileOrDir"/>
<applicationService serviceInterface="com.intellij.codeEditor.printing.FileSeparatorProvider"
serviceImplementation="com.intellij.codeEditor.printing.FileSeparatorProvider"/>
<treeStructureProvider implementation="com.intellij.platform.PlatformProjectViewStructureProvider"/>
@@ -32,6 +32,7 @@ public class StructuralSearchUtil {
@Contract("null -> false")
public static boolean isIdentifier(PsiElement element) {
if (element == null) return false;
final StructuralSearchProfile profile = getProfileByPsiElement(element);
return profile != null && profile.isIdentifier(element);
}
@@ -682,11 +682,9 @@ public class MatcherImpl {
assert targetNode != null : "Could not match down up when no target node";
System.out.println("elementToStartMatching = " + elementToStartMatching.getText());
match(elementToStartMatching);
matchContext.getSink().matchingFinished();
final List<MatchResult> matches = sink.getMatches();
return matches;
return sink.getMatches();
}
private class MatchOneVirtualFile extends MatchOneFile {
@@ -42,6 +42,7 @@ class StringToConstraintsTransformer {
StringBuilder miscBuffer = null;
int anonymousTypedVarsCount = 0;
boolean targetFound = false;
for(int index=0;index < pattern.length();++index) {
char ch = pattern.charAt(index);
@@ -187,6 +188,10 @@ class StringToConstraintsTransformer {
constraint.setMaxCount(maxOccurs);
constraint.setGreedy(greedy);
constraint.setPartOfSearchResults(!anonymous);
if (targetFound && !anonymous) {
throw new MalformedPatternException("Pattern may have only one target");
}
targetFound = !anonymous;
}
if (index < length && pattern.charAt(index) == ':') {
@@ -248,7 +253,19 @@ class StringToConstraintsTransformer {
// eat complete condition
miscBuffer.setLength(0);
for(++index; index < length && ((ch = pattern.charAt(index))!=']' || pattern.charAt(index-1)=='\\'); ++index) {
for(++index; index < length && ((ch = pattern.charAt(index)) != ']' || pattern.charAt(index-1) == '\\'); ++index) {
if (ch == '"') {
miscBuffer.append(ch);
for (++index; index < length && (ch = pattern.charAt(index)) != '"'; ++index) {
if (ch == '\\') {
++index;
if (index >= length) break;
ch = pattern.charAt(index);
}
miscBuffer.append(ch);
}
if (ch != '"') throw new MalformedPatternException(SSRBundle.message("error.expected.end.quote"));
}
miscBuffer.append(ch);
}
if (ch != ']') throw new MalformedPatternException(SSRBundle.message("error.expected.condition.or.bracket"));
@@ -26,10 +26,7 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.structuralsearch.MatchVariableConstraint;
import com.intellij.structuralsearch.NamedScriptableDefinition;
import com.intellij.structuralsearch.ReplacementVariableDefinition;
import com.intellij.structuralsearch.SSRBundle;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.impl.matcher.CompiledPattern;
import com.intellij.structuralsearch.impl.matcher.predicates.ScriptSupport;
import com.intellij.structuralsearch.plugin.replace.ReplaceOptions;
@@ -97,7 +94,7 @@ class EditVarConstraintsDialog extends DialogWrapper {
private static Project myProject;
EditVarConstraintsDialog(final Project project,SearchModel _model,List<Variable> _variables, boolean replaceContext, FileType fileType) {
EditVarConstraintsDialog(final Project project, SearchModel _model, List<Variable> _variables, final FileType fileType) {
super(project, false);
variables = _variables;
@@ -105,13 +102,18 @@ class EditVarConstraintsDialog extends DialogWrapper {
setTitle(SSRBundle.message("editvarcontraints.edit.variables"));
regexp.getDocument().addDocumentListener(new MyDocumentListener(notRegexp, applyWithinTypeHierarchy, wholeWordsOnly));
regexp.getDocument().addDocumentListener(new MyDocumentListener(notRegexp, wholeWordsOnly));
regexp.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
applyWithinTypeHierarchy.setEnabled(e.getDocument().getTextLength() > 0 && fileType == StdFileTypes.JAVA);
}
});
read.addChangeListener(new MyChangeListener(notRead, false));
write.addChangeListener(new MyChangeListener(notWrite, false));
regexprForExprType.getDocument().addDocumentListener(new MyDocumentListener(exprTypeWithinHierarchy, notExprType));
formalArgType.getDocument().addDocumentListener(new MyDocumentListener(formalArgTypeWithinHierarchy, invertFormalArgType));
partOfSearchResults.setEnabled(!replaceContext); // todo: this doesn't do anything
containedInConstraints.setVisible(false);
withinCombo.getComboBox().setEditable(true);
@@ -297,7 +299,16 @@ class EditVarConstraintsDialog extends DialogWrapper {
varInfo.setWithinHierarchy(applyWithinTypeHierarchy.isSelected());
varInfo.setInvertRegExp(notRegexp.isSelected());
varInfo.setPartOfSearchResults(partOfSearchResults.isEnabled() && partOfSearchResults.isSelected());
final boolean target = partOfSearchResults.isSelected();
if (target) {
final MatchOptions matchOptions = configuration.getMatchOptions();
for (String name : matchOptions.getVariableConstraintNames()) {
if (!name.equals(varName)) {
matchOptions.getVariableConstraint(name).setPartOfSearchResults(false);
}
}
}
varInfo.setPartOfSearchResults(target);
varInfo.setInvertExprType(notExprType.isSelected());
varInfo.setNameOfExprType(regexprForExprType.getDocument().getText());
@@ -357,7 +368,8 @@ class EditVarConstraintsDialog extends DialogWrapper {
setSearchConstraintsVisible(true);
}
MatchVariableConstraint varInfo = configuration.getMatchOptions().getVariableConstraint(varName);
final MatchOptions matchOptions = configuration.getMatchOptions();
final MatchVariableConstraint varInfo = matchOptions.getVariableConstraint(varName);
if (varInfo == null) {
notRead.setSelected(false);
@@ -371,7 +383,7 @@ class EditVarConstraintsDialog extends DialogWrapper {
maxoccurs.setText("1");
maxoccursUnlimited.setSelected(false);
applyWithinTypeHierarchy.setSelected(false);
partOfSearchResults.setSelected(false);
partOfSearchResults.setSelected(isTarget(varName, matchOptions));
regexprForExprType.getDocument().setText("");
notExprType.setSelected(false);
@@ -406,7 +418,7 @@ class EditVarConstraintsDialog extends DialogWrapper {
maxoccurs.setText(Integer.toString(varInfo.getMaxCount()));
}
partOfSearchResults.setSelected( partOfSearchResults.isEnabled() && varInfo.isPartOfSearchResults() );
partOfSearchResults.setSelected(isTarget(varName, matchOptions));
exprTypeWithinHierarchy.setSelected(varInfo.isExprTypeWithinHierarchy());
regexprForExprType.getDocument().setText(varInfo.getNameOfExprType());
@@ -427,10 +439,29 @@ class EditVarConstraintsDialog extends DialogWrapper {
containedInConstraints.setVisible(contextVar);
textConstraintsPanel.setVisible(!contextVar);
expressionConstraints.setVisible(!contextVar);
partOfSearchResults.setVisible(!contextVar);
partOfSearchResults.setEnabled(!contextVar);
occurencePanel.setVisible(!contextVar);
}
private static boolean isTarget(String varName, MatchOptions matchOptions) {
if (Configuration.CONTEXT_VAR_NAME.equals(varName)) {
// Complete Match is default target
for (String name : matchOptions.getVariableConstraintNames()) {
if (!name.equals(Configuration.CONTEXT_VAR_NAME)) {
if (matchOptions.getVariableConstraint(name).isPartOfSearchResults()) {
return false;
}
}
}
return true;
}
final MatchVariableConstraint constraint = matchOptions.getVariableConstraint(varName);
if (constraint == null) {
return false;
}
return constraint.isPartOfSearchResults();
}
private void setSearchConstraintsVisible(boolean b) {
textConstraintsPanel.setVisible(b);
occurencePanel.setVisible(b);
@@ -649,7 +649,6 @@ public class SearchDialog extends DialogWrapper {
new EditVarConstraintsDialog(
searchContext.getProject(),
model, getVariablesFromListeners(),
isReplaceDialog(),
(FileType)fileTypes.getSelectedItem()
).show();
initiateValidation();
@@ -210,10 +210,11 @@ error.two.different.type.constraints=Two different type constraints
error.incorrect.regexp.constraint=Incorrect reg exp constraint:{0} for {1}
error.expected.character=Character expected after single quote
error.overflow=Value overflow
error.expected.brace1="Digit, '}' or ',' expected"
error.expected.brace2="Digit or '}' expected"
error.expected.brace1=Digit, '}' or ',' expected
error.expected.brace2=Digit or '}' expected
error.expected.condition=Condition expected after ''{0}''
error.expected.condition.or.bracket=Condition or ']' expected
error.expected.end.quote='"' expected
invalid.modifier.type=Invalid modifier type {0}
SSRInspection.replace.with=Replace with ''{0}''
@@ -1 +1 @@
assertTrue(StrictMath.abs('v1 - 'v2) < 't);
assertTrue(StrictMath.abs('_v1 - '_v2) < '_t);
@@ -22,8 +22,8 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
public void testReplaceInLiterals() {
String s1 = "String ID_SPEED = \"Speed\";";
String s2 = "String 'name = \"'string\";";
String s2_2 = "String 'name = \"'string:[regex( .* )]\";";
String s2 = "String 'name = \"'_string\";";
String s2_2 = "String 'name = \"'_string:[regex( .* )]\";";
String s3 = "VSegAttribute $name$ = new VSegAttribute(\"$string$\");";
String expectedResult = "VSegAttribute ID_SPEED = new VSegAttribute(\"Speed\");";
@@ -58,7 +58,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
String s7 = "IconLoader.getIcon(\"/ant/property.png\");\n" +
"IconLoader.getIcon(\"/ant/another/property.png\");\n";
String s8 = "IconLoader.getIcon(\"/'module/'name:[regex( \\w+ )].png\");";
String s8 = "IconLoader.getIcon(\"/'_module/'_name:[regex( \\w+ )].png\");";
String s9 = "Icons.$module$.$name$;";
String expectedResult3 = "Icons.ant.property;\n" +
"IconLoader.getIcon(\"/ant/another/property.png\");\n";
@@ -101,7 +101,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" JOptionPane.showMessageDialog(null, \"MESSAGE\");\n" +
" }\n" +
"}";
String s2 = "JOptionPane.'showDialog(null, 'msg);";
String s2 = "JOptionPane.'showDialog(null, '_msg);";
String s3 = "//FIXME provide a parent frame\n" +
"JOptionPane.$showDialog$(null, $msg$);";
@@ -125,7 +125,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
);
String s4 = "myButton.setText(\"Ok\");";
String s5 = "'Instance.'MethodCall:[regex( setText )]('Parameter*:[regex( \"Ok\" )]);";
String s5 = "'_Instance.'_MethodCall:[regex( setText )]('_Parameter*:[regex( \"Ok\" )]);";
String s6 = "$Instance$.$MethodCall$(\"OK\");";
String expectedResult2 = "myButton.setText(\"OK\");";
@@ -155,9 +155,9 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" matches = testMatcher.findMatches(s7,s8, options);\n" +
" if (matches.size()!=2) return false;";
String str2=" lastTest = 'Descr;\n" +
" matches = testMatcher.findMatches('In,'Pattern, options);\n" +
" if (matches.size()!='Number) return false;";
String str2=" lastTest = '_Descr;\n" +
" matches = testMatcher.findMatches('_In,'_Pattern, options);\n" +
" if (matches.size()!='_Number) return false;";
String str3 = "assertEquals($Descr$,testMatcher.findMatches($In$,$Pattern$, options).size(),$Number$);";
String expectedResult1 = "// searching for several constructions\n" +
" lastTest = \"several constructions match\";\n" +
@@ -191,7 +191,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
assertEquals("Empty replacement",expectedResult2,actualResult);
String str5 = "testMatcher.findMatches('In,'Pattern, options).size()";
String str5 = "testMatcher.findMatches('_In,'_Pattern, options).size()";
String str6 = "findMatchesCount($In$,$Pattern$)";
String expectedResult3="// searching for several constructions\n" +
" lastTest = \"several constructions match\";\n" +
@@ -220,9 +220,9 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" if (asyncMode) {\n" +
" myTreeModel.nodesWereInserted(parentNode,new int[] {i} );\n" +
" }";
String str11 = " 'parentNode.insert('newNode, 'i);\n" +
String str11 = " '_parentNode.insert('_newNode, '_i);\n" +
" if (asyncMode) {\n" +
" myTreeModel.nodesWereInserted('parentNode,new int[] {'i} );\n" +
" myTreeModel.nodesWereInserted('_parentNode,new int[] {'_i} );\n" +
" }";
String str12 = "addChild($parentNode$,$newNode$, $i$);";
String expectedResult5 = " addChild(parentNode,compositeNode, i);";
@@ -231,7 +231,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
assertEquals( "Array initializer replacement", expectedResult5,actualResult);
String str13 = " aaa(5,6,3,4,1,2);";
String str14 = "aaa('t{2,2},3,4,'q{2,2});";
String str14 = "aaa('_t{2,2},3,4,'_q{2,2});";
String str15 = "aaa($q$,3,4,$t$);";
String expectedResult6 = " aaa(1,2,3,4,5,6);";
@@ -239,7 +239,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
assertEquals("Parameter multiple match",expectedResult6,actualResult);
String str16 = " int c = a();";
String str17 = "'t:a ('q*,'p*)";
String str17 = "'_t:a ('_q*,'_p*)";
String str18 = "$t$($q$,1,$p$)";
String expectedResult7 = " int c = a(1);";
@@ -255,7 +255,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
assertEquals("One substition replacement",expectedResult8,actualResult);
String str22 = " instance.setAAA(anotherInstance.getBBB());";
String str23 = " 'i.'m:set(.+) ('a.'m2:get(.+) ());";
String str23 = " '_i.'_m:set(.+) ('_a.'_m2:get(.+) ());";
String str24 = " $a$.set$m2_1$( $i$.get$m_1$() );";
String expectedResult9 = " anotherInstance.setBBB( instance.getAAA() );";
@@ -291,7 +291,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
String str28 = "UTElementNode elementNode = new UTElementNode(myProject, processedElement, psiFile,\n" +
" processedElement.getTextOffset(), true,\n" +
" !myUsageViewDescriptor.toMarkInvalidOrReadonlyUsages(), null);";
String str29 = "new UTElementNode('param, 'directory, 'null, '0, 'true, !'descr.toMarkInvalidOrReadonlyUsages(),\n" +
String str29 = "new UTElementNode('_param, '_directory, '_null, '_0, '_true, !'_descr.toMarkInvalidOrReadonlyUsages(),\n" +
" 'referencesWord)";
String str30 = "new UTElementNode($param$, $directory$, $null$, $0$, $true$, true,\n" +
" $referencesWord$)";
@@ -314,7 +314,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
);
String s34 = "ParamChecker.isTrue(1==1, \"!!!\");";
String s35 = "ParamChecker.isTrue('expr, 'msg)";
String s35 = "ParamChecker.isTrue('_expr, '_msg)";
String s36 = "assert $expr$ : $msg$";
String expectedResult13 = "assert 1==1 : \"!!!\";";
@@ -346,7 +346,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
);
String s40 = "ParamChecker.instanceOf(queryKey, GroupBySqlTypePolicy.GroupKey.class);";
String s41 = "ParamChecker.instanceOf('obj, 'class.class);";
String s41 = "ParamChecker.instanceOf('_obj, '_class.class);";
String s42 = "assert $obj$ instanceof $class$ : \"$obj$ is an instance of \" + $obj$.getClass() + \"; expected \" + $class$.class;";
String expectedResult15 = "assert queryKey instanceof GroupBySqlTypePolicy.GroupKey : \"queryKey is an instance of \" + queryKey.getClass() + \"; expected \" + GroupBySqlTypePolicy.GroupKey.class;";
@@ -361,7 +361,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" static final String TAG_BEAN_VALUE = \"\";\n" +
"}\n" +
"XmlTag beanTag = rootTag.findSubTag(Wpd.TAG_BEAN_VALUE);";
String s44 = "'Instance?.findSubTag( 'Parameter:[exprtype( *String ) ])";
String s44 = "'_Instance?.findSubTag( '_Parameter:[exprtype( *String ) ])";
String s45 = "jetbrains.fabrique.util.XmlApiUtil.findSubTag($Instance$, $Parameter$)";
String expectedResult16 = "class Wpd {\n" +
" static final String TAG_BEAN_VALUE = \"\";\n" +
@@ -398,7 +398,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
String s49 = "class A {}\n" +
"class B extends A {}\n" +
"A a = new B();";
String s50 = "A 'b = new 'B:*A ();";
String s50 = "A '_b = new '_B:*A ();";
String s51 = "A $b$ = new $B$(\"$b$\");";
String expectedResult18 = "class A {}\n" +
"class B extends A {}\n" +
@@ -430,8 +430,8 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
"} catch(Exception ex) {\n" +
" aaa5();\n" +
"}\n";
String s53 = "try { 'a; } finally {\n" +
" 'b;" +
String s53 = "try { '_a; } finally {\n" +
" '_b;" +
"}";
String s54 = "$a$;";
String expectedResult19 = "aaa();\n" +
@@ -501,7 +501,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
String s64 = "int x = 42;\n" +
"int y = 42; // Stuff";
String s65 = "'Type 'Variable = 'Value; // 'Comment";
String s65 = "'_Type '_Variable = '_Value; // '_Comment";
String s66 = "/**\n" +
" *$Comment$\n" +
" */\n" +
@@ -521,7 +521,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
);
String s61 = "try { 1=1; } catch(Exception e) { 1=1; } catch(Throwable t) { 2=2; }";
String s62 = "try { 'a; } catch(Exception e) { 'b; }";
String s62 = "try { '_a; } catch(Exception e) { '_b; }";
String s63 = "try { $a$; } catch(Exception1 e) { $b$; } catch(Exception2 e) { $b$; }";
String expectedResult22 = "try { 1=1; } catch(Exception1 e) { 1=1; } catch(Exception2 e) { 1=1; } catch (Throwable t) { 2=2; }";
@@ -697,10 +697,10 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
"}";
String s8 = "new Runnable() {\n" +
" public void run() {\n" +
" 'l ();\n" +
" '_l ();\n" +
" }\n" +
" private void 'l () {\n" +
" 'st{2,2};\n" +
" private void '_l () {\n" +
" '_st{2,2};\n" +
" }\n" +
"};";
String s9 = "new My() {\n" +
@@ -980,7 +980,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
options.setToReformatAccordingToStyle(true);
String s1 = "class A { public void b() {} }";
String s2 = "class 'a { 'Other* }";
String s2 = "class 'a { '_Other* }";
String s3 = "class $a$New { Logger LOG; $Other$ }";
String expectedResult = " class ANew {\n" +
" Logger LOG;\n\n" +
@@ -996,7 +996,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
);
String s4 = "class A { class C {} public void b() {} int f; }";
String s5 = "class 'a { 'Other* }";
String s5 = "class 'a { '_Other* }";
String s6 = "class $a$ { Logger LOG; $Other$ }";
String expectedResult2 = " class A {\n" +
" Logger LOG;\n\n" +
@@ -1015,7 +1015,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
);
String s7 = "class A extends B { int c; void b() {} { a = 1; } }";
String s8 = "class 'A extends B { 'Other* }";
String s8 = "class 'A extends B { '_Other* }";
String s9 = "class $A$ extends B2 { $Other$ }";
String expectedResult3 = " class A extends B2 {\n" +
" int c;\n\n" +
@@ -1036,7 +1036,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" public void b() {}\n" +
" int f;\n" +
"}";
String s11 = "class 'a { 'Other* }";
String s11 = "class 'a { '_Other* }";
String s12 = "public class $a$ {\n" +
" $Other$\n" +
"}";
@@ -1068,9 +1068,9 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
"}\n" +
"}";
String s14 = "class 'Class extends Thread {\n" +
" 'Class('ParameterType* 'ParameterName*) {\n" +
"\t super (CustomThreadGroup.getThreadGroup(), 'superarg* );\n" +
" 'Statement*;\n" +
" 'Class('_ParameterType* '_ParameterName*) {\n" +
"\t super (CustomThreadGroup.getThreadGroup(), '_superarg* );\n" +
" '_Statement*;\n" +
" }\n" +
"}";
String s15 = "class $Class$ extends CustomThread {\n" +
@@ -1100,8 +1100,8 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
String s16 = "public class A {}\n" +
"final class B {}";
String s17 = "class 'A { 'Other* }";
String s17_2 = "class 'A { private Log log = LogFactory.createLog(); 'Other* }";
String s17 = "class 'A { '_Other* }";
String s17_2 = "class 'A { private Log log = LogFactory.createLog(); '_Other* }";
String s18 = "class $A$ { private Log log = LogFactory.createLog(); $Other$ }";
String s18_2 = "class $A$ { $Other$ }";
@@ -1116,7 +1116,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
assertEquals("Removing field",expectedResult7,actualResult);
String s19 = "public class A extends Object implements Cloneable {}\n";
String s20 = "class 'A { 'Other* }";
String s20 = "class 'A { '_Other* }";
String s21 = "class $A$ { private Log log = LogFactory.createLog(); $Other$ }";
actualResult = replacer.testReplace(s19,s20,s21,options);
@@ -1124,7 +1124,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
assertEquals("Extends / implements list for class",expectedResult8,actualResult);
String s22 = "public class A<T> { int Afield; }\n";
String s23 = "class 'A { 'Other* }";
String s23 = "class 'A { '_Other* }";
String s24 = "class $A$ { private Log log = LogFactory.createLog(); $Other$ }";
actualResult = replacer.testReplace(s22,s23,s24,options);
@@ -1152,8 +1152,8 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
String s28 = "aaa";
String s29 = "class 'Class {\n" +
" 'Class('ParameterType 'ParameterName) {\n" +
" 'Class('ParameterName);\n" +
" 'Class('_ParameterType '_ParameterName) {\n" +
" 'Class('_ParameterName);\n" +
" }\n" +
"}";
String s30 = "class $Class$ {\n" +
@@ -1177,7 +1177,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" int c; // comment2\n" +
"}";
String s32 = "'Type 'Variable = 'Value?; //'Comment";
String s32 = "'_Type 'Variable = '_Value?; //'_Comment";
String s33 = "/**$Comment$*/\n" +
"$Type$ $Variable$ = $Value$;";
@@ -1212,7 +1212,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
"}";
String s35 = "public interface 'MessageInterface {\n" +
" public static final String 'X = 'VALUE;\n" +
" public static final String '_X = '_VALUE;\n" +
" 'blah*" +
"}";
String s36 = "public interface $MessageInterface$ {\n" +
@@ -1266,7 +1266,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" private int c = 2;\n" +
"}";
String s2 = "@Modifier(\"PackageLocal\") 'Type 'Instance = 'Init?;";
String s2 = "@Modifier(\"PackageLocal\") '_Type '_Instance = '_Init?;";
String s3 = "public $Type$ $Instance$ = $Init$;";
String expectedResult = "class A {\n" +
@@ -1348,7 +1348,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" /**\n" +
" * zzz\n" +
" */\n" +
" void f('t 'p){'s+;}\n" +
" void f('_t '_p){'_s+;}\n" +
"}";
String s3 = "class $c$ {\n" +
" /**\n" +
@@ -1408,13 +1408,13 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
"}";
String s2 = "/**\n" +
"* Created by IntelliJ IDEA.\n" +
"* User: 'USER\n" +
"* Date: 'DATE\n" +
"* Time: 'TIME\n" +
"* User: '_USER\n" +
"* Date: '_DATE\n" +
"* Time: '_TIME\n" +
"* To change this template use File | Settings | File Templates.\n" +
"*/\n" +
"class 'c {\n" +
" 'other*\n" +
" '_other*\n" +
"}";
String s3 = "/**\n" +
"* by: $USER$\n" +
@@ -1469,11 +1469,11 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
public void testClassReplacement9() throws IOException {
String s1 = loadFile("before1.java");
String s2 = "class 'A extends 'TestCaseCass:[regex( .*TestCase ) ] {\n" +
" 'OtherStatement*;\n" +
" public void 'testMethod*:[regex( test.* )] () {\n" +
String s2 = "class 'A extends '_TestCaseCass:[regex( .*TestCase ) ] {\n" +
" '_OtherStatement*;\n" +
" public void '_testMethod*:[regex( test.* )] () {\n" +
" }\n" +
" 'OtherStatement2*;\n" +
" '_OtherStatement2*;\n" +
"}";
String s3 = "class $A$ extends $TestCaseCass$ {\n" +
" $OtherStatement$;\n" +
@@ -1560,7 +1560,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
String actualResult;
String s43 = "public @Deprecated class Foo implements Comparable<Foo> {\n int x;\n void m(){}\n }";
String s44 = "class 'Class implements 'Interface { 'Content* }";
String s44 = "class 'Class implements '_Interface { '_Content* }";
String s45 = "@MyAnnotation\n" +
"class $Class$ implements $Interface$ {$Content$}";
String expectedResult16 = "@MyAnnotation public @Deprecated\n" +
@@ -1579,7 +1579,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
String actualResult;
String s43 = "public @Deprecated class Foo implements Comparable<Foo> {\n int x;\n void m(){}\n }";
String s44 = "class 'Class implements 'Interface {}";
String s44 = "class 'Class implements '_Interface {}";
String s45 = "@MyAnnotation\n" +
"class $Class$ implements $Interface$ {}";
String expectedResult16 = "@MyAnnotation public @Deprecated\n" +
@@ -1794,7 +1794,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" catch (final Exception e)\n" +
" { continue; }\n" +
"}";
String toFind = "try { 'TryStatement*; } catch(Exception 'ExceptionDcl) { 'CatchStatement*; }";
String toFind = "try { '_TryStatement*; } catch(Exception '_ExceptionDcl) { '_CatchStatement*; }";
String replacement = "try { $TryStatement$; }\n" + "catch(Throwable $ExceptionDcl$) { $CatchStatement$; }";
String expectedResult = "for (int i = 0; i < MIMEHelper.MIME_MAP.length; i++)\n" +
"{\n" +
@@ -1841,7 +1841,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" Math.sin(0.5);\n" +
" Math.max(1, 2);\n" +
"}}";
final String what = "Math.'m('a*)";
final String what = "Math.'m('_a*)";
final String by = "Math.$m$($a$)";
options.setToUseStaticImport(true);
@@ -1961,7 +1961,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" } catch (PersistenceException e) {\n" +
" // good\n" +
" }";
String s2 = "try { 'TryStatement; } catch('ExceptionType 'ExceptionDcl) { /* 'CommentContent */ }";
String s2 = "try { '_TryStatement; } catch('_ExceptionType '_ExceptionDcl) { /* '_CommentContent */ }";
String replacement = "try { $TryStatement$; } catch($ExceptionType$ $ExceptionDcl$) { _logger.warning(\"$CommentContent$\", $ExceptionDcl$); }";
String expected = "try { em.persist(p); } catch(PersistenceException e) { _logger.warning(\" good\", e); }";
@@ -2077,9 +2077,9 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
"a = 2;\n" +
"int b = a;\n" +
"b2 = 3;";
String s2 = "int 'a = 'i;\n" +
"'st*;\n" +
"'a = 'c;";
String s2 = "int '_a = '_i;\n" +
"'_st*;\n" +
"'_a = '_c;";
String s3 = "$st$;\n" +
"$c$ = $i$;";
@@ -2092,9 +2092,9 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
actualResult
);
String s2_2 = "int 'a = 'i;\n" +
"'st*;\n" +
"int 'c = 'a;";
String s2_2 = "int '_a = '_i;\n" +
"'_st*;\n" +
"int '_c = '_a;";
String s3_2 = "$st$;\n" +
"int $c$ = $i$;";
String expected_2 = "a = 2;\nint b = 1;\nb2 = 3;";
@@ -2123,7 +2123,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
public void testReplaceMultipleFieldsInSingleDeclaration() {
String source = "abstract class MyClass implements java.util.List {\n private String a, b;\n}";
String search = "class 'Name implements java.util.List {\n 'ClassContent*\n}";
String search = "class 'Name implements java.util.List {\n '_ClassContent*\n}";
String replace = "class $Name$ {\n $ClassContent$\n}";
String expectedResult = "abstract class MyClass {\n private String a,b;\n}";
@@ -2139,7 +2139,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
String source = "import java.io.Externalizable;\n" +
"import java.io.Serializable;\n" +
"abstract class MyClass implements Serializable, java.util.List, Externalizable {}";
String search = "class 'TestCase implements java.util.List, 'others* {\n 'MyClassContent\n}";
String search = "class 'TestCase implements java.util.List, '_others* {\n '_MyClassContent\n}";
String replace = "class $TestCase$ implements $others$ {\n $MyClassContent$\n}";
String expectedResult = "import java.io.Externalizable;\n" +
"import java.io.Serializable;\n" +
@@ -2158,7 +2158,7 @@ public class StructuralReplaceTest extends StructuralReplaceTestCase {
" public void foo() {\n" +
" }\n" +
"}";
String search = "class 'Class {\n 'Content*\n}";
String search = "class 'Class {\n '_Content*\n}";
String replace = "class $Class$ {\n" +
" void x() {}\n" +
" $Content$\n" +
@@ -826,7 +826,7 @@ public class StructuralSearchTest extends StructuralSearchTestCase {
String s10031 = "try { a(); } catch(Exception ex) {} catch(Error error) { 1=1; }\n" +
"try { a(); } catch(Exception ex) {}";
String s10032 = "try { a(); } catch('_Type+ 'Arg+) { 'Statements*; }\n";
String s10032 = "try { a(); } catch('_Type+ 'Arg+) { '_Statements*; }\n";
assertEquals(
"finally matching",
2,
@@ -2440,12 +2440,12 @@ public class StructuralSearchTest extends StructuralSearchTestCase {
"@Foo(value2=baz4) int a3;\n" +
"}";
String s12 = "@Foo(value=baz) int 'a;)";
String s12_2 = "@Foo(value='baz:baz2 ) int 'a;)";
String s12_3 = "@Foo('value:value2 = baz3 ) int 'a;)";
String s12_4 = "@Foo('value:value2 = 'baz3:baz3 ) int 'a;)";
String s12_5 = "@Foo('value:value2 = 'baz3:baz ) int 'a;)";
String s12_6 = "@Foo('value:value2 = 'baz3 ) int 'a;)";
String s12_7 = "@Foo('value:value2 = ) int 'a;";
String s12_2 = "@Foo(value='baz:baz2 ) int '_a;)";
String s12_3 = "@Foo('value:value2 = baz3 ) int '_a;)";
String s12_4 = "@Foo('value:value2 = '_baz3:baz3 ) int '_a;)";
String s12_5 = "@Foo('value:value2 = '_baz3:baz ) int '_a;)";
String s12_6 = "@Foo('value:value2 = '_baz3 ) int '_a;)";
String s12_7 = "@Foo('value:value2 = ) int '_a;";
assertEquals("Find anno parameter value",1,findMatchesCount(s11,s12));
assertEquals("Find anno parameter value",2,findMatchesCount(s11,s12_2));
@@ -4,6 +4,7 @@ import com.intellij.structuralsearch.MalformedPatternException;
import com.intellij.structuralsearch.MatchOptions;
import com.intellij.structuralsearch.MatchVariableConstraint;
import com.intellij.structuralsearch.UnsupportedPatternException;
import com.intellij.structuralsearch.plugin.ui.Configuration;
import org.junit.Before;
import org.junit.Test;
@@ -121,6 +122,14 @@ public class StringToConstraintsTransformerTest {
assertEquals("$a$::$b$", myOptions.getSearchPattern());
}
@Test
public void testScriptEscaping() {
test("'_type 'a:[within( \"if ('_a:[regex( .*e.* )\\]) { '_st*; }\" )] = '_b;");
assertEquals("$type$ $a$ = $b$;", myOptions.getSearchPattern());
final MatchVariableConstraint constraint = myOptions.getVariableConstraint(Configuration.CONTEXT_VAR_NAME);
assertEquals("\"if ('_a:[regex( .*e.* )]) { '_st*; }\"", constraint.getWithinConstraint());
}
private void test(String pattern) {
myOptions.setSearchPattern(pattern);
StringToConstraintsTransformer.transformOldPattern(myOptions);
@@ -440,7 +440,7 @@ public interface CodeInsightTestFixture extends IdeaProjectTestFixture {
GutterMark findGutter(@NotNull @TestDataFile @NonNls String filePath);
@NotNull
Collection<GutterMark> findCaretGutters();
Collection<GutterMark> findGuttersAtCaret();
@NotNull
PsiManager getPsiManager();
@@ -930,7 +930,7 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig
@NotNull
@Override
public Collection<GutterMark> findCaretGutters() {
public Collection<GutterMark> findGuttersAtCaret() {
CommonProcessors.CollectProcessor<GutterMark> processor = new CommonProcessors.CollectProcessor<GutterMark>();
findGutters(processor);
return processor.getResults();
@@ -159,6 +159,8 @@ ide.mac.boldEditorTabs=false
ide.mac.disableMacScrollbars=false
ide.mac.disableMacScrollbars.restartRequired=true
ide.mac.disableMacScrollbars.description=Disables OS X overlay scrollbars
ide.mac.pressAndHold.workaround=true
ide.mac.pressAndHold.workaround.description=Enable workaround for press-and-hold input method for accented characters on Mac OS
ide.perProjectModality=false
ide.perProjectModality.description=New modality approach. All dialogs are DOCUMENT_MODAL expect ide-wide dialogs
@@ -815,7 +815,7 @@ public class ContainerUtil extends ContainerUtilRt {
@Nullable
@Contract(pure=true)
public static <T> T find(@NotNull Iterable<? extends T> iterable, final T equalTo) {
public static <T> T find(@NotNull Iterable<? extends T> iterable, @NotNull final T equalTo) {
return find(iterable, new Condition<T>() {
@Override
public boolean value(final T object) {
@@ -1576,7 +1576,7 @@ public class ContainerUtil extends ContainerUtilRt {
}
}
public static <T> void sort(@NotNull List<T> list, @NotNull Comparator<T> comparator) {
public static <T> void sort(@NotNull List<T> list, @NotNull Comparator<? super T> comparator) {
int size = list.size();
if (size < 2) return;
@@ -92,7 +92,7 @@ public class MostlySingularMultiMap<K, V> implements Serializable {
return myMap.isEmpty();
}
public boolean processForKey(@NotNull K key, @NotNull Processor<V> p) {
public boolean processForKey(@NotNull K key, @NotNull Processor<? super V> p) {
return processValue(p, myMap.get(key));
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,7 +31,7 @@ import java.util.Map;
abstract class AbstractCollectionBinding extends Binding implements MultiNodeBinding {
private Map<Class, Binding> myElementBindings;
private final Class myElementType;
private final Class<?> myElementType;
private final String myTagName;
private final AbstractCollection myAnnotation;
@@ -247,7 +247,7 @@ abstract class AbstractCollectionBinding extends Binding implements MultiNodeBin
return myAnnotation == null || myAnnotation.surroundWithTag() ? getCollectionTagName(target) : null;
}
protected String getCollectionTagName(final Object target) {
protected String getCollectionTagName(Object target) {
return myTagName;
}
}
@@ -301,14 +301,17 @@ class BeanBinding extends Binding {
do {
for (Field field : currentClass.getDeclaredFields()) {
int modifiers = field.getModifiers();
//noinspection deprecation
if (!Modifier.isStatic(modifiers) &&
(field.getAnnotation(OptionTag.class) != null ||
field.getAnnotation(Tag.class) != null ||
field.getAnnotation(Attribute.class) != null ||
field.getAnnotation(Property.class) != null ||
field.getAnnotation(Text.class) != null ||
field.getAnnotation(CollectionBean.class) != null ||
(Modifier.isPublic(modifiers) &&
!Modifier.isFinal(modifiers) &&
// we don't want to allow final fields of all types, but only supported
(!Modifier.isFinal(modifiers) || Collection.class.isAssignableFrom(field.getType())) &&
!Modifier.isTransient(modifiers) &&
field.getAnnotation(Transient.class) == null))) {
accessors.add(new FieldAccessor(field));
@@ -361,7 +364,7 @@ class BeanBinding extends Binding {
return new TextBinding(accessor);
}
if (binding instanceof JDOMExternalizableStringListBinding) {
if (binding instanceof CompactCollectionBinding) {
return new AccessorBindingWrapper(accessor, binding);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,16 +22,13 @@ import java.lang.reflect.Type;
import java.util.*;
class CollectionBinding extends AbstractCollectionBinding {
public CollectionBinding(ParameterizedType type, final Accessor accessor) {
public CollectionBinding(ParameterizedType type, Accessor accessor) {
super(getComponentClass(type), Constants.COLLECTION, accessor);
}
private static Class getComponentClass(ParameterizedType type) {
private static Class getComponentClass(@NotNull ParameterizedType type) {
Type arg = type.getActualTypeArguments()[0];
if (arg instanceof ParameterizedType) {
return (Class)((ParameterizedType)arg).getRawType();
}
return (Class)arg;
return arg instanceof ParameterizedType ? (Class)((ParameterizedType)arg).getRawType() : (Class)arg;
}
@Override
@@ -58,7 +55,7 @@ class CollectionBinding extends AbstractCollectionBinding {
}
@Override
protected String getCollectionTagName(final Object target) {
protected String getCollectionTagName(Object target) {
if (target instanceof Set) {
return Constants.SET;
}
@@ -0,0 +1,116 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xmlb;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* @see com.intellij.util.xmlb.annotations.CollectionBean
*/
class CompactCollectionBinding extends Binding {
private final String name;
protected CompactCollectionBinding(@NotNull Accessor accessor) {
super(accessor);
name = myAccessor.getName();
}
@Nullable
@Override
public Object serialize(Object o, @Nullable Object context, SerializationFilter filter) {
Element result = new Element(name);
@SuppressWarnings("unchecked")
List<String> list = (List<String>)o;
if (list == null || list.isEmpty()) {
return result;
}
for (String item : list) {
result.addContent(new Element("item").setAttribute("value", item));
}
return result;
}
@Nullable
@Override
public Object deserialize(Object context, @NotNull Object node) {
@SuppressWarnings("unchecked")
List<String> list = (List<String>)context;
list.clear();
Element element = (Element)node;
if (element.getName().equals(name)) {
for (Element item : element.getChildren("item")) {
ContainerUtil.addIfNotNull(list, item.getAttributeValue("value"));
}
}
else {
// JDOMExternalizableStringList format
Element value = element.getChild("value");
if (value != null) {
value = value.getChild("list");
}
if (value != null) {
for (Element item : value.getChildren("item")) {
//noinspection SpellCheckingInspection
ContainerUtil.addIfNotNull(list, item.getAttributeValue("itemvalue"));
}
}
}
return list;
}
@Override
public boolean isBoundTo(Object node) {
if (node instanceof Element) {
Element element = (Element)node;
String elementName = element.getName();
if (isNameEqual(elementName)) {
return true;
}
else if (elementName.equals(Constants.OPTION)) {
// JDOMExternalizableStringList format
return isNameEqual(element.getAttributeValue(Constants.NAME));
}
}
return false;
}
private boolean isNameEqual(@Nullable String value) {
if (value == null) {
return false;
}
else if (value.equals(name)) {
return true;
}
else if (value.length() == (name.length() + 2) && value.startsWith("my")) {
return Character.isUpperCase(value.charAt(2)) && value.regionMatches(true, 2, name, 0, name.length());
}
else {
return false;
}
}
@Override
public Class getBoundNodeType() {
return Element.class;
}
}
@@ -1,69 +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 com.intellij.util.xmlb;
import com.intellij.openapi.util.JDOMExternalizableStringList;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@SuppressWarnings("deprecation")
class JDOMExternalizableStringListBinding extends Binding {
private final String myName;
protected JDOMExternalizableStringListBinding(@NotNull Accessor accessor) {
super(accessor);
myName = myAccessor.getName();
}
@Nullable
@Override
public Object serialize(Object o, @Nullable Object context, SerializationFilter filter) {
Element result = new Element(myName);
JDOMExternalizableStringList list = (JDOMExternalizableStringList)o;
if (list == null || list.isEmpty()) {
return result;
}
for (String item : list) {
result.addContent(new Element("item").setAttribute("value", item));
}
return result;
}
@Nullable
@Override
public Object deserialize(Object context, @NotNull Object node) {
JDOMExternalizableStringList list = (JDOMExternalizableStringList)context;
list.clear();
for (Element item : ((Element)node).getChildren("item")) {
ContainerUtil.addIfNotNull(list, item.getAttributeValue("value"));
}
return list;
}
@Override
public boolean isBoundTo(Object node) {
return node instanceof Element && ((Element)node).getName().equals(myName);
}
@Override
public Class getBoundNodeType() {
return Element.class;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,12 +18,12 @@ package com.intellij.util.xmlb;
import com.intellij.openapi.util.JDOMExternalizableStringList;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.xmlb.annotations.CollectionBean;
import org.jdom.*;
import org.jdom.filter.Filter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.annotation.Annotation;
import java.lang.ref.SoftReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
@@ -119,7 +119,8 @@ class XmlSerializerImpl {
map.put(key, binding);
try {
binding.init();
} catch (XmlSerializationException e) {
}
catch (XmlSerializationException e) {
map.remove(key);
throw e;
}
@@ -156,6 +157,12 @@ class XmlSerializerImpl {
return new PrimitiveValueBinding(aClass, accessor);
}
if (Collection.class.isAssignableFrom(aClass) && originalType instanceof ParameterizedType) {
if (accessor != null) {
CollectionBean listBean = accessor.getAnnotation(CollectionBean.class);
if (listBean != null) {
return new CompactCollectionBinding(accessor);
}
}
return new CollectionBinding((ParameterizedType)originalType, accessor);
}
if (accessor != null) {
@@ -167,7 +174,7 @@ class XmlSerializerImpl {
}
//noinspection deprecation
if (JDOMExternalizableStringList.class == aClass) {
return new JDOMExternalizableStringListBinding(accessor);
return new CompactCollectionBinding(accessor);
}
}
if (Date.class.isAssignableFrom(aClass)) {
@@ -179,21 +186,6 @@ class XmlSerializerImpl {
return new BeanBinding(aClass, accessor);
}
@Nullable
@Deprecated
@SuppressWarnings({"unchecked", "unused"})
/**
* @deprecated to remove in IDEA 15
*/
static <T> T findAnnotation(Annotation[] annotations, Class<T> aClass) {
if (annotations == null) return null;
for (Annotation annotation : annotations) {
if (aClass.isAssignableFrom(annotation.getClass())) return (T)annotation;
}
return null;
}
@Nullable
@SuppressWarnings({"unchecked"})
static <T> T convert(Object value, Class<T> type) {

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