diff options
Diffstat (limited to 'java')
103 files changed, 1509 insertions, 1863 deletions
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java index b644c8a4c86d..6655fe863fad 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -913,7 +913,7 @@ public class CompileDriver { lfs.refreshIoFiles(outputs, _status == ExitStatus.CANCELLED, false, null); indicator.setText(""); } - if (compileContext.isAnnotationProcessorsEnabled()) { + if (compileContext.isAnnotationProcessorsEnabled() && !myProject.isDisposed()) { final Set<File> genSourceRoots = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY); final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); for (Module module : affectedModules) { diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileWorker.java b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileWorker.java index 242899017cd9..8f815f35c40c 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileWorker.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileWorker.java @@ -87,6 +87,7 @@ public class PackageFileWorker { for (final VirtualFile file : files) { indicator.checkCanceled(); new ReadAction() { + @Override protected void run(final Result result) { try { packageFile(file, project, artifacts, packIntoArchives); diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/AutoRendererAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/AutoRendererAction.java index 1891a7749a23..1d1537f93c9e 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/AutoRendererAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/AutoRendererAction.java @@ -15,6 +15,7 @@ */ package com.intellij.debugger.actions; +import com.intellij.debugger.engine.DebugProcessImpl; import com.intellij.debugger.engine.events.DebuggerContextCommandImpl; import com.intellij.debugger.impl.DebuggerContextImpl; import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl; @@ -26,21 +27,25 @@ import com.intellij.openapi.actionSystem.AnActionEvent; public class AutoRendererAction extends AnAction{ public void actionPerformed(AnActionEvent e) { final DebuggerContextImpl debuggerContext = DebuggerAction.getDebuggerContext(e.getDataContext()); - final DebuggerTreeNodeImpl[] selectedNodes = DebuggerAction.getSelectedNodes(e.getDataContext()); - if(debuggerContext != null && debuggerContext.getDebugProcess() != null) { - debuggerContext.getDebugProcess().getManagerThread().schedule(new DebuggerContextCommandImpl(debuggerContext) { - public void threadAction() { - for (int i = 0; i < selectedNodes.length; i++) { - DebuggerTreeNodeImpl selectedNode = selectedNodes[i]; - NodeDescriptorImpl descriptor = selectedNode.getDescriptor(); - if (descriptor instanceof ValueDescriptorImpl) { - ((ValueDescriptorImpl) descriptor).setRenderer(null); - selectedNode.calcRepresentation(); + if(debuggerContext != null) { + final DebugProcessImpl debugProcess = debuggerContext.getDebugProcess(); + if(debugProcess != null) { + final DebuggerTreeNodeImpl[] selectedNodes = DebuggerAction.getSelectedNodes(e.getDataContext()); + if (selectedNodes != null) { + debugProcess.getManagerThread().schedule(new DebuggerContextCommandImpl(debuggerContext) { + public void threadAction() { + for (DebuggerTreeNodeImpl selectedNode : selectedNodes) { + final NodeDescriptorImpl descriptor = selectedNode.getDescriptor(); + if (descriptor instanceof ValueDescriptorImpl) { + ((ValueDescriptorImpl)descriptor).setRenderer(null); + selectedNode.calcRepresentation(); + } + } } - } - } - }); + }); + } + } } } } diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java index ac513d7a40b9..a4fe426088f7 100644 --- a/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java +++ b/java/debugger/impl/src/com/intellij/debugger/actions/ThreadDumpAction.java @@ -33,7 +33,6 @@ import com.intellij.debugger.ui.DebuggerSessionTab; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; @@ -298,12 +297,30 @@ public class ThreadDumpAction extends AnAction implements AnAction.TransparentUp catch (Throwable e) { sourceName = "Unknown Source"; } - return DebuggerBundle.message( - "export.threads.stackframe.format", - location.declaringType().name() + "." + location.method().name(), - sourceName, - location.lineNumber() - ); + + final StringBuilder methodName = new StringBuilder(); + try { + methodName.append(location.declaringType().name()); + } + catch (Throwable e) { + methodName.append(e.getMessage()); + } + methodName.append("."); + try { + methodName.append(location.method().name()); + } + catch (Throwable e) { + methodName.append(e.getMessage()); + } + + int lineNumber; + try { + lineNumber = location.lineNumber(); + } + catch (Throwable e) { + lineNumber = -1; + } + return DebuggerBundle.message("export.threads.stackframe.format", methodName.toString(), sourceName, lineNumber); } private static String threadName(ThreadReference threadReference) { diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextImpl.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextImpl.java index d353368f9e69..e35ba834a9b5 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerContextImpl.java @@ -171,6 +171,7 @@ public final class DebuggerContextImpl implements DebuggerContext { } public boolean isEvaluationPossible() { - return getDebugProcess().getSuspendManager().getPausedContext() != null; + final DebugProcessImpl debugProcess = getDebugProcess(); + return debugProcess != null && debugProcess.getSuspendManager().getPausedContext() != null; } }
\ No newline at end of file diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java b/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java index 84ed7306912a..804799dd9301 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/InvokeThread.java @@ -34,6 +34,7 @@ public abstract class InvokeThread<E extends PrioritizedTask> { public static final class WorkerThreadRequest<E extends PrioritizedTask> implements Runnable { private final InvokeThread<E> myOwner; private volatile Future<?> myRequestFuture; + private volatile boolean myStopRequested = false; WorkerThreadRequest(InvokeThread<E> owner) { myOwner = owner; @@ -60,13 +61,16 @@ public abstract class InvokeThread<E extends PrioritizedTask> { } public void interrupt() { - assert myRequestFuture != null; - myRequestFuture.cancel( true ); + final Future<?> future = myRequestFuture; + assert future != null; + myStopRequested = true; + future.cancel(true); } public boolean isInterrupted() { - assert myRequestFuture != null; - return myRequestFuture.isCancelled() || myRequestFuture.isDone(); + final Future<?> future = myRequestFuture; + assert future != null; + return myStopRequested || future.isCancelled() || future.isDone(); } public void join() throws InterruptedException, ExecutionException { @@ -189,15 +193,15 @@ public abstract class InvokeThread<E extends PrioritizedTask> { return myEvents.pushBack(r, r.getPriority().ordinal()); } - protected void switchToRequest(WorkerThreadRequest newWorkerThread) { - final WorkerThreadRequest request = getCurrentThreadRequest(); - LOG.assertTrue(request != null); - myCurrentRequest = newWorkerThread; + protected void switchToRequest(WorkerThreadRequest newRequest) { + final WorkerThreadRequest currentThreadRequest = getCurrentThreadRequest(); + LOG.assertTrue(currentThreadRequest != null); + myCurrentRequest = newRequest; if (LOG.isDebugEnabled()) { - LOG.debug("Closing " + request + " new request = " + newWorkerThread); + LOG.debug("Closing " + currentThreadRequest + " new request = " + newRequest); } - request.interrupt(); + currentThreadRequest.interrupt(); } public WorkerThreadRequest getCurrentRequest() { diff --git a/java/debugger/impl/src/com/intellij/debugger/jdi/ThreadReferenceProxyImpl.java b/java/debugger/impl/src/com/intellij/debugger/jdi/ThreadReferenceProxyImpl.java index 25d08bb63732..38140c698382 100644 --- a/java/debugger/impl/src/com/intellij/debugger/jdi/ThreadReferenceProxyImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/jdi/ThreadReferenceProxyImpl.java @@ -171,7 +171,15 @@ public final class ThreadReferenceProxyImpl extends ObjectReferenceProxyImpl imp myFrameCount = 0; } catch (IncompatibleThreadStateException e) { - if (!threadReference.isSuspended()) { + final boolean isSuspended; + try { + isSuspended = threadReference.isSuspended(); + } + catch (Throwable th) { + // unable to determine whether the thread is actually suspended, so propagating original exception + throw EvaluateExceptionUtil.createEvaluateException(e); + } + if (!isSuspended) { // give up because it seems to be really resumed throw EvaluateExceptionUtil.createEvaluateException(e); } diff --git a/java/debugger/impl/src/com/intellij/debugger/jdi/VirtualMachineProxyImpl.java b/java/debugger/impl/src/com/intellij/debugger/jdi/VirtualMachineProxyImpl.java index 109b51ec507e..345637ba9efd 100644 --- a/java/debugger/impl/src/com/intellij/debugger/jdi/VirtualMachineProxyImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/jdi/VirtualMachineProxyImpl.java @@ -68,7 +68,18 @@ public class VirtualMachineProxyImpl implements JdiTimer, VirtualMachineProxy { canWatchFieldModification(); canPopFrames(); - virtualMachine.allClasses(); // this will cache classes inside JDI and enable faster search of classes later + try { + // this will cache classes inside JDI and enable faster search of classes later + virtualMachine.allClasses(); + } + catch (Throwable e) { + // catch all exceptions in order not to break vm attach process + // Example: + // java.lang.IllegalArgumentException: Invalid JNI signature character ';' + // caused by some bytecode "optimizers" which break type signatures as a side effect. + // solution if you are using JAX-WS: add -Dcom.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize=true to JVM args + LOG.info(e); + } List<ThreadGroupReference> groups = virtualMachine.topLevelThreadGroups(); for (ThreadGroupReference threadGroupReference : groups) { diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/PositionHighlighter.java b/java/debugger/impl/src/com/intellij/debugger/ui/PositionHighlighter.java index 1339e9c9bc0d..fa91c9b60141 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/PositionHighlighter.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/PositionHighlighter.java @@ -15,7 +15,6 @@ */ package com.intellij.debugger.ui; -import com.intellij.codeInsight.daemon.impl.DaemonListeners; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.DebuggerInvocationUtil; import com.intellij.debugger.SourcePosition; @@ -131,9 +130,9 @@ public class PositionHighlighter { private static void adjustCounter(@NotNull Editor editor, int increment) { JComponent component = editor.getComponent(); - Object o = component.getClientProperty(DaemonListeners.IGNORE_MOUSE_TRACKING); + Object o = component.getClientProperty(Editor.IGNORE_MOUSE_TRACKING); Integer value = ((o instanceof Integer) ? (Integer)o : 0) + increment; - component.putClientProperty(DaemonListeners.IGNORE_MOUSE_TRACKING, value > 0 ? value : null); + component.putClientProperty(Editor.IGNORE_MOUSE_TRACKING, value > 0 ? value : null); } public void remove() { diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointNameCellRenderer.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointNameCellRenderer.java deleted file mode 100644 index eac638e656da..000000000000 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointNameCellRenderer.java +++ /dev/null @@ -1,60 +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.breakpoints; - -import com.intellij.util.ui.UIUtil; - -import javax.swing.*; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.*; - -/** - * @author Jeka - */ -public class BreakpointNameCellRenderer extends DefaultTableCellRenderer { - private final Color myAnyExceptionForeground = new Color(128, 0, 0); - - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - setBorder(null); - BreakpointTableModel tableModel = (BreakpointTableModel)table.getModel(); - Breakpoint breakpoint = tableModel.getBreakpoint(row); - if (breakpoint == null){ - return this; - }; - final Icon icon = (breakpoint instanceof BreakpointWithHighlighter)? - breakpoint.ENABLED? ((BreakpointWithHighlighter)breakpoint).getSetIcon(false) : ((BreakpointWithHighlighter)breakpoint).getDisabledIcon( - false) : breakpoint.getIcon(); - setIcon(icon); - setDisabledIcon(icon); - - if(isSelected){ - setForeground(UIUtil.getTableSelectionForeground()); - } - else{ - Color foreColor; - if(breakpoint instanceof AnyExceptionBreakpoint){ - foreColor = myAnyExceptionForeground; - } - else{ - foreColor = UIUtil.getTableForeground(); - } - setForeground(foreColor); - } - setEnabled(isSelected || breakpoint.ENABLED); - return this; - } -} diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTable.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTable.java deleted file mode 100644 index 7530fa524e52..000000000000 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTable.java +++ /dev/null @@ -1,123 +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.breakpoints; - -import com.intellij.openapi.project.Project; -import com.intellij.util.ui.Table; -import com.intellij.xdebugger.XDebuggerBundle; - -import javax.swing.*; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableCellRenderer; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; - -/** - * @author Eugene Zhuravlev - * Date: May 23, 2005 - */ -public class BreakpointTable extends Table { - public BreakpointTable(final Project project) { - super(new BreakpointTableModel(project)); - setColumnSelectionAllowed(false); - InputMap inputMap = getInputMap(); - ActionMap actionMap = getActionMap(); - Object o = inputMap.get(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0)); - if (o == null) { - //noinspection HardCodedStringLiteral - o = "enable_disable"; - inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), o); - } - actionMap.put(o, new AbstractAction() { - public void actionPerformed(ActionEvent e) { - if (isEditing()) { - return; - } - int[] indices = getSelectedRows(); - boolean currentlyMarked = true; - for (int i = 0; i < indices.length; i++) { - final Boolean isMarked = (Boolean)getValueAt(indices[i], BreakpointTableModel.ENABLED_STATE); - currentlyMarked = isMarked != null? isMarked.booleanValue() : false; - if (!currentlyMarked) { - break; - } - } - final Boolean valueToSet = currentlyMarked ? Boolean.FALSE : Boolean.TRUE; - for (int i = 0; i < indices.length; i++) { - setValueAt(valueToSet, indices[i], BreakpointTableModel.ENABLED_STATE); - } - } - }); - - setShowGrid(false); - setIntercellSpacing(new Dimension(0, 0)); - setTableHeader(null); - setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); - setColumnSelectionAllowed(false); - - int width = new JCheckBox().getPreferredSize().width; - TableColumnModel columnModel = getColumnModel(); - - TableColumn enabledStateColumn = columnModel.getColumn(BreakpointTableModel.ENABLED_STATE); - enabledStateColumn.setPreferredWidth(width); - enabledStateColumn.setMaxWidth(width); - final Class enabledStateColumnClass = getModel().getColumnClass(BreakpointTableModel.ENABLED_STATE); - final TableCellRenderer delegateRenderer = getDefaultRenderer(enabledStateColumnClass); - setDefaultRenderer(enabledStateColumnClass, new DefaultTableCellRenderer() { - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - final Component component = delegateRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - if (component instanceof JComponent) { - ((JComponent)component).setBorder(null); - } - return component; - } - }); - columnModel.getColumn(BreakpointTableModel.NAME).setCellRenderer(new BreakpointNameCellRenderer()); - - getEmptyText().setText(XDebuggerBundle.message("debugger.no.breakpoints")); - } - - public BreakpointTableModel getModel() { - return (BreakpointTableModel)super.getModel(); - } - - public void setBreakpoints(Breakpoint[] breakpoints) { - getModel().setBreakpoints(breakpoints); - } - - public final java.util.List<Breakpoint> getBreakpoints() { - return getModel().getBreakpoints(); - } - - public Breakpoint[] getSelectedBreakpoints() { - if (getRowCount() == 0) { - return Breakpoint.EMPTY_ARRAY; - } - - int[] rows = getSelectedRows(); - if (rows.length == 0) { - return Breakpoint.EMPTY_ARRAY; - } - Breakpoint[] rv = new Breakpoint[rows.length]; - for (int idx = 0; idx < rows.length; idx++) { - rv[idx] = getModel().getBreakpoint(rows[idx]); - } - return rv; - } -} diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTableModel.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTableModel.java deleted file mode 100644 index 6999260ec9df..000000000000 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTableModel.java +++ /dev/null @@ -1,161 +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 BreakpointTableModel - * @author Jeka - */ -package com.intellij.debugger.ui.breakpoints; - -import com.intellij.debugger.DebuggerBundle; -import com.intellij.debugger.DebuggerManagerEx; -import com.intellij.openapi.project.Project; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.ui.ItemRemovable; - -import javax.swing.table.AbstractTableModel; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class BreakpointTableModel extends AbstractTableModel implements ItemRemovable { - public static final int ENABLED_STATE = 0; - public static final int NAME = 1; - - private java.util.List<Breakpoint> myBreakpoints = null; - private final BreakpointManager myBreakpointManager; - - public BreakpointTableModel(final Project project) { - myBreakpoints = new ArrayList<Breakpoint>(); - myBreakpointManager = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager(); - } - - public final void setBreakpoints(Breakpoint[] breakpoints) { - myBreakpoints.clear(); - if (breakpoints != null) { - ContainerUtil.addAll(myBreakpoints, breakpoints); - } - fireTableDataChanged(); - } - - public List<Breakpoint> getBreakpoints() { - return Collections.unmodifiableList(myBreakpoints); - } - - public void removeBreakpoints(Breakpoint[] breakpoints) { - myBreakpoints.removeAll(Arrays.asList(breakpoints)); - fireTableDataChanged(); - } - - public Breakpoint getBreakpoint(int index) { - if (index < 0 || index >= myBreakpoints.size()) return null; - return myBreakpoints.get(index); - } - - public boolean isBreakpointEnabled(int index) { - return ((Boolean)getValueAt(index, ENABLED_STATE)).booleanValue(); - } - - public int getBreakpointIndex(Breakpoint breakpoint) { - return myBreakpoints.indexOf(breakpoint); - } - - public void insertBreakpointAt(Breakpoint breakpoint, int index) { - myBreakpoints.add(index, breakpoint); - fireTableRowsInserted(index, index); - } - - public void addBreakpoint(Breakpoint breakpoint) { - myBreakpoints.add(breakpoint); - int row = myBreakpoints.size() - 1; - fireTableRowsInserted(row, row); - } - - public void removeRow(int idx) { - if (idx >= 0 && idx < myBreakpoints.size()) { - myBreakpoints.remove(idx); - fireTableRowsDeleted(idx, idx); - } - } - - public int getRowCount() { - return myBreakpoints.size(); - } - - public int getColumnCount() { - return 2; - } - - public String getColumnName(int column) { - switch (column) { - case ENABLED_STATE: - return DebuggerBundle.message("breakpoint.table.header.column.enabled"); - case NAME: - return DebuggerBundle.message("breakpoint.table.header.column.name"); - default : - return ""; - } - } - - public Object getValueAt(int rowIndex, int columnIndex) { - Breakpoint breakpoint = myBreakpoints.get(rowIndex); - if (columnIndex == NAME) { - return breakpoint.getDisplayName(); - } - if (columnIndex == ENABLED_STATE) { - return breakpoint.ENABLED? Boolean.TRUE : Boolean.FALSE; - } - return null; - } - - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - if (rowIndex < 0 || rowIndex >= myBreakpoints.size()) { - return; - } - Breakpoint breakpoint = myBreakpoints.get(rowIndex); -/* - if (columnIndex == NAME) { - breakpoint.setDisplayName((aValue != null)? aValue.toString() : ""); - } - else -*/ - if (columnIndex == ENABLED_STATE) { - final boolean isEnabled = aValue == null || ((Boolean)aValue).booleanValue(); - final boolean valueChanged = isEnabled != breakpoint.ENABLED; - breakpoint.ENABLED = isEnabled; - if (valueChanged) { - breakpoint.updateUI(); - } - } - fireTableRowsUpdated(rowIndex, rowIndex); - } - - public Class getColumnClass(int columnIndex) { - if (columnIndex == ENABLED_STATE) { - return Boolean.class; - } - return super.getColumnClass(columnIndex); - } - - public boolean isCellEditable(int rowIndex, int columnIndex) { - if (columnIndex != ENABLED_STATE) { - return false; - } - final boolean isSlave = myBreakpointManager.findMasterBreakpoint(myBreakpoints.get(rowIndex)) != null; - return !isSlave; - } -} diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java deleted file mode 100644 index 695fea471402..000000000000 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/BreakpointTree.java +++ /dev/null @@ -1,824 +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.breakpoints; -import com.intellij.debugger.DebuggerBundle; -import com.intellij.debugger.DebuggerManagerEx; -import com.intellij.openapi.project.Project; -import com.intellij.ui.*; -import com.intellij.util.ArrayUtil; -import com.intellij.util.PlatformIcons; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.Convertor; -import com.intellij.util.ui.tree.TreeUtil; -import com.intellij.xdebugger.XDebuggerBundle; -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import java.util.*; - -/** - * @author Eugene Zhuravlev - * Date: May 20, 2005 - */ -public class BreakpointTree extends CheckboxTree { - private static final String DEFAULT_PACKAGE_NAME = DebuggerBundle.message("default.package.name"); - private final CheckedTreeNode myRootNode; - private final List<Breakpoint> myBreakpoints = new ArrayList<Breakpoint>(); - private final Map<TreeDescriptor, CheckedTreeNode> myDescriptorToNodeMap = new HashMap<TreeDescriptor, CheckedTreeNode>(); - - private boolean myGroupByMethods = false; - private boolean myGroupByClasses = true; - private boolean myFlattenPackages = true; - - private final NodeAppender[] myAppenders = { - new BreakpointToMethodAppender(), - new BreakpointToClassAppender(), - new BreakpointToPackageAppender(), - new MethodToClassAppender(), - new MethodToPackageAppender(), - new ClassToPackageAppender(), - new PackageToPackageAppender(), - }; - - private final Comparator<CheckedTreeNode> myNodeComparator = new Comparator<CheckedTreeNode>() { - public int compare(CheckedTreeNode o1, CheckedTreeNode o2) { - final int w1 = getWeight(o1); - final int w2 = getWeight(o2); - if (w1 != w2) { - return w1 - w2; - } - final TreeDescriptor d1 = (TreeDescriptor)o1.getUserObject(); - final TreeDescriptor d2 = (TreeDescriptor)o2.getUserObject(); - if (d1 instanceof BreakpointDescriptor && d2 instanceof BreakpointDescriptor) { - return 0; - } - return d1.getDisplayString().compareTo(d2.getDisplayString()); - } - - private int getWeight(CheckedTreeNode node) { - if (node.getUserObject() instanceof BreakpointDescriptor) { - return 100; - } - if (node.getUserObject() instanceof MethodDescriptor) { - return 90; - } - if (node.getUserObject() instanceof PackageDescriptor) { - return 80; - } - if (node.getUserObject() instanceof ClassDescriptor) { - return 70; - } - return 50; - } - }; - private final BreakpointManager myBreakpointManager; - private final BreakpointManagerListener myNodeUpdateListener; - - protected void installSpeedSearch() { - new TreeSpeedSearch(this, new Convertor<TreePath, String>() { - public String convert(TreePath path) { - final CheckedTreeNode node = (CheckedTreeNode)path.getLastPathComponent(); - return ((TreeDescriptor)node.getUserObject()).getDisplayString(); - } - }); - } - - public boolean getExpandsSelectedPaths() { - return true; - } - - public Breakpoint[] getSelectedBreakpoints() { - final TreePath[] selectionPaths = getSelectionPaths(); - if (selectionPaths == null || selectionPaths.length == 0) { - return Breakpoint.EMPTY_ARRAY; - } - final List<Breakpoint> breakpoints = new ArrayList<Breakpoint>(selectionPaths.length); - for (TreePath path : selectionPaths) { - final CheckedTreeNode node = (CheckedTreeNode)path.getLastPathComponent(); - TreeUtil.traverseDepth(node, new TreeUtil.Traverse() { - public boolean accept(Object _node) { - final CheckedTreeNode node = (CheckedTreeNode)_node; - final TreeDescriptor descriptor = (TreeDescriptor)node.getUserObject(); - if (descriptor instanceof BreakpointDescriptor) { - breakpoints.add(((BreakpointDescriptor)descriptor).getBreakpoint()); - } - return true; - } - }); - } - return breakpoints.toArray(new Breakpoint[breakpoints.size()]); - } - - public void selectBreakpoint(Breakpoint breakpoint) { - final CheckedTreeNode node = myDescriptorToNodeMap.get(new BreakpointDescriptor(breakpoint)); - if (node == null) { - return; - } - TreeUtil.selectNode(this, node); - } - - public void selectBreakpoints(Breakpoint[] breakpoints) { - final List<CheckedTreeNode> nodes = new ArrayList<CheckedTreeNode>(breakpoints.length); - for (Breakpoint breakpoint : breakpoints) { - final CheckedTreeNode node = myDescriptorToNodeMap.get(new BreakpointDescriptor(breakpoint)); - if (node != null) { - nodes.add(node); - } - } - clearSelection(); - for (CheckedTreeNode node : nodes) { - addSelectionPath(new TreePath(node.getPath())); - } - } - - public void selectFirstBreakpoint() { - TreeUtil.traverseDepth(myRootNode, new TreeUtil.Traverse() { - public boolean accept(Object node) { - final CheckedTreeNode treeNode = (CheckedTreeNode)node; - final TreeDescriptor descriptor = (TreeDescriptor)treeNode.getUserObject(); - if (descriptor instanceof BreakpointDescriptor) { - TreeUtil.selectNode(BreakpointTree.this, treeNode); - return false; - } - return true; - } - }); - } - - public List<Breakpoint> getBreakpoints() { - return Collections.unmodifiableList(myBreakpoints); - } - - public void dispose() { - final KeyStroke[] treeStrokes = getRegisteredKeyStrokes(); - for (KeyStroke stroke : treeStrokes) { - unregisterKeyboardAction(stroke); - } - myBreakpointManager.removeBreakpointManagerListener(myNodeUpdateListener); - } - - private abstract static class TreeDescriptor { - protected void customizeCellRenderer(final ColoredTreeCellRenderer targetRenderer, CheckedTreeNode node, boolean selected, final boolean checked, boolean expanded, boolean leaf, boolean hasFocus) { - targetRenderer.setIcon(getDisplayIcon()); - targetRenderer.append(getDisplayString(), checked? SimpleTextAttributes.SIMPLE_CELL_ATTRIBUTES : SimpleTextAttributes.GRAYED_ATTRIBUTES); - } - - protected abstract String getDisplayString(); - - protected abstract Icon getDisplayIcon(); - - } - - private final class BreakpointDescriptor extends TreeDescriptor { - private final Breakpoint myBreakpoint; - public BreakpointDescriptor(Breakpoint breakpoint) { - myBreakpoint = breakpoint; - } - @NotNull - public Breakpoint getBreakpoint() { - return myBreakpoint; - } - - protected Icon getDisplayIcon() { - return myBreakpoint instanceof BreakpointWithHighlighter ? - myBreakpoint.ENABLED? ((BreakpointWithHighlighter)myBreakpoint).getSetIcon(false) : ((BreakpointWithHighlighter)myBreakpoint).getDisabledIcon(false) : myBreakpoint.getIcon(); - } - - public String getDisplayString() { - return myBreakpoint.getDisplayName(); - } - - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final BreakpointDescriptor breakpointDescriptor = (BreakpointDescriptor)o; - return myBreakpoint.equals(breakpointDescriptor.myBreakpoint); - } - - public int hashCode() { - return myBreakpoint.hashCode(); - } - - public boolean isSlave() { - final Breakpoint breakpoint = getBreakpoint(); - return myBreakpointManager.findMasterBreakpoint(breakpoint) != null; - } - } - - private static final class MethodDescriptor extends TreeDescriptor { - @NotNull - private final String myClassName; - @NotNull - private final String myMethodName; - @NotNull - private final String myPackageName; - - public MethodDescriptor(@NotNull String methodName, @NotNull String className, @NotNull String packageName) { - myClassName = className; - myMethodName = methodName.endsWith("()")? methodName : methodName + "()"; - myPackageName = packageName; - } - - @NotNull - public String getPackageName() { - return myPackageName; - } - - public String getClassName() { - return myClassName; - } - - public String getMethodName() { - return myMethodName; - } - - protected String getDisplayString() { - return myMethodName; - } - - protected Icon getDisplayIcon() { - return PlatformIcons.METHOD_ICON; - } - - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final MethodDescriptor methodDescriptor = (MethodDescriptor)o; - if (!myClassName.equals(methodDescriptor.myClassName)) { - return false; - } - return myMethodName.equals(methodDescriptor.myMethodName); - } - - public int hashCode() { - int result = myClassName.hashCode(); - result = 29 * result + myMethodName.hashCode(); - return result; - } - } - - private static final class ClassDescriptor extends TreeDescriptor { - @NotNull private final String myClassName; - @NotNull private final String myPackageName; - - public ClassDescriptor(@NotNull String className, @NotNull String packageName) { - myClassName = className; - myPackageName = packageName.length() == 0? DEFAULT_PACKAGE_NAME : packageName; - } - - @NotNull - public String getPackageName() { - return myPackageName; - } - - @NotNull - public String getClassName() { - return myClassName; - } - - protected String getDisplayString() { - return getClassName(); - } - - protected Icon getDisplayIcon() { - return PlatformIcons.CLASS_ICON; - } - - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - final ClassDescriptor classDescriptor = (ClassDescriptor)o; - - return myClassName.equals(classDescriptor.myClassName); - - } - - public int hashCode() { - return myClassName.hashCode(); - } - } - - private static final class PackageDescriptor extends TreeDescriptor { - private final String myPackageName; - - public PackageDescriptor(String packageName) { - myPackageName = "".equals(packageName)? DEFAULT_PACKAGE_NAME : packageName; - } - - public String getPackageName() { - return myPackageName; - } - - public String getParentPackageName() { - final int dotIndex = myPackageName.lastIndexOf('.'); - return dotIndex >= 0 ? myPackageName.substring(0, dotIndex) : null; - } - - public void customizeCellRenderer(final ColoredTreeCellRenderer targetRenderer, CheckedTreeNode node, boolean selected, - final boolean checked, boolean expanded, boolean leaf, boolean hasFocus) { - targetRenderer.setIcon(PlatformIcons.PACKAGE_ICON); - final String displayName; - final CheckedTreeNode parent = (CheckedTreeNode)node.getParent(); - if (parent != null && parent.getUserObject() instanceof PackageDescriptor) { - final String parentPackageInTree = ((PackageDescriptor)parent.getUserObject()).getPackageName() + "."; - displayName = myPackageName.startsWith(parentPackageInTree)? myPackageName.substring(parentPackageInTree.length()) : myPackageName; - } - else { - displayName = myPackageName; - } - targetRenderer.append(displayName, checked? SimpleTextAttributes.SIMPLE_CELL_ATTRIBUTES : SimpleTextAttributes.GRAYED_ATTRIBUTES); - } - - protected String getDisplayString() { - return myPackageName; - } - - protected Icon getDisplayIcon() { - return PlatformIcons.PACKAGE_ICON; - } - - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - final PackageDescriptor packageDescriptor = (PackageDescriptor)o; - - return myPackageName.equals(packageDescriptor.myPackageName); - - } - - public int hashCode() { - return myPackageName.hashCode(); - } - } - - public BreakpointTree(final Project project) { - super(new BreakpointTreeCellRenderer(), new CheckedTreeNode(new RootDescriptor())); - myRootNode = (CheckedTreeNode)getModel().getRoot(); - myDescriptorToNodeMap.put((TreeDescriptor)myRootNode.getUserObject(), myRootNode); - myBreakpointManager = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager(); - myNodeUpdateListener = new BreakpointManagerListener() { - public void breakpointsChanged() { - repaint(); - } - }; - myBreakpointManager.addBreakpointManagerListener(myNodeUpdateListener); - getEmptyText().setText(XDebuggerBundle.message("debugger.no.breakpoints")); - } - - public boolean isGroupByMethods() { - return myGroupByMethods; - } - - public void setGroupByMethods(boolean groupByMethods) { - if (myGroupByMethods != groupByMethods) { - myGroupByMethods = groupByMethods; - rebuildTree(); - } - } - - public boolean isGroupByClasses() { - return myGroupByClasses; - } - - public void setGroupByClasses(boolean groupByClasses) { - if (myGroupByClasses != groupByClasses) { - myGroupByClasses = groupByClasses; - rebuildTree(); - } - } - - public boolean isFlattenPackages() { - return myFlattenPackages; - } - - public void setFlattenPackages(boolean flattenPackages) { - if (myFlattenPackages != flattenPackages) { - myFlattenPackages = flattenPackages; - rebuildTree(); - } - } - - @Override - protected void onNodeStateChanged(final CheckedTreeNode node) { - final Object descriptor = node.getUserObject(); - final Breakpoint breakpoint; - if (descriptor instanceof BreakpointDescriptor) { - breakpoint = ((BreakpointDescriptor)descriptor).getBreakpoint(); - if (myBreakpointManager.findMasterBreakpoint(breakpoint) != null) { - return; - } - } - else { - breakpoint = null; - } - - if (breakpoint != null) { - myBreakpointManager.setBreakpointEnabled(breakpoint, node.isChecked()); - } - - } - - public void addBreakpoint(final Breakpoint breakpoint) { - myBreakpoints.add(breakpoint); - breakpoint.updateUI(new Runnable() { - public void run() { - rebuildTree(); - } - }); - rebuildTree(); - selectBreakpoint(breakpoint); - } - - public void removeBreakpoint(Breakpoint breakpoint) { - myBreakpoints.remove(breakpoint); - rebuildTree(); - } - - public void removeBreakpoints(Breakpoint[] breakpoints) { - myBreakpoints.removeAll(Arrays.asList(breakpoints)); - rebuildTree(); - } - - public void setBreakpoints(Breakpoint[] breakpoints) { - myBreakpoints.clear(); - ContainerUtil.addAll(myBreakpoints, breakpoints); - rebuildTree(); - } - - public Breakpoint getPreviousSibling(Breakpoint breakpoint) { - return getSibling(breakpoint, false); - } - - - public Breakpoint getNextSibling(Breakpoint breakpoint) { - return getSibling(breakpoint, true); - } - - private Breakpoint getSibling(Breakpoint breakpoint, boolean nextSibling) { - final CheckedTreeNode node = myDescriptorToNodeMap.get(new BreakpointDescriptor(breakpoint)); - if (node == null) { - return null; - } - final CheckedTreeNode sibling = (CheckedTreeNode) (nextSibling? node.getNextSibling() : node.getPreviousSibling()); - if (sibling == null) { - return null; - } - final TreeDescriptor descriptor = (TreeDescriptor)sibling.getUserObject(); - return descriptor instanceof BreakpointDescriptor ? ((BreakpointDescriptor)descriptor).getBreakpoint() : null; - } - - private void rebuildTree() { - final TreeStateSnapshot treeStateSnapshot = new TreeStateSnapshot(this); - myRootNode.removeAllChildren(); - myDescriptorToNodeMap.clear(); - myDescriptorToNodeMap.put((TreeDescriptor)myRootNode.getUserObject(), myRootNode); - // build tree - for (final Breakpoint breakpoint : myBreakpoints) { - CheckedTreeNode node = createNode(new BreakpointDescriptor(breakpoint)); - node.setChecked(breakpoint.ENABLED); - addNode(node); - } - // remove all package nodes with one child - final int count = myRootNode.getChildCount(); - final List<CheckedTreeNode> children = new ArrayList<CheckedTreeNode>(); - for (int idx = 0; idx < count; idx++) { - CheckedTreeNode child = (CheckedTreeNode)myRootNode.getChildAt(idx); - if (!(child.getUserObject() instanceof PackageDescriptor)) { - children.add(child); - continue; - } - while (child.getUserObject() instanceof PackageDescriptor && child.getChildCount() <= 1) { - child = (CheckedTreeNode)child.getChildAt(0); - } - if (!(child.getUserObject() instanceof PackageDescriptor)) { - child = (CheckedTreeNode)child.getParent(); - } - for (CheckedTreeNode childToRemove = (CheckedTreeNode)child.getParent(); !childToRemove.equals(myRootNode); childToRemove = (CheckedTreeNode)childToRemove.getParent()) { - myDescriptorToNodeMap.remove(childToRemove.getUserObject()); - } - children.add(child); - } - for (final CheckedTreeNode aChildren : children) { - aChildren.removeFromParent(); - } - myRootNode.removeAllChildren(); - for (final CheckedTreeNode child : children) { - myRootNode.add(child); - } - sortChildren(myRootNode); - ((DefaultTreeModel)getModel()).nodeStructureChanged(myRootNode); - treeStateSnapshot.restore(this); - expandPath(new TreePath(myRootNode)); - } - - private void sortChildren(CheckedTreeNode node) { - final int childCount = node.getChildCount(); - if (childCount == 0) { - return; - } - final List<CheckedTreeNode> children = new ArrayList<CheckedTreeNode>(childCount); - for (int idx = 0; idx < childCount; idx++) { - children.add((CheckedTreeNode)node.getChildAt(idx)); - } - for (CheckedTreeNode child : children) { - sortChildren(child); - child.removeFromParent(); - } - Collections.sort(children, myNodeComparator); - for (CheckedTreeNode child : children) { - node.add(child); - } - } - - @NotNull - private CheckedTreeNode createNode(final TreeDescriptor descriptor) { - final CheckedTreeNode node = new CheckedTreeNode(descriptor); - myDescriptorToNodeMap.put(descriptor, node); - return node; - } - - /** - * @param node - */ - private void addNode(CheckedTreeNode node) { - for (final NodeAppender appender : myAppenders) { - node = appender.append(node); - if (node == null) { - break; - } - } - if (node != null) { - attachNodeToParent(getDescriptor(myRootNode), node); - } - } - - private static TreeDescriptor getDescriptor(final CheckedTreeNode node) { - return (TreeDescriptor)node.getUserObject(); - } - - /** - * @param parentDescriptor a descriptor of the childNode (possibly not existing) to attach to - * @param childNode the childNode to be attached - * @return either parent node if it has just been created or null, if the node has been attached to already existing childNode - */ - private CheckedTreeNode attachNodeToParent(final TreeDescriptor parentDescriptor, final CheckedTreeNode childNode) { - CheckedTreeNode parentNode = myDescriptorToNodeMap.get(parentDescriptor); - try { - if (parentNode != null) { - parentNode.add(childNode); - return null; // added to already existing, so stop iteration over appenders - } - parentNode = createNode(parentDescriptor); - parentNode.add(childNode); - return parentNode; - } - finally { - if (parentNode != null && parentNode.getChildCount() == 1) { - expandPath(new TreePath(parentNode.getPath())); - } - } - } - - private static class BreakpointTreeCellRenderer extends CheckboxTreeCellRenderer { - public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { - if (value instanceof CheckedTreeNode) { - final CheckedTreeNode node = (CheckedTreeNode)value; - final TreeDescriptor descriptor = getDescriptor(node); - descriptor.customizeCellRenderer(getTextRenderer(), node, selected, node.isChecked(), expanded, leaf, hasFocus); - if (descriptor instanceof BreakpointDescriptor) { - myCheckbox.setEnabled(node.isEnabled() && !((BreakpointDescriptor)descriptor).isSlave()); - } - } - } - } - - private abstract static class NodeAppender { - public abstract CheckedTreeNode append(CheckedTreeNode node); - } - - private class BreakpointToMethodAppender extends NodeAppender { - public CheckedTreeNode append(CheckedTreeNode node) { - if (!myGroupByMethods) { - return node; - } - final TreeDescriptor descriptor = getDescriptor(node); - if (!(descriptor instanceof BreakpointDescriptor)) { - return node; - } - final Breakpoint breakpoint = ((BreakpointDescriptor)descriptor).getBreakpoint(); - if (!(breakpoint instanceof LineBreakpoint)) { - return node; - } - final LineBreakpoint lineBreakpoint = (LineBreakpoint)breakpoint; - final String methodName = lineBreakpoint.getMethodName(); - final String className = lineBreakpoint.getShortClassName(); - final String packageName = lineBreakpoint.getPackageName(); - if (methodName == null || className == null || packageName == null) { - return node; - } - return attachNodeToParent(new MethodDescriptor(methodName, className, packageName), node); - } - } - - private class BreakpointToClassAppender extends NodeAppender { - public CheckedTreeNode append(CheckedTreeNode node) { - if (!myGroupByClasses) { - return node; - } - final TreeDescriptor descriptor = getDescriptor(node); - if (!(descriptor instanceof BreakpointDescriptor)) { - return node; - } - - final Breakpoint breakpoint = ((BreakpointDescriptor)descriptor).getBreakpoint(); - final String className = breakpoint.getShortClassName(); - if (className == null) { - return node; - } - final String packageName = breakpoint.getPackageName(); - if (packageName == null) { - return node; - } - return attachNodeToParent(new ClassDescriptor(className, packageName), node); - } - } - - private class BreakpointToPackageAppender extends NodeAppender { - public CheckedTreeNode append(CheckedTreeNode node) { - final TreeDescriptor descriptor = getDescriptor(node); - if (!(descriptor instanceof BreakpointDescriptor)) { - return node; - } - - final Breakpoint breakpoint = ((BreakpointDescriptor)descriptor).getBreakpoint(); - final String packageName; - if (breakpoint instanceof ExceptionBreakpoint) { - packageName = breakpoint.getPackageName(); - } - else if (breakpoint instanceof BreakpointWithHighlighter) { - packageName = breakpoint.getPackageName(); - } - else { - packageName = null; - } - if (packageName == null) { - return node; - } - return attachNodeToParent(new PackageDescriptor(packageName), node); - } - } - - private class MethodToClassAppender extends NodeAppender { - public CheckedTreeNode append(CheckedTreeNode node) { - if (!myGroupByClasses) { - return node; - } - final TreeDescriptor descriptor = getDescriptor(node); - if (!(descriptor instanceof MethodDescriptor)) { - return node; - } - final MethodDescriptor methodDescriptor = (MethodDescriptor)descriptor; - final String className = methodDescriptor.getClassName(); - final String packageName = methodDescriptor.getPackageName(); - return attachNodeToParent(new ClassDescriptor(className, packageName), node); - } - } - - private class MethodToPackageAppender extends NodeAppender { - public CheckedTreeNode append(CheckedTreeNode node) { - final TreeDescriptor descriptor = getDescriptor(node); - if (!(descriptor instanceof MethodDescriptor)) { - return node; - } - final MethodDescriptor methodDescriptor = (MethodDescriptor)descriptor; - final String packageName = methodDescriptor.getPackageName(); - return attachNodeToParent(new PackageDescriptor(packageName), node); - } - } - - private class ClassToPackageAppender extends NodeAppender { - public CheckedTreeNode append(CheckedTreeNode node) { - final TreeDescriptor descriptor = getDescriptor(node); - if (!(descriptor instanceof ClassDescriptor)) { - return node; - } - - final String packageName = ((ClassDescriptor)descriptor).getPackageName(); - return attachNodeToParent(new PackageDescriptor(packageName), node); - } - } - - private class PackageToPackageAppender extends NodeAppender { - public CheckedTreeNode append(CheckedTreeNode node) { - if (myFlattenPackages) { - return node; - } - final TreeDescriptor descriptor = getDescriptor(node); - if (!(descriptor instanceof PackageDescriptor)) { - return node; - } - - final PackageDescriptor packageDescriptor = (PackageDescriptor)descriptor; - final String parentPackageName = packageDescriptor.getParentPackageName(); - if (parentPackageName == null) { - return node; - } - final CheckedTreeNode parentNode = attachNodeToParent(new PackageDescriptor(parentPackageName), node); - if (parentNode == null) { - return null; - } - return append(parentNode); - } - } - - private static class RootDescriptor extends TreeDescriptor { - - protected String getDisplayString() { - return ""; - } - - protected Icon getDisplayIcon() { - return PlatformIcons.PROJECT_ICON; - } - } - - private static class TreeStateSnapshot { - private final Object[] myExpandedUserObjects; - private final Object[] mySelectedUserObjects; - - public TreeStateSnapshot(BreakpointTree tree) { - final List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(tree); - myExpandedUserObjects = getUserObjects(expandedPaths.toArray(new TreePath[expandedPaths.size()])); - mySelectedUserObjects =getUserObjects(tree.getSelectionPaths()); - } - - private static Object[] getUserObjects(final TreePath[] treePaths) { - if (treePaths == null) { - return ArrayUtil.EMPTY_OBJECT_ARRAY; - } - Object[] userObjects = new Object[treePaths.length]; - int index = 0; - for (TreePath path : treePaths) { - userObjects[index++] = ((CheckedTreeNode)path.getLastPathComponent()).getUserObject(); - } - return userObjects; - } - - public void restore(BreakpointTree tree) { - final List<TreePath> pathsToExpand = getPaths(tree, myExpandedUserObjects); - if (!pathsToExpand.isEmpty()) { - TreeUtil.restoreExpandedPaths(tree, pathsToExpand); - } - - final List<TreePath> pathsToSelect = getPaths(tree, mySelectedUserObjects); - if (!pathsToSelect.isEmpty()) { - tree.getSelectionModel().clearSelection(); - tree.setSelectionPaths(pathsToSelect.toArray(new TreePath[pathsToSelect.size()])); - } - } - - private static List<TreePath> getPaths(BreakpointTree tree, final Object[] userObjects) { - final List<TreePath> paths = new ArrayList<TreePath>(userObjects.length); - for (Object descriptor : userObjects) { - final CheckedTreeNode node = tree.myDescriptorToNodeMap.get(descriptor); - if (node != null) { - paths.add(new TreePath(node.getPath())); - } - } - return paths; - } - } -} diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/DebuggerTreeRenderer.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/DebuggerTreeRenderer.java index 857443f456c9..fe6941850a15 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/DebuggerTreeRenderer.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/DebuggerTreeRenderer.java @@ -23,12 +23,14 @@ import com.intellij.debugger.ui.tree.ValueDescriptor; import com.intellij.icons.AllIcons; import com.intellij.ide.highlighter.JavaHighlightingColors; import com.intellij.openapi.editor.colors.EditorColorsManager; +import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.*; import com.intellij.util.PlatformIcons; import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants; import com.intellij.xdebugger.impl.ui.tree.ValueMarkup; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -112,15 +114,37 @@ public class DebuggerTreeRenderer extends ColoredTreeCellRenderer { return nodeIcon; } + @NotNull + public static EditorColorsScheme getColorScheme(@Nullable JComponent component) { + EditorColorsScheme globalScheme = EditorColorsManager.getInstance().getGlobalScheme(); + if (component != null && ColorUtil.isDark(component.getBackground()) != ColorUtil.isDark(globalScheme.getDefaultBackground())) { + EditorColorsScheme scheme = EditorColorsManager.getInstance().getScheme(EditorColorsScheme.DEFAULT_SCHEME_NAME); + if (scheme != null) { + return scheme; + } + } + return globalScheme; + } + + public static SimpleColoredText getDescriptorText(DebuggerContextImpl debuggerContext, + NodeDescriptorImpl descriptor, + EditorColorsScheme colorsScheme, + boolean multiline) { + return getDescriptorText(debuggerContext, descriptor, colorsScheme, multiline, true); + } + public static SimpleColoredText getDescriptorText(final DebuggerContextImpl debuggerContext, NodeDescriptorImpl descriptor, boolean multiline) { - return getDescriptorText(debuggerContext, descriptor, multiline, true); + return getDescriptorText(debuggerContext, descriptor, getColorScheme(null), multiline, true); } public static SimpleColoredText getDescriptorTitle(final DebuggerContextImpl debuggerContext, NodeDescriptorImpl descriptor) { - return getDescriptorText(debuggerContext, descriptor, false, false); + return getDescriptorText(debuggerContext, descriptor, getColorScheme(null), false, false); } - private static SimpleColoredText getDescriptorText(final DebuggerContextImpl debuggerContext, final NodeDescriptorImpl descriptor, boolean multiline, + private static SimpleColoredText getDescriptorText(DebuggerContextImpl debuggerContext, + NodeDescriptorImpl descriptor, + EditorColorsScheme colorScheme, + boolean multiline, boolean appendValue) { SimpleColoredText descriptorText = new SimpleColoredText(); @@ -195,10 +219,10 @@ public class DebuggerTreeRenderer extends ColoredTreeCellRenderer { else { TextAttributes attributes = null; if (valueDescriptor.isNull()){ - attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(JavaHighlightingColors.KEYWORD); + attributes = colorScheme.getAttributes(JavaHighlightingColors.KEYWORD); } else if (valueDescriptor.isString()) { - attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(JavaHighlightingColors.STRING); + attributes = colorScheme.getAttributes(JavaHighlightingColors.STRING); } valueLabelAttribs = attributes != null? SimpleTextAttributes.fromTextAttributes(attributes) : DEFAULT_ATTRIBUTES; } @@ -207,11 +231,11 @@ public class DebuggerTreeRenderer extends ColoredTreeCellRenderer { if(exception != null) { final String errorMessage = exception.getMessage(); if(valueLabel.endsWith(errorMessage)) { - appendValueTextWithEscapesRendering(descriptorText, valueLabel.substring(0, valueLabel.length() - errorMessage.length()), valueLabelAttribs); + appendValueTextWithEscapesRendering(descriptorText, valueLabel.substring(0, valueLabel.length() - errorMessage.length()), valueLabelAttribs, colorScheme); descriptorText.append(errorMessage, XDebuggerUIConstants.EXCEPTION_ATTRIBUTES); } else { - appendValueTextWithEscapesRendering(descriptorText, valueLabel, valueLabelAttribs); + appendValueTextWithEscapesRendering(descriptorText, valueLabel, valueLabelAttribs, colorScheme); descriptorText.append(errorMessage, XDebuggerUIConstants.EXCEPTION_ATTRIBUTES); } } @@ -220,7 +244,7 @@ public class DebuggerTreeRenderer extends ColoredTreeCellRenderer { descriptorText.append(XDebuggerUIConstants.COLLECTING_DATA_MESSAGE, XDebuggerUIConstants.COLLECTING_DATA_HIGHLIGHT_ATTRIBUTES); } else { - appendValueTextWithEscapesRendering(descriptorText, valueLabel, valueLabelAttribs); + appendValueTextWithEscapesRendering(descriptorText, valueLabel, valueLabelAttribs, colorScheme); } } } @@ -233,7 +257,10 @@ public class DebuggerTreeRenderer extends ColoredTreeCellRenderer { return descriptorText; } - private static void appendValueTextWithEscapesRendering(SimpleColoredText descriptorText, String valueText, final SimpleTextAttributes attribs) { + private static void appendValueTextWithEscapesRendering(SimpleColoredText descriptorText, + String valueText, + SimpleTextAttributes attribs, + EditorColorsScheme colorScheme) { SimpleTextAttributes escapeAttribs = null; final StringBuilder buf = new StringBuilder(); boolean slashFound = false; @@ -248,7 +275,7 @@ public class DebuggerTreeRenderer extends ColoredTreeCellRenderer { } if (escapeAttribs == null) { // lazy init - TextAttributes fromHighlighter = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(JavaHighlightingColors.VALID_STRING_ESCAPE); + TextAttributes fromHighlighter = colorScheme.getAttributes(JavaHighlightingColors.VALID_STRING_ESCAPE); if (fromHighlighter != null) { escapeAttribs = SimpleTextAttributes.fromTextAttributes(fromHighlighter); } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/ArgumentValueDescriptorImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/ArgumentValueDescriptorImpl.java index 3cb94d43e15c..7adee9d7c0eb 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/ArgumentValueDescriptorImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/ArgumentValueDescriptorImpl.java @@ -30,6 +30,8 @@ import com.intellij.util.IncorrectOperationException; import com.sun.jdi.PrimitiveValue; import com.sun.jdi.Value; +import java.util.HashSet; +import java.util.Set; import java.util.Stack; public class ArgumentValueDescriptorImpl extends ValueDescriptorImpl{ @@ -110,6 +112,7 @@ public class ArgumentValueDescriptorImpl extends ValueDescriptorImpl{ private class LocalVariableNameFinder extends JavaRecursiveElementVisitor { private final int myStartSlot; private final StringBuilder myNameBuilder; + private final Set<String> myVisitedNames = new HashSet<String>(); private int myCurrentSlotIndex; private final Stack<Integer> myIndexStack; @@ -122,14 +125,24 @@ public class ArgumentValueDescriptorImpl extends ValueDescriptorImpl{ @Override public void visitLocalVariable(PsiLocalVariable variable) { - if (myCurrentSlotIndex == myIndex) { + appendName(variable.getName()); + final PsiType varType = variable.getType(); + myCurrentSlotIndex += (varType == PsiType.DOUBLE || varType == PsiType.LONG)? 2 : 1; + } + + public void visitSynchronizedStatement(PsiSynchronizedStatement statement) { + appendName("<monitor>"); + myCurrentSlotIndex++; + super.visitSynchronizedStatement(statement); + } + + private void appendName(String varName) { + if (myCurrentSlotIndex == myIndex && myVisitedNames.add(varName)) { if (myNameBuilder.length() != 0) { myNameBuilder.append(" | "); } - myNameBuilder.append(variable.getName()); + myNameBuilder.append(varName); } - final PsiType varType = variable.getType(); - myCurrentSlotIndex += (varType == PsiType.DOUBLE || varType == PsiType.LONG)? 2 : 1; } @Override diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeImpl.java index 665a6a1ad25d..b6877dc6acc3 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTreeNodeImpl.java @@ -87,7 +87,7 @@ public class DebuggerTreeNodeImpl extends TreeBuilderNode implements DebuggerTre final NodeDescriptorImpl descriptor = getDescriptor(); myIcon = DebuggerTreeRenderer.getDescriptorIcon(descriptor); final DebuggerContextImpl context = getTree().getDebuggerContext(); - myText = DebuggerTreeRenderer.getDescriptorText(context, descriptor, false); + myText = DebuggerTreeRenderer.getDescriptorText(context, descriptor, DebuggerTreeRenderer.getColorScheme(myTree), false); if (descriptor instanceof ValueDescriptor) { final ValueMarkup markup = ((ValueDescriptor)descriptor).getMarkup(context.getDebugProcess()); myMarkupTooltipText = markup != null? markup.getToolTipText() : null; diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/FieldDescriptorImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/FieldDescriptorImpl.java index 521c2236639f..586dadfe5068 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/FieldDescriptorImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/FieldDescriptorImpl.java @@ -18,12 +18,14 @@ package com.intellij.debugger.ui.impl.watch; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.DebuggerContext; import com.intellij.debugger.SourcePosition; +import com.intellij.debugger.engine.DebugProcessImpl; import com.intellij.debugger.engine.DebuggerManagerThreadImpl; import com.intellij.debugger.engine.DebuggerUtils; import com.intellij.debugger.engine.JVMNameUtil; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil; import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; +import com.intellij.debugger.engine.events.DebuggerContextCommandImpl; import com.intellij.debugger.impl.DebuggerContextImpl; import com.intellij.debugger.impl.DebuggerSession; import com.intellij.debugger.impl.PositionUtil; @@ -32,6 +34,8 @@ import com.intellij.debugger.ui.tree.FieldDescriptor; import com.intellij.debugger.ui.tree.NodeDescriptor; import com.intellij.debugger.ui.tree.render.ClassRenderer; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Computable; +import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; @@ -98,20 +102,43 @@ public class FieldDescriptorImpl extends ValueDescriptorImpl implements FieldDes PsiClass aClass = facade.findClass(type.name().replace('$', '.'), scope); if (aClass == null) { // trying to search, assuming declaring class is an anonymous class - try { - final List<Location> locations = type.allLineLocations(); - if (!locations.isEmpty()) { - // important: use the last location to be sure the position will be within the anonymous class - final Location lastLocation = locations.get(locations.size() - 1); - final SourcePosition position = context.getDebugProcess().getPositionManager().getSourcePosition(lastLocation); - if (position != null) { - aClass = JVMNameUtil.getClassAt(position); + final DebugProcessImpl debugProcess = context.getDebugProcess(); + if (debugProcess != null) { + final Computable<PsiClass> classComputable = new Computable<PsiClass>() { + public PsiClass compute() { + try { + final List<Location> locations = type.allLineLocations(); + if (!locations.isEmpty()) { + // important: use the last location to be sure the position will be within the anonymous class + final Location lastLocation = locations.get(locations.size() - 1); + final SourcePosition position = debugProcess.getPositionManager().getSourcePosition(lastLocation); + if (position != null) { + return JVMNameUtil.getClassAt(position); + } + } + } + catch (AbsentInformationException ignored) { + } + catch (ClassNotPreparedException ignored) { + } + return null; } + }; + if (!DebuggerManagerThreadImpl.isManagerThread()) { + final Ref<PsiClass> classRef = new Ref<PsiClass>(null); + debugProcess.getManagerThread().invokeAndWait(new DebuggerContextCommandImpl(context) { + public Priority getPriority() { + return Priority.HIGH; + } + public void threadAction() { + classRef.set(classComputable.compute()); + } + }); + aClass = classRef.get(); + } + else { + aClass = classComputable.compute(); } - } - catch (AbsentInformationException ignored) { - } - catch (ClassNotPreparedException ignored) { } } diff --git a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryOptionsPanel.java b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryOptionsPanel.java index 3eb6b0ab6cb9..0d06c9fb1632 100644 --- a/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryOptionsPanel.java +++ b/java/idea-ui/src/com/intellij/facet/impl/ui/libraries/LibraryOptionsPanel.java @@ -125,10 +125,7 @@ public class LibraryOptionsPanel implements Disposable { public void run() { if (!myDisposed) { showSettingsPanel(libraryDescription, baseDirectoryPath, versionFilter, showDoNotCreateOption, versions); - LibraryDownloadSettings settings = mySettings.getDownloadSettings(); - if (settings != null) { - onVersionChanged(settings.getVersion()); - } + onVersionChanged(getPresentableVersion()); } } }); @@ -141,7 +138,28 @@ public class LibraryOptionsPanel implements Disposable { } } - protected void onVersionChanged(FrameworkLibraryVersion version) { + @Nullable + private String getPresentableVersion() { + switch (myButtonEnumModel.getSelected()) { + case DOWNLOAD: + LibraryDownloadSettings settings = mySettings.getDownloadSettings(); + if (settings != null) { + return settings.getVersion().getVersionNumber(); + } + break; + case USE_LIBRARY: + LibraryEditor item = myLibraryComboBoxModel.getSelectedItem(); + if (item instanceof ExistingLibraryEditor) { + return item.getName(); + } + break; + default: + return null; + } + return null; + } + + protected void onVersionChanged(@Nullable String version) { } public JPanel getSimplePanel() { @@ -176,6 +194,7 @@ public class LibraryOptionsPanel implements Disposable { @Override public void actionPerformed(ActionEvent e) { updateState(); + onVersionChanged(getPresentableVersion()); } }); @@ -208,6 +227,7 @@ public class LibraryOptionsPanel implements Disposable { myButtonEnumModel.setSelected(Choice.USE_LIBRARY); } updateState(); + onVersionChanged(getPresentableVersion()); } }); myExistingLibraryComboBox.setRenderer(new ColoredListCellRenderer() { @@ -346,7 +366,7 @@ public class LibraryOptionsPanel implements Disposable { } private void doCreate() { - final NewLibraryConfiguration libraryConfiguration = myLibraryDescription.createNewLibrary(myPanel, getBaseDirectory()); + final NewLibraryConfiguration libraryConfiguration = myLibraryDescription.createNewLibrary(myCreateButton, getBaseDirectory()); if (libraryConfiguration != null) { final NewLibraryEditor libraryEditor = new NewLibraryEditor(libraryConfiguration.getLibraryType(), libraryConfiguration.getProperties()); libraryEditor.setName(myLibrariesContainer.suggestUniqueLibraryName(libraryConfiguration.getDefaultLibraryName())); diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/NewProjectWizard.java b/java/idea-ui/src/com/intellij/ide/projectWizard/NewProjectWizard.java index 290d3cd65f8f..77d6d91b9f3b 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/NewProjectWizard.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/NewProjectWizard.java @@ -33,8 +33,6 @@ public class NewProjectWizard extends AbstractProjectWizard { public NewProjectWizard(@Nullable Project project, @NotNull ModulesProvider modulesProvider, @Nullable String defaultPath) { super("New Project", project, defaultPath); -// addStep(); -// addStep(new ProjectSummaryStep(myWizardContext)); myWizardContext.setNewWizard(true); mySequence = new StepSequence(); mySequence.addCommonStep(new ProjectTypeStep(myWizardContext, this, modulesProvider)); diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectCategory.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectCategory.java index 0862c7379724..7ef2e82feab3 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectCategory.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectCategory.java @@ -69,6 +69,10 @@ public abstract class ProjectCategory { return ArrayUtil.EMPTY_STRING_ARRAY; } + public String[] getPreselectedFrameworkIds() { + return ArrayUtil.EMPTY_STRING_ARRAY; + } + @Override public String toString() { return getDisplayName(); diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectSummaryStep.form b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectSummaryStep.form deleted file mode 100644 index a0f1f25df0ec..000000000000 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectSummaryStep.form +++ /dev/null @@ -1,26 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.ide.projectWizard.ProjectSummaryStep"> - <grid id="27dc6" binding="myRootPanel" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> - <margin top="0" left="0" bottom="0" right="0"/> - <constraints> - <xy x="20" y="20" width="500" height="400"/> - </constraints> - <properties/> - <border type="none"/> - <children> - <grid id="15993" binding="myNameAndLocationPanel" layout-manager="BorderLayout" hgap="0" vgap="0"> - <constraints> - <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/> - </constraints> - <properties/> - <border type="none"/> - <children/> - </grid> - <vspacer id="c6894"> - <constraints> - <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/> - </constraints> - </vspacer> - </children> - </grid> -</form> diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectSummaryStep.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectSummaryStep.java deleted file mode 100644 index 28e9cec7dee9..000000000000 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectSummaryStep.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2000-2013 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.projectWizard; - -import com.intellij.ide.util.projectWizard.NamePathComponent; -import com.intellij.ide.util.projectWizard.WizardContext; -import com.intellij.ide.wizard.CommitStepException; -import com.intellij.ide.wizard.StepAdapter; - -import javax.swing.*; -import java.awt.*; - -/** - * @author Dmitry Avdeev - * Date: 20.09.13 - */ -public class ProjectSummaryStep extends StepAdapter { - - private final WizardContext myWizardContext; - private JPanel myRootPanel; - private JPanel myNameAndLocationPanel; - private final NamePathComponent myNamePathComponent; - - public ProjectSummaryStep(WizardContext context) { - myWizardContext = context; - myNamePathComponent = NamePathComponent.initNamePathComponent(myWizardContext); - myNameAndLocationPanel.add(myNamePathComponent, BorderLayout.CENTER); - } - - @Override - public void _commit(boolean finishChosen) throws CommitStepException { - myWizardContext.setProjectName(myNamePathComponent.getNameValue()); - myWizardContext.setProjectFileDirectory(myNamePathComponent.getPath()); - } - - @Override - public JComponent getComponent() { - return myRootPanel; - } - - @Override - public JComponent getPreferredFocusedComponent() { - return myNamePathComponent.getNameComponent(); - } -} diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.form b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.form index 000469cc2a44..1eaf1286e09e 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.form +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.form @@ -45,29 +45,7 @@ <BorderFactoryClass class="java.lang.String" value="com.intellij.ui.IdeBorderFactory$PlainSmallWithoutIndent"/> </clientProperties> <border type="none"/> - <children> - <grid id="4ffce" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1"> - <margin top="0" left="0" bottom="0" right="0"/> - <constraints> - <card name="group description card"/> - </constraints> - <properties/> - <border type="none"/> - <children> - <component id="3c23c" class="com.intellij.ui.components.JBLabel" binding="myGroupDescriptionLabel"> - <constraints> - <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="2" hsize-policy="0" anchor="0" fill="1" indent="0" use-parent-layout="false"/> - </constraints> - <properties/> - </component> - <vspacer id="617a5"> - <constraints> - <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/> - </constraints> - </vspacer> - </children> - </grid> - </children> + <children/> </grid> </children> </grid> diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java index 3efa81829db1..4c66356d3034 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java @@ -15,6 +15,7 @@ */ package com.intellij.ide.projectWizard; +import com.intellij.CommonBundle; import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider; import com.intellij.ide.util.frameworkSupport.FrameworkRole; import com.intellij.ide.util.frameworkSupport.FrameworkSupportUtil; @@ -25,19 +26,35 @@ import com.intellij.ide.util.newProjectWizard.modes.CreateFromTemplateMode; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.ide.util.projectWizard.ModuleWizardStep; import com.intellij.ide.util.projectWizard.WizardContext; +import com.intellij.ide.wizard.CommitStepException; import com.intellij.openapi.Disposable; import com.intellij.openapi.module.Module; +import com.intellij.openapi.progress.ProgressIndicator; +import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; +import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer; import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainerFactory; +import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.platform.ProjectTemplate; -import com.intellij.ui.components.JBLabel; +import com.intellij.platform.ProjectTemplateEP; +import com.intellij.platform.templates.ArchivedProjectTemplate; +import com.intellij.platform.templates.LocalArchivedTemplate; +import com.intellij.platform.templates.RemoteTemplatesFactory; +import com.intellij.ui.*; import com.intellij.ui.components.JBList; +import com.intellij.ui.tabs.TabInfo; +import com.intellij.ui.tabs.TabsListener; +import com.intellij.ui.tabs.impl.JBTabsImpl; +import com.intellij.util.Function; +import com.intellij.util.containers.ConcurrentMultiMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FactoryMap; import com.intellij.util.containers.MultiMap; @@ -49,6 +66,7 @@ import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; +import java.net.URL; import java.util.*; import java.util.List; @@ -56,18 +74,21 @@ import java.util.List; * @author Dmitry Avdeev * Date: 04.09.13 */ -public class ProjectTypeStep extends ModuleWizardStep { +public class ProjectTypeStep extends ModuleWizardStep implements Disposable { private static final String FRAMEWORKS_CARD = "frameworks card"; - private static final String GROUP_CARD = "group description card"; private final WizardContext myContext; private final NewProjectWizard myWizard; private final ModulesProvider myModulesProvider; + private final JTextPane myTemplateDescription; private JPanel myPanel; private JPanel myOptionsPanel; - private JBLabel myGroupDescriptionLabel; private JBList myProjectTypeList; - private final ProjectTypesList myList; + + private final ProjectTypesList myProjectTypesList; + private final JBList myTemplatesList; + private final TabInfo myFrameworksTab; + private final TabInfo myTemplatesTab; @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private final FactoryMap<ProjectCategory, ModuleBuilder> myBuilders = new FactoryMap<ProjectCategory, ModuleBuilder>() { @@ -81,6 +102,9 @@ public class ProjectTypeStep extends ModuleWizardStep { private final AddSupportForFrameworksPanel myFrameworksPanel; private final ModuleBuilder.ModuleConfigurationUpdater myConfigurationUpdater; + private boolean myCommitted; + private final JBTabsImpl myTabs; + private final MultiMap<String, ProjectTemplate> myTemplates = loadLocalTemplates(); public ProjectTypeStep(WizardContext context, NewProjectWizard wizard, ModulesProvider modulesProvider) { myContext = context; @@ -124,80 +148,148 @@ public class ProjectTypeStep extends ModuleWizardStep { } } - myList = new ProjectTypesList(myProjectTypeList, map); + myProjectTypesList = new ProjectTypesList(myProjectTypeList, map); myProjectTypeList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { - @Override public void valueChanged(ListSelectionEvent e) { - ModuleBuilder builder = getSelectedBuilder(); - if (builder != null) { - myContext.setProjectBuilder(builder); - myWizard.getSequence().setType(builder.getBuilderId()); - builder.addModuleConfigurationUpdater(myConfigurationUpdater); - } - updateOptionsPanel(getSelectedObject()); + projectTypeChanged(true); } }); for (ProjectCategory category : map.values()) { myWizard.getSequence().addStepsForBuilder(myBuilders.get(category), context, modulesProvider); } - myFrameworksPanel = new AddSupportForFrameworksPanel(Collections.<FrameworkSupportInModuleProvider>emptyList(), model, true); Disposer.register(wizard.getDisposable(), myFrameworksPanel); - myOptionsPanel.add(myFrameworksPanel.getMainPanel(), FRAMEWORKS_CARD); + myTemplatesList = new JBList(); + myTemplatesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + myTemplatesList.setCellRenderer(new ColoredListCellRenderer<ProjectCategory>() { + @Override + protected void customizeCellRenderer(JList list, ProjectCategory value, int index, boolean selected, boolean hasFocus) { + append(value.getDisplayName()).setIcon(value.getIcon()); + } + }); + myTemplatesList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + projectTypeChanged(false); + ProjectCategory type = (ProjectCategory)myTemplatesList.getSelectedValue(); + myTemplateDescription.setText(type == null ? "" : type.getDescription()); + } + }); + + myTabs = new JBTabsImpl(null, IdeFocusManager.findInstance(), this); + myFrameworksTab = new TabInfo(myFrameworksPanel.getMainPanel()).setText(" Frameworks "); + myTabs.addTab(myFrameworksTab); + + JPanel templatesPanel = new JPanel(new BorderLayout()); + templatesPanel.add(ScrollPaneFactory.createScrollPane(myTemplatesList, SideBorder.BOTTOM)); + myTemplateDescription = new JTextPane(); + myTemplateDescription.setBorder(IdeBorderFactory.createEmptyBorder(5, 5, 5, 5)); + Messages.installHyperlinkSupport(myTemplateDescription); + templatesPanel.add(myTemplateDescription, BorderLayout.SOUTH); + + myTemplatesTab = new TabInfo(templatesPanel).setText(" Templates "); + myTabs.addTab(myTemplatesTab); + myOptionsPanel.add(myTabs.getComponent(), FRAMEWORKS_CARD); + + myTabs.addListener(new TabsListener.Adapter() { + @Override + public void selectionChanged(TabInfo oldSelection, TabInfo newSelection) { + projectTypeChanged(false); + } + }); + } + + // new category or template is selected + public void projectTypeChanged(boolean updatePanel) { + ModuleBuilder builder = getSelectedBuilder(); + if (builder != null) { + myContext.setProjectBuilder(builder); + myWizard.getSequence().setType(builder.getBuilderId()); + if (myFrameworksTab == myTabs.getSelectedInfo()) { + builder.addModuleConfigurationUpdater(myConfigurationUpdater); + } + } + if (updatePanel) { + ProjectCategory type = getSelectedProjectType(); + if (type != null) { + updateOptionsPanel(type); + } + } } @Nullable - public ProjectCategory getSelectedObject() { - return myList.getSelectedTemplate(); + public ProjectCategory getSelectedProjectType() { + if (myTabs.getSelectedInfo() == myFrameworksTab) { + return myProjectTypesList.getSelectedType(); + } + else { + return (ProjectCategory)myTemplatesList.getSelectedValue(); + } } @Nullable private ModuleBuilder getSelectedBuilder() { - ProjectCategory object = getSelectedObject(); + ProjectCategory object = getSelectedProjectType(); return object == null ? null : myBuilders.get(object); } - private void updateOptionsPanel(Object object) { - String card = GROUP_CARD; - if (object instanceof ProjectCategory) { - final ProjectCategory projectCategory = (ProjectCategory)object; - ModuleBuilder builder = myBuilders.get(projectCategory); - JComponent panel = builder.getCustomOptionsPanel(new Disposable() { - @Override - public void dispose() { - disposeUIResources(); - } - }); - if (panel != null) { - card = builder.getBuilderId(); - if (myCards.add(card)) { - myOptionsPanel.add(panel, card); - } + private void updateOptionsPanel(final @NotNull ProjectCategory projectCategory) { + ModuleBuilder builder = myBuilders.get(projectCategory); + JComponent panel = builder.getCustomOptionsPanel(new Disposable() { + @Override + public void dispose() { + disposeUIResources(); } - else { - card = FRAMEWORKS_CARD; - List<FrameworkSupportInModuleProvider> allProviders = FrameworkSupportUtil.getProviders(builder); - List<FrameworkSupportInModuleProvider> matched = - ContainerUtil.filter(allProviders, new Condition<FrameworkSupportInModuleProvider>() { - @Override - public boolean value(FrameworkSupportInModuleProvider provider) { - return matchFramework(projectCategory, provider); - } - }); - - myFrameworksPanel.setProviders(matched, new HashSet<String>(Arrays.asList(projectCategory.getAssociatedFrameworkIds()))); + }); + String card; + if (panel != null) { + card = builder.getBuilderId(); + if (myCards.add(card)) { + myOptionsPanel.add(panel, card); } } - else if (object instanceof TemplatesGroup) { - myGroupDescriptionLabel.setText(((TemplatesGroup)object).getDescription()); + else { + card = FRAMEWORKS_CARD; + List<FrameworkSupportInModuleProvider> allProviders = FrameworkSupportUtil.getProviders(builder); + List<FrameworkSupportInModuleProvider> matched = + ContainerUtil.filter(allProviders, new Condition<FrameworkSupportInModuleProvider>() { + @Override + public boolean value(FrameworkSupportInModuleProvider provider) { + return matchFramework(projectCategory, provider); + } + }); + + myFrameworksPanel.setProviders(matched, + new HashSet<String>(Arrays.asList(projectCategory.getAssociatedFrameworkIds())), + new HashSet<String>(Arrays.asList(projectCategory.getPreselectedFrameworkIds()))); + + boolean hasTemplates = updateTemplates(projectCategory, true); + myFrameworksTab.setEnabled(!matched.isEmpty() || !hasTemplates); } ((CardLayout)myOptionsPanel.getLayout()).show(myOptionsPanel, card); } + private boolean updateTemplates(ProjectCategory projectCategory, boolean initial) { + List<ProjectCategory> templates = ContainerUtil.map(myTemplates.get(projectCategory.getId()), new Function<ProjectTemplate, ProjectCategory>() { + @Override + public ProjectCategory fun(ProjectTemplate template) { + return new TemplateBasedProjectType(template); + } + }); + + //noinspection unchecked + myTemplatesList.setModel(new CollectionListModel<ProjectCategory>(templates)); + myTemplatesTab.setEnabled(!templates.isEmpty()); + if (initial && !templates.isEmpty()) { + myTemplatesList.setSelectedIndex(0); + } + return !templates.isEmpty(); + } + private boolean matchFramework(ProjectCategory projectCategory, FrameworkSupportInModuleProvider framework) { if (!framework.isEnabledForModuleBuilder(myBuilders.get(projectCategory))) return false; @@ -223,12 +315,29 @@ public class ProjectTypeStep extends ModuleWizardStep { @Override public void updateStep() { - myList.resetSelection(); + myProjectTypesList.resetSelection(); + loadRemoteTemplates(); } @Override public void onStepLeaving() { - myList.saveSelection(); + myProjectTypesList.saveSelection(); + } + + @Override + public void onWizardFinished() throws CommitStepException { + if (!myCommitted && myTabs.getSelectedInfo() == myFrameworksTab) { + boolean ok = myFrameworksPanel.downloadLibraries(); + if (!ok) { + int answer = Messages.showYesNoDialog(getComponent(), + ProjectBundle.message("warning.message.some.required.libraries.wasn.t.downloaded"), + CommonBundle.getWarningTitle(), Messages.getWarningIcon()); + if (answer != 0) { + throw new CommitStepException(null); + } + } + myCommitted = true; + } } @Override @@ -243,6 +352,63 @@ public class ProjectTypeStep extends ModuleWizardStep { @TestOnly public boolean setSelectedProjectType(String group, String name) { - return myList.setSelectedTemplate(group, name); + return myProjectTypesList.setSelectedType(group, name); + } + + @Override + public void dispose() { + } + + @Override + public void disposeUIResources() { + Disposer.dispose(this); + } + + private static MultiMap<String, ProjectTemplate> loadLocalTemplates() { + ConcurrentMultiMap<String, ProjectTemplate> map = new ConcurrentMultiMap<String, ProjectTemplate>(); + ProjectTemplateEP[] extensions = ProjectTemplateEP.EP_NAME.getExtensions(); + for (ProjectTemplateEP ep : extensions) { + ClassLoader classLoader = ep.getLoaderForClass(); + URL url = classLoader.getResource(ep.templatePath); + if (url != null) { + map.putValue(ep.projectType, new LocalArchivedTemplate(url, classLoader)); + } + } + return map; + } + + private void loadRemoteTemplates() { + ProgressManager.getInstance().run(new Task.Backgroundable(myContext.getProject(), "Loading Templates") { + @Override + public void run(@NotNull ProgressIndicator indicator) { + try { + myTemplatesList.setPaintBusy(true); + RemoteTemplatesFactory factory = new RemoteTemplatesFactory(); + String[] groups = factory.getGroups(); + for (String group : groups) { + ProjectTemplate[] templates = factory.createTemplates(group, myContext); + for (ProjectTemplate template : templates) { + String id = ((ArchivedProjectTemplate)template).getCategory(); + myTemplates.putValue(id == null ? group : id, template); + } + } + //noinspection SSBasedInspection + SwingUtilities.invokeLater(new Runnable() { + public void run() { + int index = myTemplatesList.getSelectedIndex(); + ProjectCategory type = myProjectTypesList.getSelectedType(); + if (type != null) { + updateTemplates(type, false); + } + myTemplatesList.setSelectedIndex(index); + } + }); + } + finally { + myTemplatesList.setPaintBusy(false); + } + } + }); + } } diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypesList.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypesList.java index ddac3b1c9927..b5d60bc7f024 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypesList.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypesList.java @@ -125,7 +125,7 @@ public class ProjectTypesList implements Disposable { void resetSelection() { if (myList.getSelectedIndex() != -1) return; SelectTemplateSettings settings = SelectTemplateSettings.getInstance(); - if (settings.getLastGroup() == null || !setSelectedTemplate(settings.getLastGroup(), settings.getLastTemplate())) { + if (settings.getLastGroup() == null || !setSelectedType(settings.getLastGroup(), settings.getLastTemplate())) { myList.setSelectedIndex(0); } } @@ -151,12 +151,12 @@ public class ProjectTypesList implements Disposable { } @Nullable - public ProjectCategory getSelectedTemplate() { + public ProjectCategory getSelectedType() { Object value = myList.getSelectedValue(); return value instanceof TemplateItem ? ((TemplateItem)value).myTemplate : null; } - public boolean setSelectedTemplate(@Nullable String group, @Nullable String name) { + public boolean setSelectedType(@Nullable String group, @Nullable String name) { for (int i = 0; i < myList.getModel().getSize(); i++) { Object o = myList.getModel().getElementAt(i); if (o instanceof TemplateItem && ((TemplateItem)o).myGroup.equals(group) && ((TemplateItem)o).getName().equals(name)) { @@ -173,7 +173,7 @@ public class ProjectTypesList implements Disposable { public void dispose() { } - class TemplateItem { + static class TemplateItem { private final ProjectCategory myTemplate; private final String myGroup; diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/TemplateBasedProjectType.java b/java/idea-ui/src/com/intellij/ide/projectWizard/TemplateBasedProjectType.java index 8f462aea22aa..e9eefe505881 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/TemplateBasedProjectType.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/TemplateBasedProjectType.java @@ -17,12 +17,10 @@ package com.intellij.ide.projectWizard; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.platform.ProjectTemplate; -import com.intellij.platform.templates.ArchivedTemplatesFactory; import com.intellij.platform.templates.LocalArchivedTemplate; import org.jetbrains.annotations.NotNull; import javax.swing.*; -import java.io.File; import java.net.URL; /** @@ -36,8 +34,7 @@ public class TemplateBasedProjectType extends ProjectCategory { public TemplateBasedProjectType(String templatePath) { URL resource = getClass().getResource(templatePath); assert resource != null : templatePath; - String name = ArchivedTemplatesFactory.getTemplateName(new File(templatePath).getName()); - myTemplate = new LocalArchivedTemplate(name, resource, getClass().getClassLoader()); + myTemplate = new LocalArchivedTemplate(resource, getClass().getClassLoader()); } public TemplateBasedProjectType(ProjectTemplate template) { diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java index 60f6f6981cc8..4de1dda33846 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java @@ -31,11 +31,13 @@ import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; +import com.intellij.ui.IdeBorderFactory; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; +import javax.swing.*; import java.awt.*; import java.io.File; @@ -56,6 +58,14 @@ public abstract class AbstractProjectWizard extends AbstractWizard<ModuleWizardS myWizardContext = initContext(project, null); } + @Override + protected String addStepComponent(Component component) { + if (component instanceof JComponent) { + ((JComponent)component).setBorder(IdeBorderFactory.createEmptyBorder(0, 0, 0, 0)); + } + return super.addStepComponent(component); + } + public abstract StepSequence getSequence(); private static WizardContext initContext(@Nullable Project project, @Nullable String defaultPath) { @@ -156,15 +166,21 @@ public abstract class AbstractProjectWizard extends AbstractWizard<ModuleWizardS step._commit(true); } catch (CommitStepException e) { - String message = e.getMessage(); - if (message != null) { - Messages.showErrorDialog(getCurrentStepComponent(), message); - } + handleCommitException(e); return; } if (!isLastStep(idx)) { idx = getNextStep(idx); } else { + for (ModuleWizardStep wizardStep : mySteps) { + try { + wizardStep.onWizardFinished(); + } + catch (CommitStepException e) { + handleCommitException(e); + return; + } + } break; } } while (true); @@ -176,6 +192,13 @@ public abstract class AbstractProjectWizard extends AbstractWizard<ModuleWizardS super.doOKAction(); } + private void handleCommitException(CommitStepException e) { + String message = e.getMessage(); + if (message != null) { + Messages.showErrorDialog(getCurrentStepComponent(), message); + } + } + protected boolean commitStepData(final ModuleWizardStep step) { try { if (!step.validate()) { diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddModuleWizard.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddModuleWizard.java index 31af15d98b09..13f019e21147 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddModuleWizard.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddModuleWizard.java @@ -36,13 +36,11 @@ import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import com.intellij.openapi.util.Condition; import com.intellij.projectImport.ProjectImportBuilder; import com.intellij.projectImport.ProjectImportProvider; -import com.intellij.ui.IdeBorderFactory; import com.intellij.util.Function; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; -import javax.swing.*; import java.awt.*; public class AddModuleWizard extends AbstractProjectWizard { @@ -135,14 +133,6 @@ public class AddModuleWizard extends AbstractProjectWizard { } @Override - protected String addStepComponent(Component component) { - if (component instanceof JComponent) { - ((JComponent)component).setBorder(IdeBorderFactory.createEmptyBorder(0, 0, 0, 0)); - } - return super.addStepComponent(component); - } - - @Override public StepSequence getSequence() { return myWizardMode.getSteps(myWizardContext, myModulesProvider); } diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java index 26571042d3df..79cace7526cf 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java @@ -108,7 +108,7 @@ public class AddSupportForFrameworksPanel implements Disposable { ((DefaultTreeModel)myFrameworksTree.getModel()).nodeChanged(getSelectedNode()); } }, this); - setProviders(providers, Collections.<String>emptySet()); + setProviders(providers, Collections.<String>emptySet(), Collections.<String>emptySet()); myFrameworksTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { @@ -129,10 +129,15 @@ public class AddSupportForFrameworksPanel implements Disposable { } - public void setProviders(List<FrameworkSupportInModuleProvider> providers, Set<String> associated) { + public void setProviders(List<FrameworkSupportInModuleProvider> providers, Set<String> associated, Set<String> preselected) { myProviders = providers; myAssociatedFrameworks = createNodes(myProviders, associated); + for (FrameworkSupportNodeBase node : myRoots) { + if (preselected.contains(node.getId())) { + node.setChecked(true); + } + } setAssociatedFrameworks(); myFrameworksTree.setRoots(myRoots); @@ -253,7 +258,7 @@ public class AddSupportForFrameworksPanel implements Disposable { private List<LibraryCompositionSettings> getLibrariesCompositionSettingsList() { List<LibraryCompositionSettings> list = new ArrayList<LibraryCompositionSettings>(); - List<FrameworkSupportNode> selected = getFrameworkNodes(true); + List<FrameworkSupportNode> selected = getSelectedNodes(); for (FrameworkSupportNode node : selected) { ContainerUtil.addIfNotNull(list, getLibraryCompositionSettings(node)); } @@ -349,34 +354,33 @@ public class AddSupportForFrameworksPanel implements Disposable { } public boolean hasSelectedFrameworks() { - return !getFrameworkNodes(true).isEmpty(); + return !getSelectedNodes().isEmpty(); } - private List<FrameworkSupportNode> getFrameworkNodes(final boolean selectedOnly) { + private List<FrameworkSupportNode> getSelectedNodes() { List<FrameworkSupportNode> list = new ArrayList<FrameworkSupportNode>(); if (myRoots != null) { - addChildFrameworks(myRoots, list, selectedOnly); + addChildFrameworks(myRoots, list); } + list.addAll(ContainerUtil.mapNotNull(myAssociatedFrameworks, new Function.InstanceOf<FrameworkSupportNodeBase, FrameworkSupportNode>(FrameworkSupportNode.class))); return list; } - private static void addChildFrameworks(final List<FrameworkSupportNodeBase> list, final List<FrameworkSupportNode> result, - final boolean selectedOnly) { + private static void addChildFrameworks(final List<FrameworkSupportNodeBase> list, final List<FrameworkSupportNode> result) { for (FrameworkSupportNodeBase node : list) { - if (!selectedOnly || node.isChecked() || node instanceof FrameworkGroupNode) { + if (node.isChecked() || node instanceof FrameworkGroupNode) { if (node instanceof FrameworkSupportNode) { result.add((FrameworkSupportNode)node); } //noinspection unchecked - addChildFrameworks(node.getChildren(), result, selectedOnly); + addChildFrameworks(node.getChildren(), result); } } } public void addSupport(final @NotNull Module module, final @NotNull ModifiableRootModel rootModel) { List<Library> addedLibraries = new ArrayList<Library>(); - List<FrameworkSupportNode> selectedFrameworks = getFrameworkNodes(true); - selectedFrameworks.addAll(ContainerUtil.mapNotNull(myAssociatedFrameworks, new Function.InstanceOf<FrameworkSupportNodeBase, FrameworkSupportNode>(FrameworkSupportNode.class))); + List<FrameworkSupportNode> selectedFrameworks = getSelectedNodes(); sortFrameworks(selectedFrameworks); List<FrameworkSupportConfigurable> selectedConfigurables = new ArrayList<FrameworkSupportConfigurable>(); final IdeaModifiableModelsProvider modifiableModelsProvider = new IdeaModifiableModelsProvider(); diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportOptionsComponent.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportOptionsComponent.java index 8237baf4538e..1b5c3b9404c8 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportOptionsComponent.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportOptionsComponent.java @@ -100,7 +100,7 @@ public class FrameworkSupportOptionsComponent { myLibraryOptionsPanel = new LibraryOptionsPanel(description, myModel.getBaseDirectoryForLibrariesPath(), createLibraryVersionFilter(), container, !myConfigurable.isOnlyLibraryAdded()) { @Override - protected void onVersionChanged(FrameworkLibraryVersion version) { + protected void onVersionChanged(@Nullable String version) { if (myFrameworkVersionComponent == null) { myModel.setSelectedLibraryVersion(provider.getId(), version); } diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworksTree.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworksTree.java index 6dcd22561e80..dc2cecdd5422 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworksTree.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworksTree.java @@ -16,7 +16,6 @@ package com.intellij.ide.util.newProjectWizard; import com.intellij.framework.FrameworkOrGroup; -import com.intellij.framework.PresentableVersion; import com.intellij.ide.util.newProjectWizard.impl.FrameworkSupportModelBase; import com.intellij.ui.CheckboxTree; import com.intellij.ui.CheckedTreeNode; @@ -114,9 +113,9 @@ public class FrameworksTree extends CheckboxTree { getTextRenderer().append(node.getTitle(), attributes); if (node.isChecked()) { FrameworkOrGroup object = node.getUserObject(); - PresentableVersion version = myModel.getPresentableVersion(object.getId()); + String version = myModel.getFrameworkVersion(object.getId()); if (version != null) { - getTextRenderer().append(" (" + version.getVersionNumber() + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES); + getTextRenderer().append(" (" + version + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES); } } getTextRenderer().setIcon(node.getIcon()); diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/LoadingProjectTemplate.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/LoadingProjectTemplate.java index 2154ec25c4ed..9cd0f67c9549 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/LoadingProjectTemplate.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/LoadingProjectTemplate.java @@ -27,7 +27,7 @@ import javax.swing.*; * @author Dmitry Avdeev * Date: 11/28/12 */ -class LoadingProjectTemplate implements ProjectTemplate { +public class LoadingProjectTemplate implements ProjectTemplate { @NotNull @Override public String getName() { diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java index 813eae735b90..1af97c19d3cd 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/ProjectTypesList.java @@ -68,7 +68,6 @@ public class ProjectTypesList implements Disposable { } }.setComparator(new SpeedSearchComparator(false)); List<TemplateItem> items = buildItems(map); - final RemoteTemplatesFactory factory = new RemoteTemplatesFactory(); final TemplatesGroup samplesGroup = new TemplatesGroup("Loading Templates...", "", null, 0); myLoadingItem = new TemplateItem(new LoadingProjectTemplate(), samplesGroup) { @Override @@ -84,6 +83,7 @@ public class ProjectTypesList implements Disposable { items.add(myLoadingItem); myModel = new CollectionListModel<TemplateItem>(items); + final RemoteTemplatesFactory factory = new RemoteTemplatesFactory(); ProgressManager.getInstance().run(new Task.Backgroundable(context.getProject(), "Loading Templates") { @Override public void run(@NotNull ProgressIndicator indicator) { diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java index e1d46ea35e30..d0a353617b5b 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java @@ -519,6 +519,7 @@ public class SelectTemplateStep extends ModuleWizardStep implements SettingsStep myModuleNameDocListenerEnabled = true; } + @Override @NotNull public JTextField getModuleNameField() { return myModuleName; diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/impl/FrameworkSupportModelBase.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/impl/FrameworkSupportModelBase.java index 3ac7333ce294..aa109764df9e 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/impl/FrameworkSupportModelBase.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/impl/FrameworkSupportModelBase.java @@ -17,10 +17,8 @@ package com.intellij.ide.util.newProjectWizard.impl; import com.intellij.facet.impl.ui.libraries.FrameworkLibraryProvider; import com.intellij.framework.FrameworkVersion; -import com.intellij.framework.PresentableVersion; import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider; import com.intellij.framework.addSupport.FrameworkVersionListener; -import com.intellij.framework.library.FrameworkLibraryVersion; import com.intellij.ide.util.frameworkSupport.FrameworkSupportConfigurable; import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel; import com.intellij.ide.util.frameworkSupport.FrameworkSupportModelListener; @@ -55,7 +53,7 @@ public abstract class FrameworkSupportModelBase extends UserDataHolderBase imple private final Map<String, FrameworkSupportNode> mySettingsMap = new HashMap<String, FrameworkSupportNode>(); private final Map<String, FrameworkSupportOptionsComponent> myOptionsComponentsMap = new HashMap<String, FrameworkSupportOptionsComponent>(); private final Map<String, FrameworkVersion> mySelectedVersions = new HashMap<String, FrameworkVersion>(); - private final Map<String, FrameworkLibraryVersion> myLibraryVersions = new HashMap<String, FrameworkLibraryVersion>(); + private final Map<String, String> myFrameworkVersions = new HashMap<String, String>(); private FrameworkLibraryProvider myLibraryProvider; public FrameworkSupportModelBase(final @Nullable Project project, @Nullable ModuleBuilder builder, @NotNull LibrariesContainer librariesContainer) { @@ -169,7 +167,7 @@ public abstract class FrameworkSupportModelBase extends UserDataHolderBase imple return myLibraryProvider; } - public void setLibraryProvider(FrameworkLibraryProvider libraryProvider) { + public void setLibraryProvider(@Nullable FrameworkLibraryProvider libraryProvider) { myLibraryProvider = libraryProvider; for (FrameworkSupportOptionsComponent optionsComponent : myOptionsComponentsMap.values()) { optionsComponent.updateLibrariesPanel(); @@ -205,13 +203,13 @@ public abstract class FrameworkSupportModelBase extends UserDataHolderBase imple return myLibrariesContainer; } - public void setSelectedLibraryVersion(String id, FrameworkLibraryVersion version) { - myLibraryVersions.put(id, version); + public void setSelectedLibraryVersion(String id, String version) { + myFrameworkVersions.put(id, version); myVersionEventDispatcher.getMulticaster().versionChanged(getSelectedVersion(id)); } - public PresentableVersion getPresentableVersion(String id) { + public String getFrameworkVersion(String id) { FrameworkVersion version = mySelectedVersions.get(id); - return version == null ? myLibraryVersions.get(id) : version; + return version == null ? myFrameworkVersions.get(id) : version.getVersionNumber(); } } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/ExistingLibraryEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/ExistingLibraryEditor.java index 7e4b7721619e..d33dbb50f2d1 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/ExistingLibraryEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/ExistingLibraryEditor.java @@ -71,10 +71,13 @@ public class ExistingLibraryEditor extends LibraryEditorBase implements Disposab private LibraryType detectType() { if (!myDetectedTypeComputed) { - final Pair<LibraryType<?>,LibraryProperties<?>> pair = LibraryDetectionManager.getInstance().detectType(Arrays.asList(getFiles(OrderRootType.CLASSES))); - if (pair != null) { - myDetectedType = pair.getFirst(); - myDetectedLibraryProperties = pair.getSecond(); + LibraryTable libraryTable = myLibrary.getTable(); + if (libraryTable == null || libraryTable.isEditable()) { + final Pair<LibraryType<?>,LibraryProperties<?>> pair = LibraryDetectionManager.getInstance().detectType(Arrays.asList(getFiles(OrderRootType.CLASSES))); + if (pair != null) { + myDetectedType = pair.getFirst(); + myDetectedLibraryProperties = pair.getSecond(); + } } myDetectedTypeComputed = true; } diff --git a/java/idea-ui/src/com/intellij/platform/templates/ArchivedProjectTemplate.java b/java/idea-ui/src/com/intellij/platform/templates/ArchivedProjectTemplate.java index adc9ddd65c36..8937dd97dcc8 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/ArchivedProjectTemplate.java +++ b/java/idea-ui/src/com/intellij/platform/templates/ArchivedProjectTemplate.java @@ -35,9 +35,11 @@ import java.util.zip.ZipInputStream; public abstract class ArchivedProjectTemplate implements ProjectTemplate { protected final String myDisplayName; + @Nullable private final String myCategory; - public ArchivedProjectTemplate(@NotNull String displayName) { + public ArchivedProjectTemplate(@NotNull String displayName, @Nullable String category) { myDisplayName = displayName; + myCategory = category; } @NotNull @@ -67,4 +69,9 @@ public abstract class ArchivedProjectTemplate implements ProjectTemplate { } public abstract ZipInputStream getStream() throws IOException; + + @Nullable + public String getCategory() { + return myCategory; + } } diff --git a/java/idea-ui/src/com/intellij/platform/templates/ArchivedTemplatesFactory.java b/java/idea-ui/src/com/intellij/platform/templates/ArchivedTemplatesFactory.java index 08c673fb1f55..b2ea5025efd2 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/ArchivedTemplatesFactory.java +++ b/java/idea-ui/src/com/intellij/platform/templates/ArchivedTemplatesFactory.java @@ -17,7 +17,7 @@ package com.intellij.platform.templates; import com.intellij.ide.fileTemplates.impl.UrlUtil; import com.intellij.ide.plugins.IdeaPluginDescriptor; -import com.intellij.ide.plugins.PluginManager; +import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; @@ -41,14 +41,14 @@ import java.util.*; */ public class ArchivedTemplatesFactory extends ProjectTemplatesFactory { - private static final String ZIP = ".zip"; + static final String ZIP = ".zip"; private final ClearableLazyValue<MultiMap<String, Pair<URL, ClassLoader>>> myGroups = new ClearableLazyValue<MultiMap<String, Pair<URL, ClassLoader>>>() { @NotNull @Override protected MultiMap<String, Pair<URL, ClassLoader>> compute() { MultiMap<String, Pair<URL, ClassLoader>> map = new MultiMap<String, Pair<URL, ClassLoader>>(); - IdeaPluginDescriptor[] plugins = PluginManager.getPlugins(); + IdeaPluginDescriptor[] plugins = PluginManagerCore.getPlugins(); Map<URL, ClassLoader> urls = new HashMap<URL, ClassLoader>(); for (IdeaPluginDescriptor plugin : plugins) { if (!plugin.isEnabled()) continue; @@ -83,7 +83,8 @@ public class ArchivedTemplatesFactory extends ProjectTemplatesFactory { if (index != -1) { child = child.substring(0, index); } - map.putValue(child.replace('_', ' '), Pair.create(new URL(url.getKey().toExternalForm() + "/" + child), url.getValue())); + String name = child.replace('_', ' '); + map.putValue(name, Pair.create(new URL(url.getKey().toExternalForm() + "/" + child), url.getValue())); } } catch (IOException e) { @@ -132,8 +133,7 @@ public class ArchivedTemplatesFactory extends ProjectTemplatesFactory { for (String child : children) { if (child.endsWith(ZIP)) { URL templateUrl = new URL(url.first.toExternalForm() + "/" + child); - String name = getTemplateName(child); - templates.add(new LocalArchivedTemplate(name, templateUrl, url.second)); + templates.add(new LocalArchivedTemplate(templateUrl, url.second)); } } } @@ -144,10 +144,6 @@ public class ArchivedTemplatesFactory extends ProjectTemplatesFactory { return templates.toArray(new ProjectTemplate[templates.size()]); } - public static String getTemplateName(String child) { - return child.substring(0, child.length() - ZIP.length()).replace('_', ' '); - } - @Override public int getGroupWeight(String group) { return CUSTOM_GROUP.equals(group) ? -2 : 0; diff --git a/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java b/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java index f671335e6d7e..e9c84800dafe 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java +++ b/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java @@ -31,6 +31,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collections; @@ -52,10 +53,9 @@ public class LocalArchivedTemplate extends ArchivedProjectTemplate { private List<WizardInputField> myInputFields = Collections.emptyList(); private Icon myIcon; - public LocalArchivedTemplate(@NotNull String displayName, - @NotNull URL archivePath, + public LocalArchivedTemplate(@NotNull URL archivePath, @NotNull ClassLoader classLoader) { - super(displayName); + super(getTemplateName(archivePath), null); myArchivePath = archivePath; myModuleType = computeModuleType(this); @@ -80,6 +80,11 @@ public class LocalArchivedTemplate extends ArchivedProjectTemplate { } } + private static String getTemplateName(URL url) { + String fileName = new File(url.getPath()).getName(); + return fileName.substring(0, fileName.length() - ArchivedTemplatesFactory.ZIP.length()).replace('_', ' '); + } + @Override public String getDescription() { return readEntry(new Condition<ZipEntry>() { diff --git a/java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java b/java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java index d3db36470740..f62333ce30b2 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java +++ b/java/idea-ui/src/com/intellij/platform/templates/RemoteTemplatesFactory.java @@ -147,7 +147,7 @@ public class RemoteTemplatesFactory extends ProjectTemplatesFactory { final String path = element.getChildText("path", ns); final String description = element.getChildTextTrim("description", ns); String name = element.getChildTextTrim("name", ns); - return new ArchivedProjectTemplate(name) { + return new ArchivedProjectTemplate(name, element.getChildTextTrim("category")) { @Override protected ModuleType getModuleType() { return moduleType; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java index 0a804c583a51..064888bf4215 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java @@ -539,6 +539,7 @@ public class HighlightClassUtil { @NotNull PsiResolveHelper resolveHelper, @NotNull TextRange range, @NotNull PsiClassType[] handledExceptions) { + if (aClass instanceof PsiAnonymousClass) return null; PsiClass baseClass = aClass.getSuperClass(); if (baseClass == null) return null; PsiMethod[] constructors = baseClass.getConstructors(); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java index 7a89381553f8..8d845ff3023e 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java @@ -31,6 +31,7 @@ import com.intellij.util.IncorrectOperationException; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Stack; +import com.siyeh.ig.numeric.UnnecessaryExplicitNumericCastInspection; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -79,7 +80,7 @@ public class ControlFlowAnalyzer extends JavaElementVisitor { myAssertionError = createClassType(manager, scope, JAVA_LANG_ASSERTION_ERROR); myString = myFactory.createTypeValue(createClassType(manager, scope, JAVA_LANG_STRING), Nullness.NOT_NULL); - PsiParameter mockVar = JavaPsiFacade.getElementFactory(manager.getProject()).createParameter("$exception$", createClassType(manager, scope, JAVA_LANG_OBJECT)); + PsiParameter mockVar = JavaPsiFacade.getElementFactory(manager.getProject()).createParameterFromText("java.lang.Object $exception$", null); myExceptionHolder = myFactory.getVarFactory().createVariableValue(mockVar, false); myFields = new HashSet<DfaVariableValue>(); @@ -312,6 +313,14 @@ public class ControlFlowAnalyzer extends JavaElementVisitor { } } } + else if (parent instanceof PsiTryStatement) { + PsiResourceList list = ((PsiTryStatement)parent).getResourceList(); + if (list != null) { + for (PsiResourceVariable variable : list.getResourceVariables()) { + myCurrentFlow.removeVariable(variable); + } + } + } } @Override public void visitBlockStatement(PsiBlockStatement statement) { @@ -1866,7 +1875,13 @@ public class ControlFlowAnalyzer extends JavaElementVisitor { final PsiTypeElement typeElement = castExpression.getCastType(); if (typeElement != null && operand != null) { - addInstruction(new TypeCastInstruction(castExpression, operand, typeElement.getType())); + if (typeElement.getType() instanceof PsiPrimitiveType && + UnnecessaryExplicitNumericCastInspection.isPrimitiveNumericCastNecessary(castExpression)) { + addInstruction(new PopInstruction()); + pushUnknown(); + } else { + addInstruction(new TypeCastInstruction(castExpression, operand, typeElement.getType())); + } } finishElement(castExpression); } diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/RedundantTypeArgsInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/RedundantTypeArgsInspection.java index f94d1a600ba0..bb3c4ea3b8a9 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/RedundantTypeArgsInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/RedundantTypeArgsInspection.java @@ -15,6 +15,7 @@ */ package com.intellij.codeInspection.miscGenerics; +import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInspection.*; import com.intellij.openapi.diagnostic.Logger; @@ -150,6 +151,7 @@ public class RedundantTypeArgsInspection extends GenericsInspectionToolBase { @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiReferenceParameterList typeArgumentList = (PsiReferenceParameterList)descriptor.getPsiElement(); + if (!FileModificationService.getInstance().preparePsiElementForWrite(typeArgumentList)) return; try { final PsiMethodCallExpression expr = (PsiMethodCallExpression)JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText("foo()", null); diff --git a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypeInfoImpl.java b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypeInfoImpl.java index dd46437867c3..227825b4aced 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypeInfoImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypeInfoImpl.java @@ -17,10 +17,13 @@ package com.intellij.codeInsight; import com.intellij.openapi.util.NullableComputable; +import com.intellij.openapi.util.NullableLazyValue; +import com.intellij.openapi.util.VolatileNullableLazyValue; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiType; import com.intellij.psi.util.PsiUtil; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class ExpectedTypeInfoImpl implements ExpectedTypeInfo { public static final NullableComputable<String> NULL = new NullableComputable<String>() { @@ -37,7 +40,8 @@ public class ExpectedTypeInfoImpl implements ExpectedTypeInfo { @NotNull private final TailType myTailType; private final PsiMethod myCalledMethod; - @NotNull private final NullableComputable<String> expectedName; + @NotNull private final NullableComputable<String> expectedNameComputable; + @NotNull private final NullableLazyValue<String> expectedNameLazyValue; @Override public int getKind() { @@ -62,15 +66,22 @@ public class ExpectedTypeInfoImpl implements ExpectedTypeInfo { this.myTailType = myTailType; this.defaultType = defaultType; myCalledMethod = calledMethod; - this.expectedName = expectedName; + this.expectedNameComputable = expectedName; + expectedNameLazyValue = new VolatileNullableLazyValue<String>() { + @Nullable + @Override + protected String compute() { + return expectedNameComputable.compute(); + } + }; PsiUtil.ensureValidType(type); PsiUtil.ensureValidType(defaultType); } - @NotNull - public NullableComputable<String> getExpectedName() { - return expectedName; + @Nullable + public String getExpectedName() { + return expectedNameLazyValue.getValue(); } @Override diff --git a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java index bc6273eb1074..c9f75a0486b5 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java @@ -630,9 +630,15 @@ public class ExpectedTypesProvider { myResult = visitor.getResult(); if (!(expr.getParent() instanceof PsiExpressionList)) { for (int i = 0; i < myResult.length; i++) { - ExpectedTypeInfo info = myResult[i]; + final ExpectedTypeInfo info = myResult[i]; myResult[i] = createInfoImpl(info.getType(), info.getKind(), info.getDefaultType(), TailType.NONE, info.getCalledMethod(), - ((ExpectedTypeInfoImpl)info).getExpectedName()); + new NullableComputable<String>() { + @Nullable + @Override + public String compute() { + return ((ExpectedTypeInfoImpl)info).getExpectedName(); + } + }); } } return; @@ -870,9 +876,15 @@ public class ExpectedTypesProvider { else if (myExpr.equals(expr.getThenExpression())) { ExpectedTypeInfo[] types = getExpectedTypes(expr, myForCompletion); for (int i = 0; i < types.length; i++) { - ExpectedTypeInfo info = types[i]; + final ExpectedTypeInfo info = types[i]; types[i] = createInfoImpl(info.getType(), info.getKind(), info.getDefaultType(), TailType.COND_EXPR_COLON, info.getCalledMethod(), - ((ExpectedTypeInfoImpl)info).getExpectedName()); + new NullableComputable<String>() { + @Nullable + @Override + public String compute() { + return ((ExpectedTypeInfoImpl)info).getExpectedName(); + } + }); } myResult = types; } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java b/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java index 1bdedafa4219..2367ce3deb11 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java @@ -25,6 +25,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.psi.*; import com.intellij.psi.impl.source.PostprocessReformattingAspect; +import com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.AllClassesSearch; import com.intellij.util.Consumer; @@ -155,6 +156,10 @@ public class AllClassesGetter { @Override public boolean process(PsiClass psiClass) { + if (parameters.getInvocationCount() < 2 && PsiReferenceExpressionImpl.seemsScrambled(psiClass)) { + return true; + } + assert psiClass != null; if (isAcceptableInContext(context, psiClass, filterByScope, pkgContext)) { String qName = psiClass.getQualifiedName(); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java index e2296e4c3d2c..cabc5d915fed 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java @@ -227,7 +227,7 @@ public class JavaCompletionSorting { private static int calcMatch(final List<String> words, int max, ExpectedTypeInfo[] myExpectedInfos) { for (ExpectedTypeInfo myExpectedInfo : myExpectedInfos) { - String expectedName = ((ExpectedTypeInfoImpl)myExpectedInfo).getExpectedName().compute(); + String expectedName = ((ExpectedTypeInfoImpl)myExpectedInfo).getExpectedName(); if (expectedName == null) continue; max = calcMatch(expectedName, words, max); max = calcMatch(truncDigits(expectedName), words, max); @@ -504,7 +504,7 @@ public class JavaCompletionSorting { int max = 0; final List<String> wordsNoDigits = NameUtil.nameToWordsLowerCase(truncDigits(name)); for (ExpectedTypeInfo myExpectedInfo : myExpectedTypes) { - String expectedName = ((ExpectedTypeInfoImpl)myExpectedInfo).getExpectedName().compute(); + String expectedName = ((ExpectedTypeInfoImpl)myExpectedInfo).getExpectedName(); if (expectedName != null) { final THashSet<String> set = new THashSet<String>(NameUtil.nameToWordsLowerCase(truncDigits(expectedName))); set.retainAll(wordsNoDigits); diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionStatistician.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionStatistician.java index bcc783643a91..c5c1e3994a46 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionStatistician.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionStatistician.java @@ -56,7 +56,7 @@ public class JavaCompletionStatistician extends CompletionStatistician{ PsiClass containingClass = ((PsiMember)o).getContainingClass(); if (containingClass != null) { - String expectedName = firstInfo instanceof ExpectedTypeInfoImpl ? ((ExpectedTypeInfoImpl)firstInfo).getExpectedName().compute() : null; + String expectedName = firstInfo instanceof ExpectedTypeInfoImpl ? ((ExpectedTypeInfoImpl)firstInfo).getExpectedName() : null; String contextPrefix = expectedName == null ? "" : "expectedName=" + expectedName + "###"; String context = contextPrefix + JavaStatisticsManager.getMemberUseKey2(containingClass); diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/ListSelectioner.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/ListSelectioner.java index 2404f21a17b0..a608c6e8b449 100644 --- a/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/ListSelectioner.java +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/ListSelectioner.java @@ -50,7 +50,9 @@ public class ListSelectioner extends BasicSelectioner { } List<TextRange> result = new ArrayList<TextRange>(); - result.add(new TextRange(start, end)); + if (start != 0 && end != 0) { + result.add(new TextRange(start, end)); + } return result; } } diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/ui/GenerateEqualsWizard.java b/java/java-impl/src/com/intellij/codeInsight/generation/ui/GenerateEqualsWizard.java index 85e9674fc2bb..c051e3a2aa1c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/ui/GenerateEqualsWizard.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/ui/GenerateEqualsWizard.java @@ -243,7 +243,7 @@ public class GenerateEqualsWizard extends AbstractGenerateEqualsWizard<PsiClass, @Override protected void addSteps() { if (myEqualsPanel != null) { - addStep(new InstanceofOptionStep()); + addStep(new InstanceofOptionStep(myClass.hasModifierProperty(PsiModifier.FINAL))); } super.addSteps(); } @@ -322,9 +322,10 @@ public class GenerateEqualsWizard extends AbstractGenerateEqualsWizard<PsiClass, private static class InstanceofOptionStep extends StepAdapter { private final JComponent myPanel; - private InstanceofOptionStep() { + private InstanceofOptionStep(boolean isFinal) { final JCheckBox checkbox = new NonFocusableCheckBox(CodeInsightBundle.message("generate.equals.hashcode.accept.sublcasses")); - checkbox.setSelected(CodeInsightSettings.getInstance().USE_INSTANCEOF_ON_EQUALS_PARAMETER); + checkbox.setSelected(!isFinal && CodeInsightSettings.getInstance().USE_INSTANCEOF_ON_EQUALS_PARAMETER); + checkbox.setEnabled(!isFinal); checkbox.addActionListener(new ActionListener() { public void actionPerformed(@NotNull final ActionEvent M) { CodeInsightSettings.getInstance().USE_INSTANCEOF_ON_EQUALS_PARAMETER = checkbox.isSelected(); diff --git a/java/java-impl/src/com/intellij/externalSystem/JavaProjectDataService.java b/java/java-impl/src/com/intellij/externalSystem/JavaProjectDataService.java index 47f4b0a3d4bb..bd394124d9b2 100644 --- a/java/java-impl/src/com/intellij/externalSystem/JavaProjectDataService.java +++ b/java/java-impl/src/com/intellij/externalSystem/JavaProjectDataService.java @@ -18,6 +18,7 @@ package com.intellij.externalSystem; import com.intellij.openapi.externalSystem.model.DataNode; import com.intellij.openapi.externalSystem.model.Key; import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataService; +import com.intellij.openapi.externalSystem.util.DisposeAwareProjectChange; import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; @@ -105,9 +106,9 @@ public class JavaProjectDataService implements ProjectDataService<JavaProjectDat if (languageLevelExtension.getLanguageLevel().isAtLeast(languageLevel)) { return; } - ExternalSystemApiUtil.executeProjectChangeAction(synchronous, new Runnable() { + ExternalSystemApiUtil.executeProjectChangeAction(synchronous, new DisposeAwareProjectChange(project) { @Override - public void run() { + public void execute() { languageLevelExtension.setLanguageLevel(languageLevel); } }); diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/call/CallHierarchyNodeDescriptor.java b/java/java-impl/src/com/intellij/ide/hierarchy/call/CallHierarchyNodeDescriptor.java index 4dacb84d0469..4eb3a33b83e9 100644 --- a/java/java-impl/src/com/intellij/ide/hierarchy/call/CallHierarchyNodeDescriptor.java +++ b/java/java-impl/src/com/intellij/ide/hierarchy/call/CallHierarchyNodeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 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. @@ -34,12 +34,8 @@ import com.intellij.openapi.util.TextRange; import com.intellij.pom.Navigatable; import com.intellij.psi.*; import com.intellij.psi.presentation.java.ClassPresentationUtil; -import com.intellij.psi.util.PsiFormatUtil; -import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.psi.util.PsiUtilBase; -import com.intellij.psi.util.PsiUtilCore; +import com.intellij.psi.util.*; import com.intellij.ui.LayeredIcon; -import com.intellij.psi.util.FileTypeUtils; import org.jetbrains.annotations.NotNull; import javax.swing.*; @@ -68,7 +64,7 @@ public final class CallHierarchyNodeDescriptor extends HierarchyNodeDescriptor i return myElement == null ? null : getEnclosingElement(myElement); } - static PsiMember getEnclosingElement(final PsiElement element){ + public static PsiMember getEnclosingElement(final PsiElement element){ return PsiTreeUtil.getNonStrictParentOfType(element, PsiMethod.class, PsiClass.class); } @@ -138,8 +134,8 @@ public final class CallHierarchyNodeDescriptor extends HierarchyNodeDescriptor i } final String methodText = PsiFormatUtil.formatMethod( method, - PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_PARAMETERS, - PsiFormatUtil.SHOW_TYPE + PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS, + PsiFormatUtilBase.SHOW_TYPE ); buffer.append(methodText); diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/call/CallerMethodsTreeStructure.java b/java/java-impl/src/com/intellij/ide/hierarchy/call/CallerMethodsTreeStructure.java index 5699d335c28e..45363bbef95f 100644 --- a/java/java-impl/src/com/intellij/ide/hierarchy/call/CallerMethodsTreeStructure.java +++ b/java/java-impl/src/com/intellij/ide/hierarchy/call/CallerMethodsTreeStructure.java @@ -17,12 +17,11 @@ package com.intellij.ide.hierarchy.call; import com.intellij.ide.hierarchy.HierarchyNodeDescriptor; import com.intellij.ide.hierarchy.HierarchyTreeStructure; +import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.MethodReferencesSearch; -import com.intellij.psi.util.PsiUtil; -import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; @@ -63,69 +62,15 @@ public final class CallerMethodsTreeStructure extends HierarchyTreeStructure { methodsToFind.add(method); ContainerUtil.addAll(methodsToFind, method.findDeepestSuperMethods()); - final Map<PsiMember, CallHierarchyNodeDescriptor> methodToDescriptorMap = new HashMap<PsiMember, CallHierarchyNodeDescriptor>(); + final Map<PsiMember, NodeDescriptor> methodToDescriptorMap = new HashMap<PsiMember, NodeDescriptor>(); for (final PsiMethod methodToFind : methodsToFind) { + final JavaCallHierarchyData data = new JavaCallHierarchyData(originalClass, methodToFind, originalType, method, methodsToFind, descriptor, methodToDescriptorMap, myProject); + MethodReferencesSearch.search(methodToFind, searchScope, true).forEach(new Processor<PsiReference>() { @Override public boolean process(final PsiReference reference) { - if (reference instanceof PsiReferenceExpression) { - final PsiExpression qualifier = ((PsiReferenceExpression)reference).getQualifierExpression(); - if (qualifier instanceof PsiSuperExpression) { // filter super.foo() call inside foo() and similar cases (bug 8411) - final PsiClass superClass = PsiUtil.resolveClassInType(qualifier.getType()); - if (originalClass.isInheritor(superClass, true)) { - return true; - } - } - if (qualifier != null && !methodToFind.hasModifierProperty(PsiModifier.STATIC)) { - final PsiType qualifierType = qualifier.getType(); - if (qualifierType instanceof PsiClassType && - !TypeConversionUtil.isAssignable(qualifierType, originalType) && - methodToFind != method) { - final PsiClass psiClass = ((PsiClassType)qualifierType).resolve(); - if (psiClass != null) { - final PsiMethod callee = psiClass.findMethodBySignature(methodToFind, true); - if (callee != null && !methodsToFind.contains(callee)) { - // skip sibling methods - return true; - } - } - } - } - } - else { - if (!(reference instanceof PsiElement)) { - return true; - } - - final PsiElement parent = ((PsiElement)reference).getParent(); - if (parent instanceof PsiNewExpression) { - if (((PsiNewExpression)parent).getClassReference() != reference) { - return true; - } - } - else if (parent instanceof PsiAnonymousClass) { - if (((PsiAnonymousClass)parent).getBaseClassReference() != reference) { - return true; - } - } - else { - return true; - } - } - - final PsiElement element = reference.getElement(); - final PsiMember key = CallHierarchyNodeDescriptor.getEnclosingElement(element); - - synchronized (methodToDescriptorMap) { - CallHierarchyNodeDescriptor d = methodToDescriptorMap.get(key); - if (d == null) { - d = new CallHierarchyNodeDescriptor(myProject, descriptor, element, false, true); - methodToDescriptorMap.put(key, d); - } - else if (!d.hasReference(reference)) { - d.incrementUsageCount(); - } - d.addReference(reference); + for (CallReferenceProcessor processor : CallReferenceProcessor.EP_NAME.getExtensions()) { + if (!processor.process(reference, data)) break; } return true; } diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/call/JavaCallReferenceProcessor.java b/java/java-impl/src/com/intellij/ide/hierarchy/call/JavaCallReferenceProcessor.java new file mode 100644 index 000000000000..e563ee64381f --- /dev/null +++ b/java/java-impl/src/com/intellij/ide/hierarchy/call/JavaCallReferenceProcessor.java @@ -0,0 +1,103 @@ +/* + * Copyright 2000-2013 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.hierarchy.call; + +import com.intellij.ide.util.treeView.NodeDescriptor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.psi.util.PsiUtil; +import com.intellij.psi.util.TypeConversionUtil; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; +import java.util.Set; + +/** + * Created by Max Medvedev on 10/5/13 + */ +public class JavaCallReferenceProcessor implements CallReferenceProcessor { + @Override + public boolean process(@NotNull PsiReference reference, @NotNull JavaCallHierarchyData data) { + PsiClass originalClass = data.getOriginalClass(); + PsiMethod method = data.getMethod(); + Set<PsiMethod> methodsToFind = data.getMethodsToFind(); + PsiMethod methodToFind = data.getMethodToFind(); + PsiClassType originalType = data.getOriginalType(); + Map<PsiMember, NodeDescriptor> methodToDescriptorMap = data.getResultMap(); + Project myProject = data.getProject(); + + if (reference instanceof PsiReferenceExpression) { + final PsiExpression qualifier = ((PsiReferenceExpression)reference).getQualifierExpression(); + if (qualifier instanceof PsiSuperExpression) { // filter super.foo() call inside foo() and similar cases (bug 8411) + final PsiClass superClass = PsiUtil.resolveClassInType(qualifier.getType()); + if (superClass == null || originalClass.isInheritor(superClass, true)) { + return true; + } + } + if (qualifier != null && !methodToFind.hasModifierProperty(PsiModifier.STATIC)) { + final PsiType qualifierType = qualifier.getType(); + if (qualifierType instanceof PsiClassType && + !TypeConversionUtil.isAssignable(qualifierType, originalType) && + methodToFind != method) { + final PsiClass psiClass = ((PsiClassType)qualifierType).resolve(); + if (psiClass != null) { + final PsiMethod callee = psiClass.findMethodBySignature(methodToFind, true); + if (callee != null && !methodsToFind.contains(callee)) { + // skip sibling methods + return true; + } + } + } + } + } + else { + if (!(reference instanceof PsiElement)) { + return true; + } + + final PsiElement parent = ((PsiElement)reference).getParent(); + if (parent instanceof PsiNewExpression) { + if (((PsiNewExpression)parent).getClassReference() != reference) { + return true; + } + } + else if (parent instanceof PsiAnonymousClass) { + if (((PsiAnonymousClass)parent).getBaseClassReference() != reference) { + return true; + } + } + else { + return true; + } + } + + final PsiElement element = reference.getElement(); + final PsiMember key = CallHierarchyNodeDescriptor.getEnclosingElement(element); + + synchronized (methodToDescriptorMap) { + CallHierarchyNodeDescriptor d = (CallHierarchyNodeDescriptor)methodToDescriptorMap.get(key); + if (d == null) { + d = new CallHierarchyNodeDescriptor(myProject, (CallHierarchyNodeDescriptor)data.getNodeDescriptor(), element, false, true); + methodToDescriptorMap.put(key, d); + } + else if (!d.hasReference(reference)) { + d.incrementUsageCount(); + } + d.addReference(reference); + } + return false; + } +} diff --git a/java/java-impl/src/com/intellij/ide/projectView/actions/MarkGeneratedSourceRootAction.java b/java/java-impl/src/com/intellij/ide/projectView/actions/MarkGeneratedSourceRootAction.java new file mode 100644 index 000000000000..e56a43233581 --- /dev/null +++ b/java/java-impl/src/com/intellij/ide/projectView/actions/MarkGeneratedSourceRootAction.java @@ -0,0 +1,69 @@ +/* + * Copyright 2000-2013 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.projectView.actions; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.actionSystem.Presentation; +import com.intellij.openapi.module.JavaModuleType; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleType; +import com.intellij.openapi.roots.ContentEntry; +import com.intellij.openapi.roots.SourceFolder; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; +import org.jetbrains.jps.model.java.JavaSourceRootProperties; +import org.jetbrains.jps.model.java.JavaSourceRootType; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; + +/** + * @author nik + */ +public class MarkGeneratedSourceRootAction extends MarkRootActionBase { + public MarkGeneratedSourceRootAction() { + Presentation presentation = getTemplatePresentation(); + presentation.setIcon(AllIcons.Modules.SourceRoot); + presentation.setText("Generated Sources Root"); + presentation.setDescription("Mark directory as a source root for generated files"); + } + + @Override + protected boolean isEnabled(@NotNull RootsSelection selection, @NotNull Module module) { + if (!(ModuleType.get(module) instanceof JavaModuleType)) return false; + + if (selection.myHaveSelectedFilesUnderSourceRoots) { + return false; + } + + if (!selection.mySelectedDirectories.isEmpty()) { + return true; + } + + for (SourceFolder root : selection.mySelectedRoots) { + JavaSourceRootProperties properties = root.getJpsElement().getProperties(JavaModuleSourceRootTypes.SOURCES); + if (properties != null && !properties.isForGeneratedSources()) { + return true; + } + } + return false; + } + + @Override + protected void modifyRoots(VirtualFile vFile, ContentEntry entry) { + JavaSourceRootProperties properties = JpsJavaExtensionService.getInstance().createSourceRootProperties("", true); + entry.addSourceFolder(vFile, JavaSourceRootType.SOURCE, properties); + } +} diff --git a/java/java-impl/src/com/intellij/ide/projectView/actions/UnmarkGeneratedSourceRootAction.java b/java/java-impl/src/com/intellij/ide/projectView/actions/UnmarkGeneratedSourceRootAction.java new file mode 100644 index 000000000000..0af8706ab38c --- /dev/null +++ b/java/java-impl/src/com/intellij/ide/projectView/actions/UnmarkGeneratedSourceRootAction.java @@ -0,0 +1,55 @@ +/* + * Copyright 2000-2013 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.projectView.actions; + +import com.intellij.icons.AllIcons; +import com.intellij.openapi.actionSystem.Presentation; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.roots.ContentEntry; +import com.intellij.openapi.roots.SourceFolder; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; +import org.jetbrains.jps.model.java.JavaSourceRootProperties; +import org.jetbrains.jps.model.java.JavaSourceRootType; + +/** + * @author nik + */ +public class UnmarkGeneratedSourceRootAction extends MarkRootActionBase { + public UnmarkGeneratedSourceRootAction() { + Presentation presentation = getTemplatePresentation(); + presentation.setIcon(AllIcons.Modules.SourceRoot); + presentation.setText("Unmark Generated Sources Root"); + presentation.setDescription("Mark directory as an ordinary source root"); + } + + @Override + protected boolean isEnabled(@NotNull RootsSelection selection, @NotNull Module module) { + for (SourceFolder root : selection.mySelectedRoots) { + JavaSourceRootProperties properties = root.getJpsElement().getProperties(JavaModuleSourceRootTypes.SOURCES); + if (properties != null && properties.isForGeneratedSources()) { + return true; + } + } + return false; + } + + @Override + protected void modifyRoots(VirtualFile vFile, ContentEntry entry) { + entry.addSourceFolder(vFile, JavaSourceRootType.SOURCE); + } +} diff --git a/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java b/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java index bf58e0f2253b..fe598e3e8d7f 100644 --- a/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java +++ b/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java @@ -30,6 +30,7 @@ import com.intellij.ide.BrowserUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; +import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; @@ -57,6 +58,7 @@ import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.List; +import java.util.Set; /** * @author Eugene Zhuravlev @@ -228,13 +230,24 @@ public class JavadocConfiguration implements ModuleRunProfile, JDOMExternalizabl parameters.addParametersString(OTHER_OPTIONS); + final Set<Module> modules = new HashSet<Module>(); + myGenerationOptions.accept(new PsiRecursiveElementWalkingVisitor() { + @Override + public void visitFile(PsiFile file) { + final Module module = ModuleUtilCore.findModuleForPsiElement(file); + if (module != null) { + modules.add(module); + } + } + }); final PathsList classPath; + final OrderEnumerator orderEnumerator = ProjectRootManager.getInstance(myProject).orderEntries(modules); if (jdk.getSdkType() instanceof JavaSdk) { - classPath = OrderEnumerator.orderEntries(myProject).withoutSdk().withoutModuleSourceEntries().getPathsList(); + classPath = orderEnumerator.withoutSdk().withoutModuleSourceEntries().getPathsList(); } else { //libraries are included into jdk - classPath = OrderEnumerator.orderEntries(myProject).withoutModuleSourceEntries().getPathsList(); + classPath = orderEnumerator.withoutModuleSourceEntries().getPathsList(); } final String classPathString = classPath.getPathsString(); if (classPathString.length() > 0) { diff --git a/java/java-impl/src/com/intellij/openapi/roots/JavaGeneratedSourcesFilter.java b/java/java-impl/src/com/intellij/openapi/roots/JavaGeneratedSourcesFilter.java new file mode 100644 index 000000000000..89e121e0bd47 --- /dev/null +++ b/java/java-impl/src/com/intellij/openapi/roots/JavaGeneratedSourcesFilter.java @@ -0,0 +1,30 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.openapi.roots; + +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; + +/** + * @author nik + */ +public class JavaGeneratedSourcesFilter extends GeneratedSourcesFilter { + @Override + public boolean isGeneratedSource(@NotNull VirtualFile file, @NotNull Project project) { + return JavaProjectRootsUtil.isInGeneratedCode(file, project); + } +} diff --git a/java/java-impl/src/com/intellij/openapi/roots/JavaProjectRootsUtil.java b/java/java-impl/src/com/intellij/openapi/roots/JavaProjectRootsUtil.java index 6a04def9469c..cecab4e02d2b 100644 --- a/java/java-impl/src/com/intellij/openapi/roots/JavaProjectRootsUtil.java +++ b/java/java-impl/src/com/intellij/openapi/roots/JavaProjectRootsUtil.java @@ -3,7 +3,6 @@ package com.intellij.openapi.roots; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.impl.SourceFolderImpl; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiCodeFragment; import com.intellij.psi.PsiFile; @@ -39,8 +38,7 @@ public class JavaProjectRootsUtil { for (Module module : ModuleManager.getInstance(project).getModules()) { for (ContentEntry entry : ModuleRootManager.getInstance(module).getContentEntries()) { for (SourceFolder sourceFolder : entry.getSourceFolders(JavaModuleSourceRootTypes.SOURCES)) { - JavaSourceRootProperties properties = (JavaSourceRootProperties)((SourceFolderImpl)sourceFolder).getJpsElement().getProperties(); - if (!properties.isForGeneratedSources()) { + if (!isForGeneratedSources(sourceFolder)) { ContainerUtil.addIfNotNull(roots, sourceFolder.getFile()); } } @@ -48,4 +46,27 @@ public class JavaProjectRootsUtil { } return roots; } + + private static boolean isForGeneratedSources(SourceFolder sourceFolder) { + JavaSourceRootProperties properties = sourceFolder.getJpsElement().getProperties(JavaModuleSourceRootTypes.SOURCES); + return properties != null && properties.isForGeneratedSources(); + } + + public static boolean isInGeneratedCode(@NotNull VirtualFile file, @NotNull Project project) { + ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); + Module module = fileIndex.getModuleForFile(file); + if (module == null) return false; + + VirtualFile sourceRoot = fileIndex.getSourceRootForFile(file); + if (sourceRoot == null) return false; + + for (ContentEntry entry : ModuleRootManager.getInstance(module).getContentEntries()) { + for (SourceFolder folder : entry.getSourceFolders()) { + if (sourceRoot.equals(folder.getFile())) { + return isForGeneratedSources(folder); + } + } + } + return false; + } } diff --git a/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java b/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java index d720a01eb987..ab6289584719 100644 --- a/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java @@ -40,10 +40,12 @@ import com.intellij.psi.impl.source.codeStyle.ImportHelper; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.Set; @@ -115,19 +117,22 @@ public class JavaPsiImplementationHelperImpl extends JavaPsiImplementationHelper final VirtualFile vFile = clsFile.getContainingFile().getVirtualFile(); ProjectFileIndex projectFileIndex = ProjectFileIndex.SERVICE.getInstance(clsFile.getProject()); - final List<OrderEntry> orderEntries = projectFileIndex.getOrderEntriesForFile(vFile); - for (OrderEntry orderEntry : orderEntries) { - VirtualFile[] files = orderEntry.getFiles(OrderRootType.SOURCES); - for (VirtualFile file : files) { - VirtualFile source = file.findFileByRelativePath(relativeFilePath); - if (source != null) { - PsiFile psiSource = clsFile.getManager().findFile(source); - if (psiSource instanceof PsiClassOwner) { - return psiSource; - } + final Set<VirtualFile> sourceRoots = ContainerUtil.newLinkedHashSet(); + for (OrderEntry orderEntry : projectFileIndex.getOrderEntriesForFile(vFile)) { + if (orderEntry instanceof LibraryOrSdkOrderEntry) { + Collections.addAll(sourceRoots, orderEntry.getFiles(OrderRootType.SOURCES)); + } + } + for (VirtualFile root : sourceRoots) { + VirtualFile source = root.findFileByRelativePath(relativeFilePath); + if (source != null) { + PsiFile psiSource = clsFile.getManager().findFile(source); + if (psiSource instanceof PsiClassOwner) { + return psiSource; } } } + return clsFile; } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaReferenceAdjuster.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaReferenceAdjuster.java index 446a6a2b4aa0..c06976774177 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaReferenceAdjuster.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaReferenceAdjuster.java @@ -133,8 +133,13 @@ public class JavaReferenceAdjuster implements ReferenceAdjuster { PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement)element.getPsi(); PsiElement qualifier = ref.getQualifier(); - if (qualifier instanceof PsiJavaCodeReferenceElement && PsiTreeUtil.getChildOfType(qualifier, PsiAnnotation.class) != null) { - return true; + if (qualifier instanceof PsiJavaCodeReferenceElement) { + if (((PsiJavaCodeReferenceElement)qualifier).resolve() instanceof PsiPackage) { + return false; + } + if (PsiTreeUtil.getChildOfType(qualifier, PsiAnnotation.class) != null) { + return true; + } } PsiModifierList modifierList = PsiImplUtil.findNeighbourModifierList(ref); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java index 271e83238b2f..4ec3a1397111 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java @@ -954,6 +954,7 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { final PsiElement parent = expr1.getUserData(ElementToWorkOn.PARENT); final RangeMarker rangeMarker = expr1.getUserData(ElementToWorkOn.TEXT_RANGE); + LOG.assertTrue(parent != null, expr1); return parent.replace(createReplacement(ref.getText(), project, prefix, suffix, parent, rangeMarker, new int[1])); } } diff --git a/java/java-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java b/java/java-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java index 3cc473aa8021..be8cab8538bf 100644 --- a/java/java-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 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,7 +18,6 @@ package com.intellij.refactoring.invertBoolean; import com.intellij.ide.util.SuperMethodWarningUtil; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.project.Project; @@ -70,8 +69,13 @@ public class InvertBooleanHandler implements RefactoringActionHandler { } public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, @NotNull DataContext dataContext) { - if (elements.length == 1 && elements[0] instanceof PsiMethod) { - invoke((PsiMethod)elements[0], project, null); + if (elements.length == 1) { + if (elements[0] instanceof PsiMethod) { + invoke((PsiMethod)elements[0], project, null); + } + else if (elements[0] instanceof PsiVariable) { + invoke((PsiVariable)elements[0], project, null); + } } } diff --git a/java/java-impl/src/com/intellij/slicer/SliceForwardUtil.java b/java/java-impl/src/com/intellij/slicer/SliceForwardUtil.java index 7374d1136c95..254498e5674d 100644 --- a/java/java-impl/src/com/intellij/slicer/SliceForwardUtil.java +++ b/java/java-impl/src/com/intellij/slicer/SliceForwardUtil.java @@ -23,7 +23,7 @@ import com.intellij.psi.search.searches.OverridingMethodsSearch; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.MethodSignatureUtil; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.util.ArrayUtil; +import com.intellij.util.ArrayUtilRt; import com.intellij.util.Processor; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; @@ -242,7 +242,7 @@ public class SliceForwardUtil { //method call else if (parent instanceof PsiExpressionList && parent.getParent() instanceof PsiCallExpression) { PsiExpression[] expressions = ((PsiExpressionList)parent).getExpressions(); - int index = ArrayUtil.find(expressions, element); + int index = ArrayUtilRt.find(expressions, element); PsiCallExpression methodCall = (PsiCallExpression)parent.getParent(); JavaResolveResult result = methodCall.resolveMethodGenerics(); PsiMethod method = (PsiMethod)result.getElement(); diff --git a/java/java-impl/src/com/intellij/spi/psi/SPIClassProviderReferenceElement.java b/java/java-impl/src/com/intellij/spi/psi/SPIClassProviderReferenceElement.java index 7d9fc0218be5..1563adae7bc5 100644 --- a/java/java-impl/src/com/intellij/spi/psi/SPIClassProviderReferenceElement.java +++ b/java/java-impl/src/com/intellij/spi/psi/SPIClassProviderReferenceElement.java @@ -45,11 +45,13 @@ public class SPIClassProviderReferenceElement extends SPIPackageOrClassReference ClassInheritorsSearch.search(superProvider).forEach(new Processor<PsiClass>() { @Override public boolean process(PsiClass psiClass) { - final String jvmClassName = ClassUtil.getJVMClassName(psiClass); - if (jvmClassName != null) { - result.add(LookupElementBuilder.create(psiClass, jvmClassName)); + if (!psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + final String jvmClassName = ClassUtil.getJVMClassName(psiClass); + if (jvmClassName != null) { + result.add(LookupElementBuilder.create(psiClass, jvmClassName)); + } } - return false; + return true; } }); return ArrayUtil.toObjectArray(result); diff --git a/java/java-impl/src/com/intellij/usageView/UsageContextDataflowToPanel.java b/java/java-impl/src/com/intellij/usageView/UsageContextDataflowToPanel.java index b097a8a7e307..de31282b0cca 100644 --- a/java/java-impl/src/com/intellij/usageView/UsageContextDataflowToPanel.java +++ b/java/java-impl/src/com/intellij/usageView/UsageContextDataflowToPanel.java @@ -84,7 +84,7 @@ public class UsageContextDataflowToPanel extends UsageContextPanelBase { public void updateLayoutLater(@Nullable final List<UsageInfo> infos) { if (infos == null) { removeAll(); - JComponent titleComp = new JLabel(UsageViewBundle.message("select.the.usage.to.preview")); + JComponent titleComp = new JLabel(UsageViewBundle.message("select.the.usage.to.preview"), SwingConstants.CENTER); add(titleComp, BorderLayout.CENTER); revalidate(); } diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/PackageGroupingRule.java b/java/java-impl/src/com/intellij/usages/impl/rules/PackageGroupingRule.java index 960e6180a7c7..86f57a463893 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/PackageGroupingRule.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/PackageGroupingRule.java @@ -27,6 +27,7 @@ import com.intellij.psi.JavaDirectoryService; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiPackage; +import com.intellij.usageView.UsageViewBundle; import com.intellij.usages.UsageGroup; import com.intellij.usages.UsageView; import org.jetbrains.annotations.NotNull; @@ -51,6 +52,11 @@ public class PackageGroupingRule extends DirectoryGroupingRule { return super.getGroupForFile(dir); } + @Override + public String getActionTitle() { + return UsageViewBundle.message("action.group.by.package"); + } + private class PackageGroup implements UsageGroup, TypeSafeDataProvider { private final PsiPackage myPackage; private Icon myIcon; diff --git a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java index 5ef2b8fe2ead..d8cdf4758148 100644 --- a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java @@ -270,16 +270,13 @@ public class GenericsUtil { continue; } final PsiType extendsBound = ((PsiWildcardType)substituted).getExtendsBound(); - if (Comparing.equal(TypeConversionUtil.erasure(extendsType), TypeConversionUtil.erasure(extendsBound))) { - if (extendsBound instanceof PsiClassType) { - if (acceptExtendsBound((PsiClassType)extendsBound, 0)) continue; - } else if (extendsBound instanceof PsiIntersectionType) { - for (PsiType psiType : ((PsiIntersectionType)extendsBound).getConjuncts()) { - if (psiType instanceof PsiClassType) { - if (acceptExtendsBound((PsiClassType)psiType, 0)) continue nextTypeParam; - } - } - } + if (acceptExtendsBound(extendsType, extendsBound)) { + continue nextTypeParam; + } + } + else if (substituted instanceof PsiIntersectionType) { + for (PsiType extendsBound : ((PsiIntersectionType)substituted).getConjuncts()) { + if (acceptExtendsBound(extendsType, extendsBound)) continue nextTypeParam; } } if (extendsType != null && !TypeConversionUtil.isAssignable(extendsType, substituted, allowUncheckedConversion)) { @@ -290,6 +287,22 @@ public class GenericsUtil { return null; } + public static boolean acceptExtendsBound(PsiType extendsType, PsiType extendsBound) { + if (Comparing.equal(TypeConversionUtil.erasure(extendsType), TypeConversionUtil.erasure(extendsBound))) { + if (extendsBound instanceof PsiClassType) { + if (acceptExtendsBound((PsiClassType)extendsBound, 0)) return true; + } + else if (extendsBound instanceof PsiIntersectionType) { + for (PsiType psiType : ((PsiIntersectionType)extendsBound).getConjuncts()) { + if (psiType instanceof PsiClassType) { + if (acceptExtendsBound((PsiClassType)psiType, 0)) return true; + } + } + } + } + return false; + } + private static boolean acceptExtendsBound(PsiClassType extendsBound, int depth) { PsiType[] parameters = extendsBound.getParameters(); if (parameters.length == 1) { @@ -303,6 +316,13 @@ public class GenericsUtil { if (bound instanceof PsiClassType && TypeConversionUtil.erasure(bound).equals(TypeConversionUtil.erasure(extendsBound))) { return acceptExtendsBound((PsiClassType)bound, depth + 1); } + if (bound instanceof PsiIntersectionType) { + for (PsiType extendsType : ((PsiIntersectionType)bound).getConjuncts()) { + if (acceptExtendsBound(extendsBound, extendsType)) { + return true; + } + } + } } } return false; diff --git a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java index 9bbb84e83020..f5f0bf96d95b 100644 --- a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java @@ -18,6 +18,7 @@ package com.intellij.psi; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.pom.java.LanguageLevel; +import com.intellij.psi.infos.MethodCandidateInfo; import com.intellij.psi.util.*; import com.intellij.util.Function; import com.sun.tools.javac.code.Kinds; @@ -163,6 +164,10 @@ public class PsiMethodReferenceUtil { public static boolean isAcceptable(@Nullable final PsiMethodReferenceExpression methodReferenceExpression, PsiType left) { if (methodReferenceExpression == null) return false; + final PsiElement argsList = PsiTreeUtil.getParentOfType(methodReferenceExpression, PsiExpressionList.class); + if (MethodCandidateInfo.ourOverloadGuard.currentStack().contains(argsList)) { + if (!methodReferenceExpression.isExact()) return true; + } if (left instanceof PsiIntersectionType) { for (PsiType conjunct : ((PsiIntersectionType)left).getConjuncts()) { if (isAcceptable(methodReferenceExpression, conjunct)) return true; diff --git a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java index 3a0bfddaf36f..8e4a13026514 100644 --- a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java +++ b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java @@ -18,8 +18,10 @@ package com.intellij.psi.infos; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.JavaVersionService; +import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.RecursionGuard; +import com.intellij.openapi.util.RecursionManager; import com.intellij.openapi.util.registry.Registry; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; @@ -37,6 +39,7 @@ import java.util.Map; * @author ik, dsl */ public class MethodCandidateInfo extends CandidateInfo{ + public static final RecursionGuard ourOverloadGuard = RecursionManager.createGuard("overload.guard"); public static final ThreadLocal<Map<PsiElement, Pair<PsiMethod, PsiSubstitutor>>> CURRENT_CANDIDATE = new ThreadLocal<Map<PsiElement, Pair<PsiMethod, PsiSubstitutor>>>(); @ApplicabilityLevelConstant private int myApplicabilityLevel = 0; private final PsiElement myArgumentList; @@ -95,6 +98,20 @@ public class MethodCandidateInfo extends CandidateInfo{ return myApplicabilityLevel; } + @ApplicabilityLevelConstant + public int getPertinentApplicabilityLevel() { + final PsiMethod method = getElement(); + if (method != null && method.hasTypeParameters() || myArgumentList == null || !PsiUtil.isLanguageLevel8OrHigher(myArgumentList)) { + return getApplicabilityLevel(); + } + return ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() { + @Override + public Integer compute() { + return getApplicabilityLevelInner(); + } + }); + } + public PsiSubstitutor getSiteSubstitutor() { return super.getSubstitutor(); } diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index ea5a668221af..4a99129c3d88 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -409,7 +409,8 @@ public class JavaDocInfoGenerator { private static PsiDocComment getDocComment(final PsiDocCommentOwner docOwner) { PsiElement navElement = docOwner.getNavigationElement(); if (!(navElement instanceof PsiDocCommentOwner)) { - throw new AssertionError("Wrong navElement: " + navElement + "; original = " + docOwner + " of class " + docOwner.getClass()); + LOG.info("Wrong navElement: " + navElement + "; original = " + docOwner + " of class " + docOwner.getClass()); + return null; } PsiDocComment comment = ((PsiDocCommentOwner)navElement).getDocComment(); if (comment == null) { //check for non-normalized fields diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java index 5b659f0f4631..e87fbe3cccbf 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiElementFactoryImpl.java @@ -49,7 +49,6 @@ public class PsiElementFactoryImpl extends PsiJavaParserFacadeImpl implements Ps private PsiClass myArrayClass15; private final ConcurrentHashMap<GlobalSearchScope, PsiClassType> myCachedObjectType = new ConcurrentHashMap<GlobalSearchScope, PsiClassType>(); - public PsiElementFactoryImpl(final PsiManagerEx manager) { super(manager); manager.registerRunnableToRunOnChange(new Runnable() { @@ -66,14 +65,14 @@ public class PsiElementFactoryImpl extends PsiJavaParserFacadeImpl implements Ps if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_5)) { if (myArrayClass == null) { @NonNls final String body = "public class __Array__{\n public final int length;\n public Object clone() {}\n}"; - myArrayClass = createClassFromText(body, null).getInnerClasses()[0]; + myArrayClass = ((PsiExtensibleClass)createClassFromText(body, null)).getOwnInnerClasses().get(0); } return myArrayClass; } else { if (myArrayClass15 == null) { @NonNls final String body = "public class __Array__<T>{\n public final int length;\n public T[] clone() {}\n}"; - myArrayClass15 = createClassFromText(body, null).getInnerClasses()[0]; + myArrayClass15 = ((PsiExtensibleClass)createClassFromText(body, null)).getOwnInnerClasses().get(0); } return myArrayClass15; } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java index 365c5e66d6c1..48c9d63aa059 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java @@ -345,7 +345,6 @@ public class PsiImplUtil { if (annotationType instanceof PsiClass) { return findApplicableTarget((PsiClass)annotationType, types); } - if (annotationType == null) return null; } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ProcessCandidateParameterTypeInferencePolicy.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ProcessCandidateParameterTypeInferencePolicy.java index e88fca2a3025..96b6f4b19271 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ProcessCandidateParameterTypeInferencePolicy.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ProcessCandidateParameterTypeInferencePolicy.java @@ -109,10 +109,9 @@ public class ProcessCandidateParameterTypeInferencePolicy extends DefaultParamet return substitutor.substitute(finalParameter.getType()); } }); - PsiResolveHelperImpl resolveHelper = (PsiResolveHelperImpl)JavaPsiFacade.getInstance(method.getProject()).getResolveHelper(); final LanguageLevel languageLevel = PsiUtil.getLanguageLevel(finalParameter); final Pair<PsiType, ConstraintType> constraint = - ((PsiOldInferenceHelper)resolveHelper.getInferenceHelper(languageLevel)).getSubstitutionForTypeParameterConstraint(typeParameter, innerReturnType, type, false, languageLevel); + new PsiOldInferenceHelper(element.getManager()).getSubstitutionForTypeParameterConstraint(typeParameter, innerReturnType, type, false, languageLevel); if (constraint != null) return constraint; } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java index 27a949b84495..76fc67ddce68 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java @@ -28,7 +28,6 @@ import com.intellij.util.ArrayUtilRt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.Serializable; import java.util.*; /** @@ -70,16 +69,15 @@ public class InferenceSession { } public InferenceSession(PsiTypeParameter[] typeParams, - PsiParameter[] parameters, - PsiExpression[] args, PsiSubstitutor siteSubstitutor, - PsiElement parent, PsiManager manager) { myManager = manager; mySiteSubstitutor = siteSubstitutor; initBounds(typeParams); + } + public void initExpressionConstraints(PsiParameter[] parameters, PsiExpression[] args, PsiElement parent) { final Pair<PsiMethod, PsiCallExpression> pair = getPair(parent); if (parameters.length > 0) { for (int i = 0; i < args.length; i++) { @@ -274,32 +272,7 @@ public class InferenceSession { if (!PsiType.VOID.equals(returnType) && returnType != null) { PsiType targetType = PsiTypesUtil.getExpectedTypeByParent(context); if (targetType == null) { - final PsiElement parent = PsiUtil.skipParenthesizedExprUp(context.getParent()); - if (parent instanceof PsiExpressionList) { - final PsiElement gParent = parent.getParent(); - if (gParent instanceof PsiCallExpression) { - final PsiExpressionList argumentList = ((PsiCallExpression)gParent).getArgumentList(); - if (argumentList != null) { - final Pair<PsiMethod, PsiSubstitutor> pair = MethodCandidateInfo.getCurrentMethod(argumentList); - final JavaResolveResult resolveResult = pair == null ? ((PsiCallExpression)gParent).resolveMethodGenerics() : null; - final PsiElement parentMethod = pair != null ? pair.first : resolveResult.getElement(); - if (parentMethod instanceof PsiMethod) { - final PsiParameter[] parameters = ((PsiMethod)parentMethod).getParameterList().getParameters(); - PsiElement arg = context; - while (arg.getParent() instanceof PsiParenthesizedExpression) { - arg = parent.getParent(); - } - final PsiExpression[] args = argumentList.getExpressions(); - targetType = getParameterType(parameters, args, ArrayUtilRt.find(args, arg), pair != null ? pair.second : resolveResult.getSubstitutor()); - } - } - } - } else if (parent instanceof PsiConditionalExpression) { - targetType = PsiTypesUtil.getExpectedTypeByParent((PsiExpression)parent); - } - else if (parent instanceof PsiLambdaExpression) { - targetType = LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression)parent).getFunctionalInterfaceType()); - } + targetType = getTargetType(context); } if (targetType != null) { myConstraints.add(new TypeCompatibilityConstraint(GenericsUtil.eliminateWildcards(targetType, false), PsiImplUtil.normalizeWildcardTypeByPosition(returnType, context))); @@ -308,6 +281,43 @@ public class InferenceSession { } } + private static PsiType getTargetType(PsiExpression context) { + final PsiElement parent = PsiUtil.skipParenthesizedExprUp(context.getParent()); + if (parent instanceof PsiExpressionList) { + final PsiElement gParent = parent.getParent(); + if (gParent instanceof PsiCallExpression) { + final PsiExpressionList argumentList = ((PsiCallExpression)gParent).getArgumentList(); + if (argumentList != null) { + final Pair<PsiMethod, PsiSubstitutor> pair = MethodCandidateInfo.getCurrentMethod(argumentList); + final JavaResolveResult resolveResult = pair == null ? ((PsiCallExpression)gParent).resolveMethodGenerics() : null; + final PsiElement parentMethod = pair != null ? pair.first : resolveResult.getElement(); + if (parentMethod instanceof PsiMethod) { + final PsiParameter[] parameters = ((PsiMethod)parentMethod).getParameterList().getParameters(); + if (parameters.length == 0) return null; + PsiElement arg = context; + while (arg.getParent() instanceof PsiParenthesizedExpression) { + arg = arg.getParent(); + } + final PsiExpression[] args = argumentList.getExpressions(); + final int i = ArrayUtilRt.find(args, arg); + if (i < 0) return null; + return getParameterType(parameters, args, i, pair != null ? pair.second : resolveResult.getSubstitutor()); + } + } + } + } else if (parent instanceof PsiConditionalExpression) { + PsiType targetType = PsiTypesUtil.getExpectedTypeByParent((PsiExpression)parent); + if (targetType == null) { + targetType = getTargetType((PsiExpression)parent); + } + return targetType; + } + else if (parent instanceof PsiLambdaExpression) { + return LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression)parent).getFunctionalInterfaceType()); + } + return null; + } + public InferenceVariable getInferenceVariable(PsiType psiType) { return getInferenceVariable(psiType, true); } @@ -419,16 +429,17 @@ public class InferenceSession { inferenceVariable.setInstantiation(null); continue; } - PsiType bound = null; - for (PsiType eqBound : eqBounds) { - if (eqBound == null) continue; - if (bound != null && !isProperType(eqBound)) continue; - bound = acceptBoundsWithRecursiveDependencies(typeParameter, eqBound, substitutor); + if (eqBounds.size() > 1) { + for (Iterator<PsiType> iterator = eqBounds.iterator(); iterator.hasNext(); ) { + PsiType eqBound = iterator.next(); + if (PsiUtil.resolveClassInType(eqBound) == typeParameter) { + iterator.remove(); + } + } + if (eqBounds.size() > 1) continue; } + PsiType bound = eqBounds.isEmpty() ? null : acceptBoundsWithRecursiveDependencies(typeParameter, eqBounds.get(0), substitutor); if (bound != null) { - if (bound instanceof PsiCapturedWildcardType && eqBounds.size() > 1) { - continue; - } inferenceVariable.setInstantiation(bound); } else { PsiType lub = null; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiGraphInferenceHelper.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiGraphInferenceHelper.java index 84c8b7cef80f..ebec24e79108 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiGraphInferenceHelper.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiGraphInferenceHelper.java @@ -38,8 +38,8 @@ public class PsiGraphInferenceHelper implements PsiInferenceHelper { @NotNull PsiSubstitutor partialSubstitutor, @Nullable PsiElement parent, @NotNull ParameterTypeInferencePolicy policy) { - final InferenceSession inferenceSession = - new InferenceSession(new PsiTypeParameter[]{typeParameter}, parameters, arguments, partialSubstitutor, parent, myManager); + final InferenceSession inferenceSession = new InferenceSession(new PsiTypeParameter[]{typeParameter}, partialSubstitutor, myManager); + inferenceSession.initExpressionConstraints(parameters, arguments, parent); return inferenceSession.infer(parameters, arguments, parent).substitute(typeParameter); } @@ -53,8 +53,8 @@ public class PsiGraphInferenceHelper implements PsiInferenceHelper { @NotNull ParameterTypeInferencePolicy policy, @NotNull LanguageLevel languageLevel) { if (typeParameters.length == 0) return partialSubstitutor; - final InferenceSession inferenceSession = - new InferenceSession(typeParameters, parameters, arguments, partialSubstitutor, parent, myManager); + final InferenceSession inferenceSession = new InferenceSession(typeParameters, partialSubstitutor, myManager); + inferenceSession.initExpressionConstraints(parameters, arguments, parent); return inferenceSession.infer(parameters, arguments, parent); } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java index 7ef2a7250030..830fad91d650 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java @@ -83,11 +83,9 @@ public class ExpressionCompatibilityConstraint extends InputOutputConstraintForm InferenceSession callSession = null; if (method != null && !method.isConstructor()) { returnType = method.getReturnType(); - final PsiParameter[] parameters = method.getParameterList().getParameters(); if (returnType != null) { - callSession = new InferenceSession(method.getTypeParameters(), parameters, - argumentList.getExpressions(), - PsiSubstitutor.EMPTY, null, myExpression.getManager()); + callSession = new InferenceSession(method.getTypeParameters(), + PsiSubstitutor.EMPTY, myExpression.getManager()); } } else if (myExpression instanceof PsiNewExpression) { //default constructor @@ -97,9 +95,7 @@ public class ExpressionCompatibilityConstraint extends InputOutputConstraintForm if (psiClass instanceof PsiClass) { returnType = JavaPsiFacade.getElementFactory(argumentList.getProject()).createType((PsiClass)psiClass, PsiSubstitutor.EMPTY); callSession = new InferenceSession(((PsiClass)psiClass).getTypeParameters(), - PsiParameter.EMPTY_ARRAY, - argumentList.getExpressions(), - PsiSubstitutor.EMPTY, null, myExpression.getManager()); + PsiSubstitutor.EMPTY, myExpression.getManager()); } } } @@ -118,7 +114,9 @@ public class ExpressionCompatibilityConstraint extends InputOutputConstraintForm else { returnType = callSubstitutor.substitute(returnType); } - constraints.add(new TypeCompatibilityConstraint(GenericsUtil.eliminateWildcards(myT, false), returnType)); + if (!TypeConversionUtil.isAssignable(myT, returnType)) { + constraints.add(new TypeCompatibilityConstraint(GenericsUtil.eliminateWildcards(myT, false), returnType)); + } } } return true; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/SubtypingConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/SubtypingConstraint.java index cfda8a0f0e36..d519c7470cee 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/SubtypingConstraint.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/SubtypingConstraint.java @@ -114,6 +114,11 @@ public class SubtypingConstraint implements ConstraintFormula { if (tBound.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { return true; } + + if (myS instanceof PsiCapturedWildcardType) { + myS = ((PsiCapturedWildcardType)myS).getWildcard(); + } + if (myS instanceof PsiWildcardType) { final PsiType sBound = ((PsiWildcardType)myS).getBound(); if (sBound != null && ((PsiWildcardType)myS).isExtends()) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java index eb4d501cdad0..9d0d23a10540 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java @@ -84,25 +84,41 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase } else if (isConstructor()) { methods = containingClass.getConstructors(); - if (methods.length == 0) { //default constructor - return containingClass; - } } if (methods != null) { PsiMethod psiMethod = null; - for (PsiMethod method : methods) { - if (PsiUtil.isAccessible(method, this, null)) { - if (psiMethod != null) return null; - psiMethod = method; + if (methods.length > 0) { + for (PsiMethod method : methods) { + if (PsiUtil.isAccessible(method, this, null)) { + if (psiMethod != null) return null; + psiMethod = method; + } + } + if (psiMethod == null) return null; + if (psiMethod.isVarArgs()) return null; + if (psiMethod.getTypeParameters().length > 0) { + final PsiReferenceParameterList parameterList = getParameterList(); + return parameterList != null && parameterList.getTypeParameterElements().length > 0 ? psiMethod : null; } } - if (psiMethod == null) return null; - if (psiMethod.isVarArgs()) return null; - if (psiMethod.getTypeParameters().length > 0) { - final PsiReferenceParameterList parameterList = getParameterList(); - return parameterList != null && parameterList.getTypeParameterElements().length > 0 ? psiMethod : null; + if (containingClass.hasTypeParameters()) { + final PsiElement qualifier = getQualifier(); + if (qualifier instanceof PsiTypeElement) { + final PsiJavaCodeReferenceElement referenceElement = ((PsiTypeElement)qualifier).getInnermostComponentReferenceElement(); + if (referenceElement != null) { + final PsiReferenceParameterList parameterList = referenceElement.getParameterList(); + if (parameterList == null || parameterList.getTypeParameterElements().length == 0) { + return null; + } + } + } else if (qualifier instanceof PsiReferenceExpression) { + final PsiReferenceParameterList parameterList = ((PsiReferenceExpression)qualifier).getParameterList(); + if (parameterList == null || parameterList.getTypeParameterElements().length == 0) { + return null; + } + } } - return psiMethod; + return psiMethod == null ? containingClass : psiMethod; } } return null; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java index 639574933136..7f4a7dd1dd8b 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java @@ -509,16 +509,13 @@ public class PsiReferenceExpressionImpl extends PsiReferenceExpressionBase imple PsiScopesUtil.resolveAndWalk(filterProcessor, this, null, true); } - private static boolean seemsScrambled(PsiClass element) { - if (!(element instanceof PsiCompiledElement)) { + public static boolean seemsScrambled(PsiClass aClass) { + if (!(aClass instanceof PsiCompiledElement)) { return false; } - final String qualifiedName = element.getQualifiedName(); - return qualifiedName != null && - qualifiedName.length() <= 2 && - !qualifiedName.isEmpty() && - Character.isLowerCase(qualifiedName.charAt(0)); + final String name = aClass.getName(); + return name != null && !name.isEmpty() && name.length() <= 2; } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java b/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java index 084ad32c5d56..224185117c4f 100644 --- a/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java +++ b/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java @@ -394,7 +394,7 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{ for (Iterator<CandidateInfo> iterator = conflicts.iterator(); iterator.hasNext();) { ProgressManager.checkCanceled(); CandidateInfo info = iterator.next(); - final int level = preferVarargs(info); + final int level = preferVarargs((MethodCandidateInfo)info); if (level < maxApplicabilityLevel) { iterator.remove(); } @@ -404,10 +404,10 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{ return maxApplicabilityLevel; } - private static int preferVarargs(CandidateInfo info) { - final int level = ((MethodCandidateInfo)info).getApplicabilityLevel(); + private static int preferVarargs(MethodCandidateInfo info) { + final int level = info.getPertinentApplicabilityLevel(); if (level == MethodCandidateInfo.ApplicabilityLevel.FIXED_ARITY) { - final PsiMethod psiMethod = (PsiMethod)info.getElement(); + final PsiMethod psiMethod = info.getElement(); if (psiMethod != null && psiMethod.isVarArgs() && JavaVersionService.getInstance().isAtLeast(psiMethod, JavaSdkVersion.JDK_1_7)) { return level + 1; } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA57492.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA57492.java index 03a45cf5b5e8..b7829da2670c 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA57492.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA57492.java @@ -3,7 +3,7 @@ abstract class A<T>{ <S extends Number & Comparable<? extends Number>> void baz(A<S> a){} void bar(A<Long> x, A<Integer> y){ - <error descr="Inferred type 'capture<? extends java.lang.Number & java.lang.Comparable<? extends java.lang.Comparable<?>>>' for type parameter 'S' is not within its bound; should implement 'java.lang.Comparable<? extends java.lang.Number>'">baz(foo(x, y))</error>; + baz<error descr="'baz(A<java.lang.Number & java.lang.Comparable<? extends java.lang.Number>>)' in 'A' cannot be applied to '(A<capture<? extends java.lang.Number & java.lang.Comparable<? extends java.lang.Comparable<?>>>>)'">(foo(x, y))</error>; } } @@ -12,6 +12,6 @@ abstract class A1<T>{ <T extends Number & Comparable<?>, S extends Number & Comparable<? extends T>> void baz(A1<S> a){} void bar(A1<Long> x, A1<Integer> y){ - <error descr="Inferred type 'capture<? extends java.lang.Number & java.lang.Comparable<? extends java.lang.Comparable<?>>>' for type parameter 'S' is not within its bound; should implement 'java.lang.Comparable<? extends java.lang.Number & java.lang.Comparable<?>>'">baz(foo(x, y))</error>; + baz<error descr="'baz(A1<java.lang.Number & java.lang.Comparable<? extends java.lang.Number & java.lang.Comparable<?>>>)' in 'A1' cannot be applied to '(A1<capture<? extends java.lang.Number & java.lang.Comparable<? extends java.lang.Comparable<?>>>>)'">(foo(x, y))</error>; } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA94011.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA94011.java index 0dd027c949c0..cf11bfd194fb 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA94011.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA94011.java @@ -10,7 +10,7 @@ class Test { public void test(Set<MyConsumer> set) { @SuppressWarnings("unchecked") - <error descr="Incompatible types. Found: 'java.util.Map<Test.Parent,Test.MyConsumer>', required: 'java.util.Map<Test.Parent,Test.MyConsumer<Test.Parent>>'">Map<Parent, MyConsumer<Parent>> map = create(set);</error> + Map<Parent, MyConsumer<Parent>> map = <error descr="Inferred type 'T' for type parameter 'T' is not within its bound; should implement 'Test.Consumer<Test.Parent>'">create(set)</error>; } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IntersectionTypes.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IntersectionTypes.java index 48bb90c3777e..cba83dc2b2ad 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IntersectionTypes.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IntersectionTypes.java @@ -128,7 +128,7 @@ class Maps { class Client { void f(Date d) { //this call should be OK - <warning descr="Unchecked generics array creation for varargs parameter">Maps.asMap</warning>(Maps.entry(fieldName(), "Test"), + Maps.asMap(Maps.entry(fieldName(), "Test"), Maps.entry(fieldName(), 1), Maps.entry(fieldName(), d)); } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/InferenceFromReturnType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/InferenceFromReturnType.java index 69fea2d6a671..5f087e16ed3f 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/InferenceFromReturnType.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/InferenceFromReturnType.java @@ -17,11 +17,11 @@ class MyTestDefaultConstructor { } private static void <warning descr="Private method 'foo(MyTestDefaultConstructor.I1)' is never used">foo</warning>(I1 i) {System.out.println(i);} - private static void foo(I2 i) {System.out.println(i);} + private static void <warning descr="Private method 'foo(MyTestDefaultConstructor.I2)' is never used">foo</warning>(I2 i) {System.out.println(i);} private static void <warning descr="Private method 'foo(MyTestDefaultConstructor.I3)' is never used">foo</warning>(I3 i) {System.out.println(i);} static { - foo(Foo::new); + foo<error descr="Cannot resolve method 'foo(<method reference>)'">(Foo::new)</error>; } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/MethodTypeParamsInference.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/MethodTypeParamsInference.java index 11c284f59c31..06e45209cf81 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/MethodTypeParamsInference.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/MethodTypeParamsInference.java @@ -20,7 +20,7 @@ class MyTest { static void foo(I3 i) {} static { - foo(MyTest::m); + foo<error descr="Cannot resolve method 'foo(<method reference>)'">(MyTest::m)</error>; foo<error descr="Ambiguous method call: both 'MyTest.foo(I1)' and 'MyTest.foo(I2)' match">(MyTest::m1)</error>; } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/RawQualifier.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/RawQualifier.java index ee1ad6c9cbc5..67bbac28af1e 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/RawQualifier.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/RawQualifier.java @@ -39,6 +39,6 @@ class MyTest1 { static void foo(I3 i) {} static { - foo(Foo::new); + foo<error descr="Cannot resolve method 'foo(<method reference>)'">(Foo::new)</error>; } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/ReturnTypeSpecific.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/ReturnTypeSpecific.java index 249114c65b88..93ca7899c7e5 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/ReturnTypeSpecific.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/ReturnTypeSpecific.java @@ -62,12 +62,12 @@ class MyTest1 { System.out.println(i); } - private static void m(I3 i) { + private static void <warning descr="Private method 'm(MyTest1.I3)' is never used">m</warning>(I3 i) { System.out.println(i); } public static void main(String[] args) { - m(Foo::new); + m<error descr="Ambiguous method call: both 'MyTest1.m(I2)' and 'MyTest1.m(I3)' match">(Foo::new)</error>; } } class MyTest2 { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/StaticProblems.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/StaticProblems.java index edaa26bbab7b..194eaace18db 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/StaticProblems.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/StaticProblems.java @@ -115,10 +115,10 @@ class MyTest2 { static void call3(I1 s) {} static void call3(I2 s) {} static { - call3(<error descr="Non-static method cannot be referenced from a static context">MyTest2::m1</error>); - call3(MyTest2::m2); - call3(MyTest2::m3); - call3(<error descr="Non-static method cannot be referenced from a static context">MyTest2::m4</error>); + call3<error descr="Cannot resolve method 'call3(<method reference>)'">(MyTest2::m1)</error>; + call3<error descr="Cannot resolve method 'call3(<method reference>)'">(MyTest2::m2)</error>; + call3<error descr="Cannot resolve method 'call3(<method reference>)'">(MyTest2::m3)</error>; + call3<error descr="Cannot resolve method 'call3(<method reference>)'">(MyTest2::m4)</error>; } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createConstructorMatchingSuper/beforeInAnonymous.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createConstructorMatchingSuper/beforeInAnonymous.java new file mode 100644 index 000000000000..9d9e88f5bc56 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createConstructorMatchingSuper/beforeInAnonymous.java @@ -0,0 +1,13 @@ +// "Create constructor matching super" "false" +public class Test { + private Test() {} +} + +class Foo { + { + new Test() { + Te<caret>st() { + } + }; + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/PrimitiveCastMayChangeValue.java b/java/java-tests/testData/inspection/dataFlow/fixture/PrimitiveCastMayChangeValue.java new file mode 100644 index 000000000000..652f0dccc9d6 --- /dev/null +++ b/java/java-tests/testData/inspection/dataFlow/fixture/PrimitiveCastMayChangeValue.java @@ -0,0 +1,15 @@ + +public class BrokenAlignment { + private static void foo(long value) { + if (value == (byte)value) { + System.out.println("1"); + } else if (value == (short)value) { + System.out.println("2"); + } else if (value == (int)value) { + System.out.println("3"); + } else { + System.out.println("4"); + } + } + +}
\ No newline at end of file diff --git a/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags.java b/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags.java index 319b8eb82514..93e69f10db5c 100644 --- a/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags.java +++ b/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags.java @@ -1,6 +1,13 @@ import java.util.*; public class CollectionTest { + /** + * Normal JavaDoc, can + * be + * formatted. + * @param args + * Arguments. + */ public static void main(String[] args) { int size; HashSet collection = new HashSet(); @@ -22,4 +29,34 @@ public class CollectionTest { System.out.print(iterator.next() + " "); } } + + // @formatter:off + /** + * And please don't touch this: + * @param x + * These are my nice comments. + * @param y + * And yet another one. + */ + public void doSomething(String x, String y) { + } + // @formatter:on + + /** + * It's OK to format this comment. + * @param z + * Parameter Z. + */ + public void doSomethingElse(String z) {} + + // @formatter:off + /** + * This comment must be preserved too. + * @param i + * Parameter I. + * @param j + * Parameter J. + */ + public void evenMore(int i, int j) {} + // @formatter:on } diff --git a/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags_after.java b/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags_after.java index 8e1abcb09d02..01233b3ac32e 100644 --- a/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags_after.java +++ b/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags_after.java @@ -1,6 +1,13 @@ import java.util.*; public class CollectionTest { + /** + * Normal JavaDoc, can + * be + * formatted. + * + * @param args Arguments. + */ public static void main(String[] args) { int size; HashSet collection = new HashSet(); @@ -22,4 +29,35 @@ public class CollectionTest { System.out.print(iterator.next() + " "); } } + + // @formatter:off + /** + * And please don't touch this: + * @param x + * These are my nice comments. + * @param y + * And yet another one. + */ + public void doSomething(String x, String y) { + } + // @formatter:on + + /** + * It's OK to format this comment. + * + * @param z Parameter Z. + */ + public void doSomethingElse(String z) { + } + + // @formatter:off + /** + * This comment must be preserved too. + * @param i + * Parameter I. + * @param j + * Parameter J. + */ + public void evenMore(int i, int j) {} + // @formatter:on } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java index 39ff89aa0bde..159759f8c97f 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java @@ -71,7 +71,7 @@ public class GenericsHighlighting8Test extends LightDaemonAnalyzerTestCase { public void testInferenceWithBounds() { doTest(); } - public void testInferenceWithSuperBounds() { + public void _testInferenceWithSuperBounds() { doTest(); } public void testInferenceWithUpperBoundPromotion() { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy index 14486f7b4cad..b2a4447dbb73 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy @@ -20,23 +20,17 @@ import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase public class AddImportActionTest extends LightCodeInsightFixtureTestCase { - @Override - protected void tearDown() { - IdeaTestUtil.setModuleLanguageLevel(myModule, LanguageLevel.HIGHEST) - super.tearDown() - } - public void testMap15() { - IdeaTestUtil.setModuleLanguageLevel(myModule, LanguageLevel.JDK_1_5) - myFixture.configureByText 'a.java', '''\ + IdeaTestUtil.withLevel(myModule, LanguageLevel.JDK_1_5, { + myFixture.configureByText 'a.java', '''\ public class Foo { void foo() { Ma<caret>p<> l; } } ''' - importClass() - myFixture.checkResult '''import java.util.Map; + importClass() + myFixture.checkResult '''import java.util.Map; public class Foo { void foo() { @@ -44,6 +38,7 @@ public class Foo { } } ''' + }) } public void testMapLatestLanguageLevel() { @@ -118,7 +113,6 @@ public class Foo extends goo.Super { public void foo(Log<caret> log) {} } ''' - } public void testAnnotatedImport() { @@ -167,9 +161,9 @@ class Test { Collection<caret> c; } ''' - } + } - public void testUnresolvedAnnotatedQualifiedImport() { + public void testUnresolvedAnnotatedImport() { myFixture.configureByText 'a.java', ''' class Test { @Nullable Collection<caret> c; diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java index 02dcfc0072b3..30993c07b4ac 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java @@ -122,6 +122,7 @@ public class DataFlowInspectionTest extends LightCodeInsightFixtureTestCase { } public void testPreserveNullableOnUncheckedCast() throws Throwable { doTest(); } + public void testPrimitiveCastMayChangeValue() throws Throwable { doTest(); } public void testPassingNullableIntoVararg() throws Throwable { doTest(); } public void testEqualsImpliesNotNull() throws Throwable { doTest(); } diff --git a/java/java-tests/testSrc/com/intellij/find/FindManagerTest.java b/java/java-tests/testSrc/com/intellij/find/FindManagerTest.java index a7c477a52541..0110fdcf5122 100644 --- a/java/java-tests/testSrc/com/intellij/find/FindManagerTest.java +++ b/java/java-tests/testSrc/com/intellij/find/FindManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,8 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.openapi.util.ProperTextRange; +import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; @@ -51,22 +53,31 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -/* - * @author: MYakovlev - * Date: Oct 17, 2002 - * Time: 7:53:31 PM +/** + * @author MYakovlev + * @since Oct 17, 2002 */ -@SuppressWarnings({"HardCodedStringLiteral"}) public class FindManagerTest extends DaemonAnalyzerTestCase { - protected VirtualFile[] mySourceDirs; + private FindManager myFindManager; + private VirtualFile[] mySourceDirs; + + @Override + protected void setUp() throws Exception { + super.setUp(); + myFindManager = FindManager.getInstance(myProject); + } - public void testFindString() throws Exception{ - FindManager findManager = FindManager.getInstance(myProject); + @Override + protected void tearDown() throws Exception { + myFindManager = null; + super.tearDown(); + } + public void testFindString() { FindModel findModel = FindManagerTestUtils.configureFindModel("done"); String text = "public static class MyClass{\n/*done*/\npublic static void main(){}}"; - FindResult findResult = findManager.findString(text, 0, findModel); + FindResult findResult = myFindManager.findString(text, 0, findModel); assertTrue(findResult.isStringFound()); findModel = new FindModel(); @@ -77,7 +88,7 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setMultipleFiles(false); findModel.setProjectScope(true); - findResult = findManager.findString(text, 40, findModel); + findResult = myFindManager.findString(text, 40, findModel); assertFalse(findResult.isStringFound()); findModel = new FindModel(); @@ -89,7 +100,7 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setProjectScope(true); findModel.setForward(false); - findResult = findManager.findString(text, 40, findModel); + findResult = myFindManager.findString(text, 40, findModel); assertTrue(findResult.isStringFound()); findModel = new FindModel(); @@ -100,7 +111,7 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setMultipleFiles(false); findModel.setProjectScope(true); - findResult = findManager.findString(text, 0, findModel); + findResult = myFindManager.findString(text, 0, findModel); assertTrue(findResult.isStringFound()); findModel = new FindModel(); @@ -112,7 +123,7 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setProjectScope(true); final FindResult[] findResultArr = new FindResult[1]; - findInNewThread(findModel, findManager, text, 0, findResultArr); + findInNewThread(findModel, myFindManager, text, 0, findResultArr); new WaitFor(30 *1000){ @Override protected boolean condition() { @@ -139,9 +150,9 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { return findThread; } - public void testFindUsages() throws Exception{ + public void testFindUsages() { initProject("findManager", "src", "src1"); - final String projectDir = (PathManagerEx.getTestDataPath() + "/find/findManager").replace('/', File.separatorChar); + String projectDir = FileUtil.toSystemDependentName(PathManagerEx.getTestDataPath() + "/find/findManager"); FindModel findModel = new FindModel(); findModel.setStringToFind("done"); @@ -154,7 +165,6 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setWithSubdirectories(true); checkFindUsages(12, findModel); - //findModel = new FindModel(); findModel.setFromCursor(false); findModel.setGlobal(true); findModel.setMultipleFiles(true); @@ -165,13 +175,9 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setWholeWordsOnly(true); checkFindUsages(5, findModel); -// findModel.setForward(false); -// findModel.setCaseSensitive(); - - } - private void checkFindUsages(int expectedResults, FindModel findModel) throws Exception{ + private void checkFindUsages(int expectedResults, FindModel findModel) { Collection<UsageInfo> usages = findUsages(findModel); assertEquals(expectedResults, usages.size()); } @@ -184,9 +190,8 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { return result; } - public void testFindWholeWordsInProperties() throws Exception { + public void testFindWholeWordsInProperties() { initProject("findInPath", "src"); - searchProperty("xx.yy"); searchProperty(".yy"); searchProperty("xx."); @@ -208,22 +213,31 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { if (!(usages.get(0).getFile() instanceof PsiJavaFile)) { Collections.swap(usages, 0, 1); } - PsiElement element = usages.get(0).getElement(); - //assertTrue(element instanceof PsiJavaFile); - PsiElement refElement = element.findElementAt(usages.get(0).getRangeInElement().getStartOffset()).getParent(); + + PsiElement refElement = getParentFromUsage(usages.get(0)); assertTrue(refElement instanceof PsiLiteralExpression); assertEquals("xx.yy", ((PsiLiteralExpression)refElement).getValue()); VirtualFile file = mySourceDirs[0].findFileByRelativePath("x/dd.properties"); + assertNotNull(file); PropertiesFile propertiesFile = (PropertiesFile)PsiManager.getInstance(myProject).findFile(file); - element = usages.get(1).getElement(); - //assertTrue(element instanceof PropertiesFile); - refElement = element.findElementAt(usages.get(1).getRangeInElement().getStartOffset()).getParent(); + assertNotNull(propertiesFile); + refElement = getParentFromUsage(usages.get(1)); assertTrue(refElement instanceof IProperty); assertSame(propertiesFile.findPropertyByKey("xx.yy"), refElement); } - public void testFindInClassHierarchy() throws Exception { + private static PsiElement getParentFromUsage(UsageInfo usage) { + ProperTextRange range = usage.getRangeInElement(); + assertNotNull(range); + PsiElement element = usage.getElement(); + assertNotNull(element); + PsiElement elementAt = element.findElementAt(range.getStartOffset()); + assertNotNull(elementAt); + return elementAt.getParent(); + } + + public void testFindInClassHierarchy() { initProject("findInClassHierarchy", "src"); FindModel findModel = new FindModel(); @@ -244,7 +258,7 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { public void testDollars() throws Exception { createFile(myModule, "A.java", "foo foo$ $foo"); createFile(myModule, "A.txt", "foo foo$ $foo"); - + FindModel findModel = new FindModel(); findModel.setWholeWordsOnly(true); findModel.setFromCursor(false); @@ -260,15 +274,12 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setStringToFind("$foo"); assertSize(2, findUsages(findModel)); - } - public void testReplaceRegexp() throws Throwable { - FindManager findManager = FindManager.getInstance(myProject); - + public void testReplaceRegexp() { FindModel findModel = new FindModel(); - findModel.setStringToFind("bug(?=here)"); - findModel.setStringToReplace("x$0y"); + findModel.setStringToFind("bug_(?=here)"); + findModel.setStringToReplace("x_$0t"); findModel.setWholeWordsOnly(false); findModel.setFromCursor(false); findModel.setGlobal(true); @@ -277,21 +288,19 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setRegularExpressions(true); findModel.setPromptOnReplace(false); - findManager.setFindNextModel(null); - findManager.getFindInFileModel().copyFrom(findModel); + myFindManager.setFindNextModel(null); + myFindManager.getFindInFileModel().copyFrom(findModel); - String text = "bughere\n" + "bughere"; + String text = "bug_here\nbug_here"; configureByText(FileTypes.PLAIN_TEXT, text); - boolean succ = FindUtil.replace(getProject(), getEditor(), 0, findModel); - assertTrue(succ); + assertTrue(FindUtil.replace(getProject(), getEditor(), 0, findModel)); - assertEquals("xbugyhere\n" + "xbugyhere", getEditor().getDocument().getText()); + assertEquals("x_bug_there\nx_bug_there", getEditor().getDocument().getText()); } - public void testReplaceRegexp1() throws Throwable { - FindManager findManager = FindManager.getInstance(myProject); + public void testReplaceRegexp1() { FindModel findModel = new FindModel(); - findModel.setStringToFind("bug(?=here)"); + findModel.setStringToFind("bug_(?=here)"); findModel.setStringToReplace("$0"); findModel.setWholeWordsOnly(false); findModel.setFromCursor(false); @@ -301,20 +310,17 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setRegularExpressions(true); findModel.setPromptOnReplace(false); - findManager.setFindNextModel(null); - findManager.getFindInFileModel().copyFrom(findModel); + myFindManager.setFindNextModel(null); + myFindManager.getFindInFileModel().copyFrom(findModel); - String text = "bughere\n" + "bughere"; + String text = "bug_here\nbug_here"; configureByText(FileTypes.PLAIN_TEXT, text); - boolean succ = FindUtil.replace(getProject(), getEditor(), 0, findModel); - assertTrue(succ); + assertTrue(FindUtil.replace(getProject(), getEditor(), 0, findModel)); assertEquals(text, getEditor().getDocument().getText()); } - public void testReplaceRegexpWithNewLine() throws Throwable { - FindManager findManager = FindManager.getInstance(myProject); - + public void testReplaceRegexpWithNewLine() { FindModel findModel = new FindModel(); findModel.setStringToFind("xxx"); findModel.setStringToReplace("xxx\\n"); @@ -326,18 +332,17 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setRegularExpressions(true); findModel.setPromptOnReplace(false); - findManager.setFindNextModel(null); - findManager.getFindInFileModel().copyFrom(findModel); + myFindManager.setFindNextModel(null); + myFindManager.getFindInFileModel().copyFrom(findModel); String text = "xxx"; configureByText(FileTypes.PLAIN_TEXT, text); - boolean succ = FindUtil.replace(getProject(), getEditor(), 0, findModel); - assertTrue(succ); + assertTrue(FindUtil.replace(getProject(), getEditor(), 0, findModel)); assertEquals(text+"\n", getEditor().getDocument().getText()); } - private void initProject(String folderName, final String... sourceDirs) throws Exception{ + private void initProject(String folderName, final String... sourceDirs) { final String testDir = JavaTestUtil.getJavaTestDataPath() + "/find/" + folderName; ApplicationManager.getApplication().runWriteAction(new Runnable(){ @Override @@ -345,11 +350,11 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { try{ mySourceDirs = new VirtualFile[sourceDirs.length]; for (int i = 0; i < sourceDirs.length; i++){ - String sourceDir = sourceDirs[i]; - mySourceDirs[i] = LocalFileSystem.getInstance().refreshAndFindFileByPath(new File(testDir + File.separatorChar + sourceDir).getCanonicalPath().replace(File.separatorChar, '/')); + String sourcePath = testDir + "/" + sourceDirs[i]; + mySourceDirs[i] = LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtil.toSystemIndependentName(sourcePath)); } - VirtualFile projectDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(new File(testDir).getCanonicalPath().replace(File.separatorChar, '/')); + VirtualFile projectDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtil.toSystemIndependentName(testDir)); Sdk jdk = IdeaTestUtil.getMockJdk17(); PsiTestUtil.removeAllRoots(myModule, jdk); PsiTestUtil.addContentRoot(myModule, projectDir); @@ -364,12 +369,10 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { }); } - public void testReplaceAll() throws Throwable { - FindManager findManager = FindManager.getInstance(myProject); - + public void testReplaceAll() throws FindManager.MalformedReplacementStringException { FindModel findModel = new FindModel(); String toFind = "xxx"; - String toReplace = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; + @SuppressWarnings("SpellCheckingInspection") String toReplace = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; findModel.setStringToFind(toFind); findModel.setStringToReplace(toReplace); findModel.setWholeWordsOnly(true); @@ -380,13 +383,14 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setRegularExpressions(false); findModel.setPromptOnReplace(false); - findManager.setFindNextModel(null); - findManager.getFindInFileModel().copyFrom(findModel); + myFindManager.setFindNextModel(null); + myFindManager.getFindInFileModel().copyFrom(findModel); String text = StringUtil.repeat(toFind + "\n",6); configureByText(FileTypes.PLAIN_TEXT, text); List<Usage> usages = FindUtil.findAll(getProject(), myEditor, findModel); + assertNotNull(usages); for (Usage usage : usages) { ReplaceInProjectManager.getInstance(getProject()).replaceUsage(usage, findModel, Collections.<Usage>emptySet(), false); } @@ -394,9 +398,10 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { assertEquals(newText, getEditor().getDocument().getText()); } - public void testFindInFileUnderLibraryUnderProject() throws Exception { + public void testFindInFileUnderLibraryUnderProject() { initProject("libUnderProject", "src"); - PsiTestUtil.addLibrary(myModule, "lib", JavaTestUtil.getJavaTestDataPath() + "/find/libUnderProject/lib", new String[]{""}, ArrayUtil.EMPTY_STRING_ARRAY); + String libDir = JavaTestUtil.getJavaTestDataPath() + "/find/libUnderProject/lib"; + PsiTestUtil.addLibrary(myModule, "lib", libDir, new String[]{""}, ArrayUtil.EMPTY_STRING_ARRAY); FindModel findModel = new FindModel(); findModel.setStringToFind("TargetWord"); @@ -411,7 +416,7 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { assertSize(2, findUsages(findModel)); } - public void testLocalScopeSearchPerformance() throws Throwable { + public void testLocalScopeSearchPerformance() throws Exception { final int fileCount = 3000; final int lineCount = 500; TempDirTestFixture fixture = new LightTempDirTestFixtureImpl(); @@ -426,6 +431,7 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { VirtualFile file = fixture.createFile("target.txt", sampleText); PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file); + assertNotNull(psiFile); final FindModel findModel = new FindModel(); findModel.setStringToFind("TargetWord"); findModel.setWholeWordsOnly(true); @@ -451,38 +457,28 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { } } - public void testFindInCommentsAndLiterals() throws Exception{ - FindManager findManager = FindManager.getInstance(myProject); - + public void testFindInCommentsAndLiterals() { FindModel findModel = FindManagerTestUtils.configureFindModel("done"); String text = "\"done done done\" /* done done done */"; - - FindManagerTestUtils.runFindInCommentsAndLiterals(findManager, findModel, text); + FindManagerTestUtils.runFindInCommentsAndLiterals(myFindManager, findModel, text); findModel.setRegularExpressions(true); - FindManagerTestUtils.runFindInCommentsAndLiterals(findManager, findModel, text); + FindManagerTestUtils.runFindInCommentsAndLiterals(myFindManager, findModel, text); } - public void testFindInJavaDocs() throws Exception{ - FindManager findManager = FindManager.getInstance(myProject); - + public void testFindInJavaDocs() { FindModel findModel = FindManagerTestUtils.configureFindModel("done"); - String text = "/** done done done */"; findModel.setInCommentsOnly(true); - FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text); + FindManagerTestUtils.runFindForwardAndBackward(myFindManager, findModel, text); findModel.setRegularExpressions(true); - FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text); - - FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text, "groovy"); + FindManagerTestUtils.runFindForwardAndBackward(myFindManager, findModel, text); } - public void testFindInCommentsProperlyWorksWithOffsets() throws Exception{ - FindManager findManager = FindManager.getInstance(myProject); - + public void testFindInCommentsProperlyWorksWithOffsets() { FindModel findModel = FindManagerTestUtils.configureFindModel("done"); String prefix = "/*"; @@ -491,72 +487,45 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setInCommentsOnly(true); LightVirtualFile file = new LightVirtualFile("A.java", text); - FindResult findResult = findManager.findString(text, prefix.length(), findModel, file); + FindResult findResult = myFindManager.findString(text, prefix.length(), findModel, file); assertTrue(findResult.isStringFound()); findModel.setRegularExpressions(true); - findResult = findManager.findString(text, prefix.length(), findModel, file); + findResult = myFindManager.findString(text, prefix.length(), findModel, file); assertTrue(findResult.isStringFound()); } - public void testFindInUserFileType() throws Exception{ - FindManager findManager = FindManager.getInstance(myProject); - + public void testFindInUserFileType() { FindModel findModel = FindManagerTestUtils.configureFindModel("done"); - String text = "\"done done\"; 'done'; // done\n" + "/* done\n" + "done */"; - - FindManagerTestUtils.runFindInCommentsAndLiterals(findManager, findModel, text, "cs"); + FindManagerTestUtils.runFindInCommentsAndLiterals(myFindManager, findModel, text, "cs"); } - public void testFindInLiteralToSkipQuotes() throws Exception{ - FindManager findManager = FindManager.getInstance(myProject); - + public void testFindInLiteralToSkipQuotes() { FindModel findModel = FindManagerTestUtils.configureFindModel("^done$"); - findModel.setRegularExpressions(true); - - String text = "\"done\"; 'done'; 'done' \"done2\""; + findModel.setRegularExpressions(true); findModel.setInStringLiteralsOnly(true); findModel.setInCommentsOnly(false); - FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text, "java"); - - text = "def n = \"\"\"done\"\"\"\n def n = /done/\n def n = \"done\"\n def n = \"done2\""; - - FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text, "groovy"); - - text = "\"\"; \"done\"; 'done'; 'done' \"done2\""; + String text = "\"done\"; 'done'; 'done' \"done2\""; + FindManagerTestUtils.runFindForwardAndBackward(myFindManager, findModel, text, "java"); findModel.setStringToFind("done"); findModel.setWholeWordsOnly(true); findModel.setRegularExpressions(false); - - FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text, "java"); - } - - public void testFindInShellCommentsOfGroovy() throws Exception{ - FindManager findManager = FindManager.getInstance(myProject); - - FindModel findModel = FindManagerTestUtils.configureFindModel("done"); - findModel.setWholeWordsOnly(true); - - String text = "#! done done done\n"; - - findModel.setInCommentsOnly(true); - FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text, "groovy"); + text = "\"\"; \"done\"; 'done'; 'done' \"done2\""; + FindManagerTestUtils.runFindForwardAndBackward(myFindManager, findModel, text, "java"); } - public void testFindInJavaDoc() throws Exception{ - FindManager findManager = FindManager.getInstance(myProject); - + public void testFindInJavaDoc() { FindModel findModel = FindManagerTestUtils.configureFindModel("do ne"); findModel.setWholeWordsOnly(true); String text = "/** do ne do ne do ne */"; findModel.setInCommentsOnly(true); - FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text, "java"); + FindManagerTestUtils.runFindForwardAndBackward(myFindManager, findModel, text, "java"); } } diff --git a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java index d86fd6b2f32a..dbdbb5aff9b9 100644 --- a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java +++ b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java @@ -412,7 +412,7 @@ public class DirectoryIndexTest extends IdeaTestCase { checkInfoNull(module2Output); checkInfoNull(module2TestOutput); - assertTrue(myIndex.isProjectExcludeRoot(excluded)); + assertFalse(myIndex.isProjectExcludeRoot(excluded)); excluded.delete(this); projectOutput.delete(this); @@ -430,7 +430,7 @@ public class DirectoryIndexTest extends IdeaTestCase { }; VirtualFileManager.getInstance().addVirtualFileListener(l, getTestRootDisposable()); excluded = myModule1Dir.createChildDirectory(this, excluded.getName()); - //todo assertTrue(myIndex.isProjectExcludeRoot(excluded)); + assertFalse(myIndex.isProjectExcludeRoot(excluded)); projectOutput = myModule1Dir.createChildDirectory(this, projectOutput.getName()); module2Output = myModule1Dir.createChildDirectory(this, module2Output.getName()); module2TestOutput = myModule2Dir.createChildDirectory(this, module2TestOutput.getName()); @@ -442,7 +442,7 @@ public class DirectoryIndexTest extends IdeaTestCase { assertEquals(created.toString(), 4, created.size()); - assertTrue(myIndex.isProjectExcludeRoot(excluded)); + assertFalse(myIndex.isProjectExcludeRoot(excluded)); } public void testExcludesShouldBeRecognizedRightOnRefresh() throws Exception { @@ -521,12 +521,24 @@ public class DirectoryIndexTest extends IdeaTestCase { checkInfo(myExcludedLibClsDir, null, true, false, "lib.cls.exc", null, myModule3); } - public void testExcludeCompilerOutputOutsideOfContentRoot() throws Exception { final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); assertTrue(fileIndex.isIgnored(myOutputDir)); assertTrue(fileIndex.isIgnored(myModule1OutputDir)); assertFalse(fileIndex.isIgnored(myOutputDir.getParent())); + assertTrue(myIndex.isProjectExcludeRoot(myOutputDir)); + assertFalse(myIndex.isProjectExcludeRoot(myModule1OutputDir)); + String moduleOutputUrl = myModule1OutputDir.getUrl(); + + myOutputDir.delete(this); + + PsiTestUtil.setCompilerOutputPath(myModule, moduleOutputUrl, false); + myOutputDir = myRootVFile.createChildDirectory(this, "out"); + myModule1OutputDir = myOutputDir.createChildDirectory(this, "module1"); + + assertTrue(myIndex.isProjectExcludeRoot(myOutputDir)); + assertTrue(myIndex.isProjectExcludeRoot(myModule1OutputDir)); + assertTrue(fileIndex.isIgnored(myModule1OutputDir)); } private void checkInfo(VirtualFile dir, diff --git a/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy b/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy index b7b39fb7a017..936bb1c84203 100644 --- a/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy +++ b/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy @@ -66,7 +66,9 @@ class StubAstSwitchTest extends LightCodeInsightFixtureTestCase { int count = 100 List<PsiClass> classList = (0..<count).collect { myFixture.addClass("class Foo$it { " + - (0..<100).collect { "void foo$it(int i, boolean b, Object o) {}" }.join("\n") + + "void foo$it(" + + (0..250).collect { "int i$it"}.join(", ") + + ") {}" + " }") } CountDownLatch latch = new CountDownLatch(count) diff --git a/java/openapi/src/com/intellij/ide/hierarchy/call/CallReferenceProcessor.java b/java/openapi/src/com/intellij/ide/hierarchy/call/CallReferenceProcessor.java new file mode 100644 index 000000000000..5c2585f1ede0 --- /dev/null +++ b/java/openapi/src/com/intellij/ide/hierarchy/call/CallReferenceProcessor.java @@ -0,0 +1,35 @@ +/* + * Copyright 2000-2013 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.hierarchy.call; + +import com.intellij.openapi.extensions.ExtensionPointName; +import com.intellij.psi.PsiReference; +import org.jetbrains.annotations.NotNull; + +/** + * Created by Max Medvedev on 10/5/13 + */ +public interface CallReferenceProcessor { + ExtensionPointName<CallReferenceProcessor> EP_NAME = ExtensionPointName.create("com.intellij.hierarchy.referenceProcessor"); + + /** + * + * @param reference reference to process + * @param data settings to use while processing + * @return false if the reference is processed + */ + boolean process(@NotNull PsiReference reference, @NotNull JavaCallHierarchyData data); +} diff --git a/java/openapi/src/com/intellij/ide/hierarchy/call/JavaCallHierarchyData.java b/java/openapi/src/com/intellij/ide/hierarchy/call/JavaCallHierarchyData.java new file mode 100644 index 000000000000..e2b5a7a6e2d9 --- /dev/null +++ b/java/openapi/src/com/intellij/ide/hierarchy/call/JavaCallHierarchyData.java @@ -0,0 +1,91 @@ +/* + * Copyright 2000-2013 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.hierarchy.call; + +import com.intellij.ide.util.treeView.NodeDescriptor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiClassType; +import com.intellij.psi.PsiMember; +import com.intellij.psi.PsiMethod; + +import java.util.Map; +import java.util.Set; + +/** + * Created by Max Medvedev on 10/5/13 + */ +public class JavaCallHierarchyData { + private final PsiClass myOriginalClass; + private final PsiMethod myMethodToFind; + private final PsiClassType myOriginalType; + private final PsiMethod myMethod; + private final Set<PsiMethod> myMethodsToFind; + private final NodeDescriptor myNodeDescriptor; + private final Map<PsiMember, NodeDescriptor> myResultMap; + private final Project myProject; + + public JavaCallHierarchyData(PsiClass originalClass, + PsiMethod methodToFind, + PsiClassType originalType, + PsiMethod method, + Set<PsiMethod> methodsToFind, + NodeDescriptor nodeDescriptor, + Map<PsiMember, NodeDescriptor> resultMap, + Project project) { + + myOriginalClass = originalClass; + myMethodToFind = methodToFind; + myOriginalType = originalType; + myMethod = method; + myMethodsToFind = methodsToFind; + myNodeDescriptor = nodeDescriptor; + myResultMap = resultMap; + myProject = project; + } + + public PsiClass getOriginalClass() { + return myOriginalClass; + } + + public PsiMethod getMethodToFind() { + return myMethodToFind; + } + + public PsiClassType getOriginalType() { + return myOriginalType; + } + + public PsiMethod getMethod() { + return myMethod; + } + + public Set<PsiMethod> getMethodsToFind() { + return myMethodsToFind; + } + + public NodeDescriptor getNodeDescriptor() { + return myNodeDescriptor; + } + + public Map<PsiMember, NodeDescriptor> getResultMap() { + return myResultMap; + } + + public Project getProject() { + return myProject; + } +} diff --git a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java index 142b66c3f78d..add2b6716c0c 100644 --- a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java @@ -139,36 +139,41 @@ public abstract class CodeInsightTestCase extends PsiTestCase { return configureByFile(vFile, projectFile); } - protected PsiFile configureByText(@NotNull FileType fileType, @NonNls final String text) throws Exception { + protected PsiFile configureByText(@NotNull FileType fileType, @NonNls final String text) { return configureByText(fileType, text, null); } - protected PsiFile configureByText(@NotNull final FileType fileType, @NonNls final String text, @Nullable String _extension) throws Exception { - final String extension = _extension == null ? fileType.getDefaultExtension():_extension; + protected PsiFile configureByText(@NotNull final FileType fileType, @NonNls final String text, @Nullable String _extension) { + try { + final String extension = _extension == null ? fileType.getDefaultExtension():_extension; - File dir = createTempDirectory(); - final File tempFile = FileUtil.createTempFile(dir, "aaa", "." + extension, true); - final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); - if (fileTypeManager.getFileTypeByExtension(extension) != fileType) { - new WriteCommandAction(getProject()) { - @Override - protected void run(Result result) throws Exception { - fileTypeManager.associateExtension(fileType, extension); - } - }.execute(); - } - final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempFile); - assert vFile != null; - VfsUtil.saveText(vFile, text); + File dir = createTempDirectory(); + final File tempFile = FileUtil.createTempFile(dir, "aaa", "." + extension, true); + final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); + if (fileTypeManager.getFileTypeByExtension(extension) != fileType) { + new WriteCommandAction(getProject()) { + @Override + protected void run(Result result) throws Exception { + fileTypeManager.associateExtension(fileType, extension); + } + }.execute(); + } + final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempFile); + assert vFile != null; + VfsUtil.saveText(vFile, text); - final VirtualFile vdir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(dir); + final VirtualFile vdir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(dir); - PsiTestUtil.addSourceRoot(myModule, vdir); + PsiTestUtil.addSourceRoot(myModule, vdir); - configureByExistingFile(vFile); + configureByExistingFile(vFile); - assertEquals(fileType, myFile.getVirtualFile().getFileType()); - return myFile; + assertEquals(fileType, myFile.getVirtualFile().getFileType()); + return myFile; + } + catch (IOException e) { + throw new RuntimeException(e); + } } diff --git a/java/java-tests/testSrc/com/intellij/find/FindManagerTestUtils.java b/java/testFramework/src/com/intellij/find/FindManagerTestUtils.java index d5e498f66596..89b2578390f7 100644 --- a/java/java-tests/testSrc/com/intellij/find/FindManagerTestUtils.java +++ b/java/testFramework/src/com/intellij/find/FindManagerTestUtils.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2013 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.find; import com.intellij.testFramework.LightVirtualFile; @@ -8,10 +23,7 @@ public class FindManagerTestUtils { runFindInCommentsAndLiterals(findManager, findModel, text, "java"); } - static void runFindInCommentsAndLiterals(FindManager findManager, - FindModel findModel, - String text, - String ext) { + public static void runFindInCommentsAndLiterals(FindManager findManager, FindModel findModel, String text, String ext) { findModel.setInStringLiteralsOnly(true); findModel.setInCommentsOnly(false); runFindForwardAndBackward(findManager, findModel, text, ext); @@ -21,7 +33,7 @@ public class FindManagerTestUtils { runFindForwardAndBackward(findManager, findModel, text, ext); } - static void runFindForwardAndBackward(FindManager findManager, FindModel findModel, String text) { + public static void runFindForwardAndBackward(FindManager findManager, FindModel findModel, String text) { runFindForwardAndBackward(findManager, findModel, text, "java"); } |