Merge remote-tracking branch 'origin/master'

This commit is contained in:
Ekaterina Tuzova
2012-07-16 19:20:33 +04:00
479 changed files with 20928 additions and 28414 deletions
@@ -1,64 +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.application.options;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.options.BaseConfigurable;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import javax.swing.*;
public class CodeStyleImportsConfigurable extends BaseConfigurable {
private CodeStyleImportsPanel myPanel;
private final CodeStyleSettings mySettings;
public CodeStyleImportsConfigurable(CodeStyleSettings settings) {
mySettings = settings;
}
public boolean isModified() {
return myPanel != null && myPanel.isModified();
}
public JComponent createComponent() {
myPanel = new CodeStyleImportsPanel(mySettings);
return myPanel;
}
public String getDisplayName() {
return ApplicationBundle.message("title.imports");
}
public void reset() {
if (myPanel != null) {
myPanel.reset();
}
}
public void apply() {
if (myPanel != null) {
myPanel.apply();
}
}
public void disposeUIResources() {
myPanel = null;
}
public String getHelpTopic() {
return "reference.settingsdialog.IDE.globalcodestyle.imports";
}
}
@@ -15,32 +15,19 @@
*/
package com.intellij.application.options;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.editor.SyntaxHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKeyDefaults;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.ui.ex.MultiLineLabel;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.PackageEntry;
import com.intellij.psi.codeStyle.PackageEntryTable;
import com.intellij.ui.*;
import com.intellij.ui.table.JBTable;
import com.intellij.util.IconUtil;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class CodeStyleImportsPanel extends JPanel {
private JCheckBox myCbUseFQClassNames;
@@ -49,10 +36,8 @@ public class CodeStyleImportsPanel extends JPanel {
private JCheckBox myCbInsertInnerClassImports;
private JTextField myClassCountField;
private JTextField myNamesCountField;
private final PackageEntryTable myImportLayoutList = new PackageEntryTable();
private final PackageEntryTable myPackageList = new PackageEntryTable();
private JBTable myImportLayoutTable;
private JBTable myPackageTable;
private final CodeStyleSettings mySettings;
private JRadioButton myJspImportCommaSeparated;
@@ -63,7 +48,7 @@ public class CodeStyleImportsPanel extends JPanel {
private JPanel myPackagesPanel;
private JPanel myImportsLayoutPanel;
private JPanel myWholePanel;
private JCheckBox myCbLayoutStaticImportsSeparately;
private ImportLayoutPanel myImportLayoutPanel;
public CodeStyleImportsPanel(CodeStyleSettings settings) {
mySettings = settings;
@@ -73,8 +58,24 @@ public class CodeStyleImportsPanel extends JPanel {
myGeneralPanel.add(createGeneralOptionsPanel(), BorderLayout.CENTER);
myJSPPanel.add(createJspImportLayoutPanel(), BorderLayout.CENTER);
myImportsLayoutPanel.add(createImportLayoutPanel(), BorderLayout.CENTER);
myPackagesPanel.add(createPackagesPanel(), BorderLayout.CENTER);
createImportPanel();
createPackagePanel();
}
private void createImportPanel() {
myImportLayoutPanel = new ImportLayoutPanel() {
@Override
public void refresh() {
refreshTable(myPackageTable, myPackageList);
refreshTable(getImportLayoutTable(), getImportLayoutList());
}
};
myImportsLayoutPanel.add(myImportLayoutPanel, BorderLayout.CENTER);
}
private void createPackagePanel() {
myPackageTable = ImportLayoutPanel.createTableForPackageEntries(myPackageList, myImportLayoutPanel);
myPackagesPanel.add(PackagePanel.createPackagesPanel(myPackageTable, myPackageList), BorderLayout.CENTER);
}
private JPanel createJspImportLayoutPanel() {
@@ -152,375 +153,11 @@ public class CodeStyleImportsPanel extends JPanel {
return group.createPanel();
}
private JPanel createPackagesPanel() {
JPanel panel = ToolbarDecorator.createDecorator(myPackageTable = createTableForPackageEntries(myPackageList))
.setAddAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
addPackageToPackages();
}
}).setRemoveAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
removeEntryFromPackages();
}
}).disableUpDownActions().setPreferredSize(new Dimension(-1, 150)).createPanel();
UIUtil.addBorder(panel, IdeBorderFactory.createTitledBorder(ApplicationBundle.message("title.packages.to.use.import.with"), false));
return panel;
}
private JPanel createImportLayoutPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(IdeBorderFactory.createTitledBorder(ApplicationBundle.message("title.import.layout"), false));
myCbLayoutStaticImportsSeparately = new JCheckBox("Layout static imports separately");
myCbLayoutStaticImportsSeparately.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (areStaticImportsEnabled()) {
boolean found = false;
for (int i = myImportLayoutList.getEntryCount() - 1; i >= 0; i--) {
PackageEntry entry = myImportLayoutList.getEntryAt(i);
if (entry == PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY) {
found = true;
break;
}
}
if (!found) {
int index = myImportLayoutList.getEntryCount();
if (index != 0 && myImportLayoutList.getEntryAt(index - 1) != PackageEntry.BLANK_LINE_ENTRY) {
myImportLayoutList.addEntry(PackageEntry.BLANK_LINE_ENTRY);
}
myImportLayoutList.addEntry(PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY);
}
}
else {
for (int i = myImportLayoutList.getEntryCount() - 1; i >= 0; i--) {
PackageEntry entry = myImportLayoutList.getEntryAt(i);
if (entry.isStatic()) {
myImportLayoutList.removeEntryAt(i);
}
}
}
refreshTable(myImportLayoutTable, myImportLayoutList);
refreshTable(myPackageTable, myPackageList);
}
});
panel.add(myCbLayoutStaticImportsSeparately, BorderLayout.NORTH);
panel.add(
ToolbarDecorator.createDecorator(myImportLayoutTable = createTableForPackageEntries(myImportLayoutList))
.addExtraAction(new AnActionButton(ApplicationBundle.message("button.add.package"), IconUtil.getAddPackageIcon()) {
@Override
public void actionPerformed(AnActionEvent e) {
addPackageToImportLayouts();
}
}).addExtraAction(new AnActionButton(ApplicationBundle.message("button.add.blank"), IconUtil.getAddBlankLineIcon()) {
@Override
public void actionPerformed(AnActionEvent e) {
addBlankLine();
}
}).setRemoveAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
removeEntryFromImportLayouts();
}
}).setMoveUpAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
moveRowUp();
}
}).setMoveDownAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
moveRowDown();
}
}).setRemoveActionUpdater(new AnActionButtonUpdater() {
@Override
public boolean isEnabled(AnActionEvent e) {
int selectedImport = myImportLayoutTable.getSelectedRow();
PackageEntry entry = selectedImport < 0 ? null : myImportLayoutList.getEntryAt(selectedImport);
return entry != null && entry != PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY && entry != PackageEntry.ALL_OTHER_IMPORTS_ENTRY;
}
}).setButtonComparator(ApplicationBundle.message("button.add.package"), ApplicationBundle.message("button.add.blank"),
"Remove", "Up", "Down")
.setPreferredSize(new Dimension(-1, 200)).createPanel(), BorderLayout.CENTER);
return panel;
}
private void refreshTable(final JBTable table, final PackageEntryTable packageTable) {
AbstractTableModel model = (AbstractTableModel)table.getModel();
table.createDefaultColumnsFromModel();
model.fireTableDataChanged();
resizeColumns(packageTable, table);
}
private boolean areStaticImportsEnabled() {
return myCbLayoutStaticImportsSeparately.isSelected();
}
private void addPackageToImportLayouts() {
int selected = myImportLayoutTable.getSelectedRow() + 1;
if (selected < 0) {
selected = myImportLayoutList.getEntryCount();
}
PackageEntry entry = new PackageEntry(false, "", true);
myImportLayoutList.insertEntryAt(entry, selected);
refreshTableModel(selected, myImportLayoutTable);
}
private static void refreshTableModel(int selectedRow, JBTable table) {
AbstractTableModel model = (AbstractTableModel)table.getModel();
model.fireTableRowsInserted(selectedRow, selectedRow);
table.setRowSelectionInterval(selectedRow, selectedRow);
TableUtil.editCellAt(table, selectedRow, 0);
Component editorComp = table.getEditorComponent();
if (editorComp != null) {
editorComp.requestFocus();
}
}
private void addPackageToPackages() {
int selected = myPackageTable.getSelectedRow() + 1;
if (selected < 0) {
selected = myPackageList.getEntryCount();
}
PackageEntry entry = new PackageEntry(false, "", true);
myPackageList.insertEntryAt(entry, selected);
refreshTableModel(selected, myPackageTable);
}
private void addBlankLine() {
int selected = myImportLayoutTable.getSelectedRow() + 1;
if (selected < 0) {
selected = myImportLayoutList.getEntryCount();
}
myImportLayoutList.insertEntryAt(PackageEntry.BLANK_LINE_ENTRY, selected);
AbstractTableModel model = (AbstractTableModel)myImportLayoutTable.getModel();
model.fireTableRowsInserted(selected, selected);
myImportLayoutTable.setRowSelectionInterval(selected, selected);
}
private void removeEntryFromImportLayouts() {
int selected = myImportLayoutTable.getSelectedRow();
if (selected < 0) {
return;
}
PackageEntry entry = myImportLayoutList.getEntryAt(selected);
if (entry == PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY || entry == PackageEntry.ALL_OTHER_IMPORTS_ENTRY) {
return;
}
TableUtil.stopEditing(myImportLayoutTable);
myImportLayoutList.removeEntryAt(selected);
AbstractTableModel model = (AbstractTableModel)myImportLayoutTable.getModel();
model.fireTableRowsDeleted(selected, selected);
if (selected >= myImportLayoutList.getEntryCount()) {
selected--;
}
if (selected >= 0) {
myImportLayoutTable.setRowSelectionInterval(selected, selected);
}
}
private void removeEntryFromPackages() {
int selected = myPackageTable.getSelectedRow();
if (selected < 0) return;
TableUtil.stopEditing(myPackageTable);
myPackageList.removeEntryAt(selected);
AbstractTableModel model = (AbstractTableModel)myPackageTable.getModel();
model.fireTableRowsDeleted(selected, selected);
if (selected >= myPackageList.getEntryCount()) {
selected--;
}
if (selected >= 0) {
myPackageTable.setRowSelectionInterval(selected, selected);
}
}
private void moveRowUp() {
int selected = myImportLayoutTable.getSelectedRow();
if (selected < 1) {
return;
}
TableUtil.stopEditing(myImportLayoutTable);
PackageEntry entry = myImportLayoutList.getEntryAt(selected);
PackageEntry previousEntry = myImportLayoutList.getEntryAt(selected - 1);
myImportLayoutList.setEntryAt(previousEntry, selected);
myImportLayoutList.setEntryAt(entry, selected - 1);
AbstractTableModel model = (AbstractTableModel)myImportLayoutTable.getModel();
model.fireTableRowsUpdated(selected - 1, selected);
myImportLayoutTable.setRowSelectionInterval(selected - 1, selected - 1);
}
private void moveRowDown() {
int selected = myImportLayoutTable.getSelectedRow();
if (selected >= myImportLayoutList.getEntryCount() - 1) {
return;
}
TableUtil.stopEditing(myImportLayoutTable);
PackageEntry entry = myImportLayoutList.getEntryAt(selected);
PackageEntry nextEntry = myImportLayoutList.getEntryAt(selected + 1);
myImportLayoutList.setEntryAt(nextEntry, selected);
myImportLayoutList.setEntryAt(entry, selected + 1);
AbstractTableModel model = (AbstractTableModel)myImportLayoutTable.getModel();
model.fireTableRowsUpdated(selected, selected + 1);
myImportLayoutTable.setRowSelectionInterval(selected + 1, selected + 1);
}
private JBTable createTableForPackageEntries(final PackageEntryTable packageTable) {
final String[] names = {
ApplicationBundle.message("listbox.import.package"),
ApplicationBundle.message("listbox.import.with.subpackages"),
};
// Create a model of the data.
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() {
return names.length + (areStaticImportsEnabled() ? 1 : 0);
}
public int getRowCount() {
return packageTable.getEntryCount();
}
public Object getValueAt(int row, int col) {
PackageEntry entry = packageTable.getEntryAt(row);
if (entry == null || !isCellEditable(row, col)) return null;
col += areStaticImportsEnabled() ? 0 : 1;
if (col == 0) {
return entry.isStatic();
}
if (col == 1) {
return entry.getPackageName();
}
if (col == 2) {
return entry.isWithSubpackages() ? Boolean.TRUE : Boolean.FALSE;
}
throw new IllegalArgumentException(String.valueOf(col));
}
public String getColumnName(int column) {
if (areStaticImportsEnabled() && column == 0) return "Static";
column -= areStaticImportsEnabled() ? 1 : 0;
return names[column];
}
public Class getColumnClass(int col) {
col += areStaticImportsEnabled() ? 0 : 1;
if (col == 0) {
return Boolean.class;
}
if (col == 1) {
return String.class;
}
if (col == 2) {
return Boolean.class;
}
throw new IllegalArgumentException(String.valueOf(col));
}
public boolean isCellEditable(int row, int col) {
PackageEntry packageEntry = packageTable.getEntryAt(row);
return !packageEntry.isSpecial();
}
public void setValueAt(Object aValue, int row, int col) {
PackageEntry packageEntry = packageTable.getEntryAt(row);
col += areStaticImportsEnabled() ? 0 : 1;
if (col == 0) {
PackageEntry newPackageEntry = new PackageEntry((Boolean)aValue, packageEntry.getPackageName(), packageEntry.isWithSubpackages());
packageTable.setEntryAt(newPackageEntry, row);
}
else if (col == 1) {
PackageEntry newPackageEntry =
new PackageEntry(packageEntry.isStatic(), ((String)aValue).trim(), packageEntry.isWithSubpackages());
packageTable.setEntryAt(newPackageEntry, row);
}
else if (col == 2) {
PackageEntry newPackageEntry =
new PackageEntry(packageEntry.isStatic(), packageEntry.getPackageName(), ((Boolean)aValue).booleanValue());
packageTable.setEntryAt(newPackageEntry, row);
}
else {
throw new IllegalArgumentException(String.valueOf(col));
}
}
};
// Create the table
final JBTable result = new JBTable(dataModel);
result.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resizeColumns(packageTable, result);
TableCellEditor editor = result.getDefaultEditor(String.class);
if (editor instanceof DefaultCellEditor) {
((DefaultCellEditor)editor).setClickCountToStart(1);
}
TableCellEditor beditor = result.getDefaultEditor(Boolean.class);
beditor.addCellEditorListener(new CellEditorListener() {
public void editingStopped(ChangeEvent e) {
if (areStaticImportsEnabled()) {
result.repaint(); // add/remove static keyword
}
}
public void editingCanceled(ChangeEvent e) {
}
});
return result;
}
private void resizeColumns(final PackageEntryTable packageTable, JBTable result) {
ColoredTableCellRenderer packageRenderer = new ColoredTableCellRenderer() {
@Override
protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) {
PackageEntry entry = packageTable.getEntryAt(row);
if (entry == PackageEntry.BLANK_LINE_ENTRY) {
append(" <blank line>", SimpleTextAttributes.LINK_ATTRIBUTES);
}
else {
TextAttributes attributes = TextAttributesKeyDefaults.getDefaultAttributes(SyntaxHighlighterColors.KEYWORD);
append("import", SimpleTextAttributes.fromTextAttributes(attributes));
if (entry.isStatic()) {
append(" ", SimpleTextAttributes.REGULAR_ATTRIBUTES);
append("static", SimpleTextAttributes.fromTextAttributes(attributes));
}
append(" ", SimpleTextAttributes.REGULAR_ATTRIBUTES);
if (entry == PackageEntry.ALL_OTHER_IMPORTS_ENTRY || entry == PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY) {
append("all other imports", SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
else {
append(entry.getPackageName() + ".*", SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
}
};
if (areStaticImportsEnabled()) {
fixColumnWidthToHeader(result, 0);
fixColumnWidthToHeader(result, 2);
result.getColumnModel().getColumn(1).setCellRenderer(packageRenderer);
result.getColumnModel().getColumn(0).setCellRenderer(new BooleanTableCellRenderer());
result.getColumnModel().getColumn(2).setCellRenderer(new BooleanTableCellRenderer());
}
else {
fixColumnWidthToHeader(result, 1);
result.getColumnModel().getColumn(0).setCellRenderer(packageRenderer);
result.getColumnModel().getColumn(1).setCellRenderer(new BooleanTableCellRenderer());
}
}
private static void fixColumnWidthToHeader(JBTable result, int columnIdx) {
final TableColumn column = result.getColumnModel().getColumn(columnIdx);
final int width =
15 + result.getTableHeader().getFontMetrics(result.getTableHeader().getFont()).stringWidth(result.getColumnName(columnIdx));
column.setMinWidth(width);
column.setMaxWidth(width);
ImportLayoutPanel.resizeColumns(packageTable, table, myImportLayoutPanel.areStaticImportsEnabled());
}
public void reset(CodeStyleSettings settings) {
@@ -531,19 +168,20 @@ public class CodeStyleImportsPanel extends JPanel {
myClassCountField.setText(Integer.toString(settings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND));
myNamesCountField.setText(Integer.toString(settings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND));
myImportLayoutList.copyFrom(settings.IMPORT_LAYOUT_TABLE);
myImportLayoutPanel.getImportLayoutList().copyFrom(settings.IMPORT_LAYOUT_TABLE);
myPackageList.copyFrom(settings.PACKAGES_TO_USE_IMPORT_ON_DEMAND);
myCbLayoutStaticImportsSeparately.setSelected(settings.LAYOUT_STATIC_IMPORTS_SEPARATELY);
myImportLayoutPanel.getCbLayoutStaticImportsSeparately().setSelected(settings.LAYOUT_STATIC_IMPORTS_SEPARATELY);
AbstractTableModel model = (AbstractTableModel)myImportLayoutTable.getModel();
final JBTable importLayoutTable = myImportLayoutPanel.getImportLayoutTable();
AbstractTableModel model = (AbstractTableModel)importLayoutTable.getModel();
model.fireTableDataChanged();
model = (AbstractTableModel)myPackageTable.getModel();
model.fireTableDataChanged();
if (myImportLayoutTable.getRowCount() > 0) {
myImportLayoutTable.getSelectionModel().setSelectionInterval(0, 0);
if (importLayoutTable.getRowCount() > 0) {
importLayoutTable.getSelectionModel().setSelectionInterval(0, 0);
}
if (myPackageTable.getRowCount() > 0) {
myPackageTable.getSelectionModel().setSelectionInterval(0, 0);
@@ -564,7 +202,7 @@ public class CodeStyleImportsPanel extends JPanel {
public void apply(CodeStyleSettings settings) {
stopTableEditing();
settings.LAYOUT_STATIC_IMPORTS_SEPARATELY = areStaticImportsEnabled();
settings.LAYOUT_STATIC_IMPORTS_SEPARATELY = myImportLayoutPanel.areStaticImportsEnabled();
settings.USE_FQ_CLASS_NAMES = myCbUseFQClassNames.isSelected();
settings.USE_FQ_CLASS_NAMES_IN_JAVADOC = myCbUseFQClassNamesInJavaDoc.isSelected();
settings.USE_SINGLE_CLASS_IMPORTS = myCbUseSingleClassImports.isSelected();
@@ -582,8 +220,9 @@ public class CodeStyleImportsPanel extends JPanel {
//just a bad number
}
myImportLayoutList.removeEmptyPackages();
settings.IMPORT_LAYOUT_TABLE.copyFrom(myImportLayoutList);
final PackageEntryTable list = myImportLayoutPanel.getImportLayoutList();
list.removeEmptyPackages();
settings.IMPORT_LAYOUT_TABLE.copyFrom(list);
myPackageList.removeEmptyPackages();
settings.PACKAGES_TO_USE_IMPORT_ON_DEMAND.copyFrom(myPackageList);
@@ -595,14 +234,13 @@ public class CodeStyleImportsPanel extends JPanel {
apply(mySettings);
}
private void stopTableEditing() {
TableUtil.stopEditing(myImportLayoutTable);
TableUtil.stopEditing(myImportLayoutPanel.getImportLayoutTable());
TableUtil.stopEditing(myPackageTable);
}
public boolean isModified(CodeStyleSettings settings) {
boolean isModified = isModified(myCbLayoutStaticImportsSeparately, settings.LAYOUT_STATIC_IMPORTS_SEPARATELY);
boolean isModified = isModified(myImportLayoutPanel.getCbLayoutStaticImportsSeparately(), settings.LAYOUT_STATIC_IMPORTS_SEPARATELY);
isModified |= isModified(myCbUseFQClassNames, settings.USE_FQ_CLASS_NAMES);
isModified |= isModified(myCbUseFQClassNamesInJavaDoc, settings.USE_FQ_CLASS_NAMES_IN_JAVADOC);
isModified |= isModified(myCbUseSingleClassImports, settings.USE_SINGLE_CLASS_IMPORTS);
@@ -610,7 +248,7 @@ public class CodeStyleImportsPanel extends JPanel {
isModified |= isModified(myClassCountField, settings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND);
isModified |= isModified(myNamesCountField, settings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND);
isModified |= isModified(myImportLayoutList, settings.IMPORT_LAYOUT_TABLE);
isModified |= isModified(myImportLayoutPanel.getImportLayoutList(), settings.IMPORT_LAYOUT_TABLE);
isModified |= isModified(myPackageList, settings.PACKAGES_TO_USE_IMPORT_ON_DEMAND);
isModified |= settings.JSP_PREFER_COMMA_SEPARATED_IMPORT_LIST != myJspImportCommaSeparated.isSelected();
@@ -0,0 +1,382 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.editor.SyntaxHighlighterColors;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.psi.codeStyle.PackageEntry;
import com.intellij.psi.codeStyle.PackageEntryTable;
import com.intellij.ui.*;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.table.JBTable;
import com.intellij.util.IconUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* @author Max Medvedev
*/
public abstract class ImportLayoutPanel extends JPanel {
private final JBCheckBox myCbLayoutStaticImportsSeparately = new JBCheckBox("Layout static imports separately");
private JBTable myImportLayoutTable;
private final PackageEntryTable myImportLayoutList = new PackageEntryTable();
public JBTable getImportLayoutTable() {
return myImportLayoutTable;
}
public PackageEntryTable getImportLayoutList() {
return myImportLayoutList;
}
public JBCheckBox getCbLayoutStaticImportsSeparately() {
return myCbLayoutStaticImportsSeparately;
}
public ImportLayoutPanel() {
super(new BorderLayout());
setBorder(IdeBorderFactory.createTitledBorder(ApplicationBundle.message("title.import.layout"), false));
myCbLayoutStaticImportsSeparately.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (areStaticImportsEnabled()) {
boolean found = false;
for (int i = myImportLayoutList.getEntryCount() - 1; i >= 0; i--) {
PackageEntry entry = myImportLayoutList.getEntryAt(i);
if (entry == PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY) {
found = true;
break;
}
}
if (!found) {
int index = myImportLayoutList.getEntryCount();
if (index != 0 && myImportLayoutList.getEntryAt(index - 1) != PackageEntry.BLANK_LINE_ENTRY) {
myImportLayoutList.addEntry(PackageEntry.BLANK_LINE_ENTRY);
}
myImportLayoutList.addEntry(PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY);
}
}
else {
for (int i = myImportLayoutList.getEntryCount() - 1; i >= 0; i--) {
PackageEntry entry = myImportLayoutList.getEntryAt(i);
if (entry.isStatic()) {
myImportLayoutList.removeEntryAt(i);
}
}
}
refresh();
}
});
this.add(myCbLayoutStaticImportsSeparately, BorderLayout.NORTH);
this.add(
ToolbarDecorator.createDecorator(myImportLayoutTable = createTableForPackageEntries(myImportLayoutList, this))
.addExtraAction(new AnActionButton(ApplicationBundle.message("button.add.package"), IconUtil.getAddPackageIcon()) {
@Override
public void actionPerformed(AnActionEvent e) {
addPackageToImportLayouts();
}
}).addExtraAction(new AnActionButton(ApplicationBundle.message("button.add.blank"), IconUtil.getAddBlankLineIcon()) {
@Override
public void actionPerformed(AnActionEvent e) {
addBlankLine();
}
}).setRemoveAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
removeEntryFromImportLayouts();
}
}).setMoveUpAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
moveRowUp();
}
}).setMoveDownAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
moveRowDown();
}
}).setRemoveActionUpdater(new AnActionButtonUpdater() {
@Override
public boolean isEnabled(AnActionEvent e) {
int selectedImport = myImportLayoutTable.getSelectedRow();
PackageEntry entry = selectedImport < 0 ? null : myImportLayoutList.getEntryAt(selectedImport);
return entry != null && entry != PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY && entry != PackageEntry.ALL_OTHER_IMPORTS_ENTRY;
}
}).setButtonComparator(ApplicationBundle.message("button.add.package"), ApplicationBundle.message("button.add.blank"),
"Remove", "Up", "Down")
.setPreferredSize(new Dimension(-1, 200)).createPanel(), BorderLayout.CENTER);
}
public abstract void refresh();
private void addPackageToImportLayouts() {
int selected = myImportLayoutTable.getSelectedRow() + 1;
if (selected < 0) {
selected = myImportLayoutList.getEntryCount();
}
PackageEntry entry = new PackageEntry(false, "", true);
myImportLayoutList.insertEntryAt(entry, selected);
refreshTableModel(selected, myImportLayoutTable);
}
private void addBlankLine() {
int selected = myImportLayoutTable.getSelectedRow() + 1;
if (selected < 0) {
selected = myImportLayoutList.getEntryCount();
}
myImportLayoutList.insertEntryAt(PackageEntry.BLANK_LINE_ENTRY, selected);
AbstractTableModel model = (AbstractTableModel)myImportLayoutTable.getModel();
model.fireTableRowsInserted(selected, selected);
myImportLayoutTable.setRowSelectionInterval(selected, selected);
}
private void removeEntryFromImportLayouts() {
int selected = myImportLayoutTable.getSelectedRow();
if (selected < 0) {
return;
}
PackageEntry entry = myImportLayoutList.getEntryAt(selected);
if (entry == PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY || entry == PackageEntry.ALL_OTHER_IMPORTS_ENTRY) {
return;
}
TableUtil.stopEditing(myImportLayoutTable);
myImportLayoutList.removeEntryAt(selected);
AbstractTableModel model = (AbstractTableModel)myImportLayoutTable.getModel();
model.fireTableRowsDeleted(selected, selected);
if (selected >= myImportLayoutList.getEntryCount()) {
selected--;
}
if (selected >= 0) {
myImportLayoutTable.setRowSelectionInterval(selected, selected);
}
}
private void moveRowUp() {
int selected = myImportLayoutTable.getSelectedRow();
if (selected < 1) {
return;
}
TableUtil.stopEditing(myImportLayoutTable);
PackageEntry entry = myImportLayoutList.getEntryAt(selected);
PackageEntry previousEntry = myImportLayoutList.getEntryAt(selected - 1);
myImportLayoutList.setEntryAt(previousEntry, selected);
myImportLayoutList.setEntryAt(entry, selected - 1);
AbstractTableModel model = (AbstractTableModel)myImportLayoutTable.getModel();
model.fireTableRowsUpdated(selected - 1, selected);
myImportLayoutTable.setRowSelectionInterval(selected - 1, selected - 1);
}
private void moveRowDown() {
int selected = myImportLayoutTable.getSelectedRow();
if (selected >= myImportLayoutList.getEntryCount() - 1) {
return;
}
TableUtil.stopEditing(myImportLayoutTable);
PackageEntry entry = myImportLayoutList.getEntryAt(selected);
PackageEntry nextEntry = myImportLayoutList.getEntryAt(selected + 1);
myImportLayoutList.setEntryAt(nextEntry, selected);
myImportLayoutList.setEntryAt(entry, selected + 1);
AbstractTableModel model = (AbstractTableModel)myImportLayoutTable.getModel();
model.fireTableRowsUpdated(selected, selected + 1);
myImportLayoutTable.setRowSelectionInterval(selected + 1, selected + 1);
}
public boolean areStaticImportsEnabled() {
return myCbLayoutStaticImportsSeparately.isSelected();
}
public static JBTable createTableForPackageEntries(final PackageEntryTable packageTable, final ImportLayoutPanel panel) {
final String[] names = {
ApplicationBundle.message("listbox.import.package"),
ApplicationBundle.message("listbox.import.with.subpackages"),
};
// Create a model of the data.
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() {
return names.length + (panel.areStaticImportsEnabled() ? 1 : 0);
}
public int getRowCount() {
return packageTable.getEntryCount();
}
@Nullable
public Object getValueAt(int row, int col) {
PackageEntry entry = packageTable.getEntryAt(row);
if (entry == null || !isCellEditable(row, col)) return null;
col += panel.areStaticImportsEnabled() ? 0 : 1;
if (col == 0) {
return entry.isStatic();
}
if (col == 1) {
return entry.getPackageName();
}
if (col == 2) {
return entry.isWithSubpackages() ? Boolean.TRUE : Boolean.FALSE;
}
throw new IllegalArgumentException(String.valueOf(col));
}
public String getColumnName(int column) {
if (panel.areStaticImportsEnabled() && column == 0) return "Static";
column -= panel.areStaticImportsEnabled() ? 1 : 0;
return names[column];
}
public Class getColumnClass(int col) {
col += panel.areStaticImportsEnabled() ? 0 : 1;
if (col == 0) {
return Boolean.class;
}
if (col == 1) {
return String.class;
}
if (col == 2) {
return Boolean.class;
}
throw new IllegalArgumentException(String.valueOf(col));
}
public boolean isCellEditable(int row, int col) {
PackageEntry packageEntry = packageTable.getEntryAt(row);
return !packageEntry.isSpecial();
}
public void setValueAt(Object aValue, int row, int col) {
PackageEntry packageEntry = packageTable.getEntryAt(row);
col += panel.areStaticImportsEnabled() ? 0 : 1;
if (col == 0) {
PackageEntry newPackageEntry = new PackageEntry((Boolean)aValue, packageEntry.getPackageName(), packageEntry.isWithSubpackages());
packageTable.setEntryAt(newPackageEntry, row);
}
else if (col == 1) {
PackageEntry newPackageEntry =
new PackageEntry(packageEntry.isStatic(), ((String)aValue).trim(), packageEntry.isWithSubpackages());
packageTable.setEntryAt(newPackageEntry, row);
}
else if (col == 2) {
PackageEntry newPackageEntry =
new PackageEntry(packageEntry.isStatic(), packageEntry.getPackageName(), ((Boolean)aValue).booleanValue());
packageTable.setEntryAt(newPackageEntry, row);
}
else {
throw new IllegalArgumentException(String.valueOf(col));
}
}
};
// Create the table
final JBTable result = new JBTable(dataModel);
result.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resizeColumns(packageTable, result, panel.areStaticImportsEnabled());
TableCellEditor editor = result.getDefaultEditor(String.class);
if (editor instanceof DefaultCellEditor) {
((DefaultCellEditor)editor).setClickCountToStart(1);
}
TableCellEditor beditor = result.getDefaultEditor(Boolean.class);
beditor.addCellEditorListener(new CellEditorListener() {
public void editingStopped(ChangeEvent e) {
if (panel.areStaticImportsEnabled()) {
result.repaint(); // add/remove static keyword
}
}
public void editingCanceled(ChangeEvent e) {
}
});
return result;
}
public static void resizeColumns(final PackageEntryTable packageTable, JBTable result, boolean areStaticImportsEnabled) {
ColoredTableCellRenderer packageRenderer = new ColoredTableCellRenderer() {
@Override
protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) {
PackageEntry entry = packageTable.getEntryAt(row);
if (entry == PackageEntry.BLANK_LINE_ENTRY) {
append(" <blank line>", SimpleTextAttributes.LINK_ATTRIBUTES);
}
else {
TextAttributes attributes = SyntaxHighlighterColors.KEYWORD.getDefaultAttributes();
append("import", SimpleTextAttributes.fromTextAttributes(attributes));
if (entry.isStatic()) {
append(" ", SimpleTextAttributes.REGULAR_ATTRIBUTES);
append("static", SimpleTextAttributes.fromTextAttributes(attributes));
}
append(" ", SimpleTextAttributes.REGULAR_ATTRIBUTES);
if (entry == PackageEntry.ALL_OTHER_IMPORTS_ENTRY || entry == PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY) {
append("all other imports", SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
else {
append(entry.getPackageName() + ".*", SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
}
};
if (areStaticImportsEnabled) {
fixColumnWidthToHeader(result, 0);
fixColumnWidthToHeader(result, 2);
result.getColumnModel().getColumn(1).setCellRenderer(packageRenderer);
result.getColumnModel().getColumn(0).setCellRenderer(new BooleanTableCellRenderer());
result.getColumnModel().getColumn(2).setCellRenderer(new BooleanTableCellRenderer());
}
else {
fixColumnWidthToHeader(result, 1);
result.getColumnModel().getColumn(0).setCellRenderer(packageRenderer);
result.getColumnModel().getColumn(1).setCellRenderer(new BooleanTableCellRenderer());
}
}
private static void fixColumnWidthToHeader(JBTable result, int columnIdx) {
final TableColumn column = result.getColumnModel().getColumn(columnIdx);
final int width =
15 + result.getTableHeader().getFontMetrics(result.getTableHeader().getFont()).stringWidth(result.getColumnName(columnIdx));
column.setMinWidth(width);
column.setMaxWidth(width);
}
public static void refreshTableModel(int selectedRow, JBTable table) {
AbstractTableModel model = (AbstractTableModel)table.getModel();
model.fireTableRowsInserted(selectedRow, selectedRow);
table.setRowSelectionInterval(selectedRow, selectedRow);
TableUtil.editCellAt(table, selectedRow, 0);
Component editorComp = table.getEditorComponent();
if (editorComp != null) {
editorComp.requestFocus();
}
}
}
@@ -1,43 +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.application.options;
import com.intellij.psi.codeStyle.CodeStyleSettingsProvider;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.psi.codeStyle.DisplayPriority;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class ImportsSettingsProvider extends CodeStyleSettingsProvider {
@NotNull
public Configurable createSettingsPage(final CodeStyleSettings settings, final CodeStyleSettings originalSettings) {
return new CodeStyleImportsConfigurable(settings);
}
@Override
public String getConfigurableDisplayName() {
return ApplicationBundle.message("title.imports");
}
@Override
public DisplayPriority getPriority() {
return DisplayPriority.CODE_SETTINGS;
}
}
@@ -1,33 +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.application.options;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.psi.codeStyle.CodeStyleSettings;
public class JavadocFormatConfigurable extends CodeStyleAbstractConfigurable {
public JavadocFormatConfigurable(CodeStyleSettings settings, CodeStyleSettings cloneSettings) {
super(settings, cloneSettings, ApplicationBundle.message("title.javadoc"));
}
protected CodeStyleAbstractPanel createPanel(final CodeStyleSettings settings) {
return new JavaDocFormattingPanel(settings);
}
public String getHelpTopic() {
return "reference.settingsdialog.IDE.globalcodestyle.javadoc";
}
}
@@ -1,37 +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.application.options;
import com.intellij.psi.codeStyle.CodeStyleSettingsProvider;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.application.ApplicationBundle;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class JavadocSettingsProvider extends CodeStyleSettingsProvider {
@NotNull
public Configurable createSettingsPage(final CodeStyleSettings settings, final CodeStyleSettings originalSettings) {
return new JavadocFormatConfigurable(settings, originalSettings);
}
@Override
public String getConfigurableDisplayName() {
return ApplicationBundle.message("title.javadoc");
}
}
@@ -0,0 +1,77 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.psi.codeStyle.PackageEntry;
import com.intellij.psi.codeStyle.PackageEntryTable;
import com.intellij.ui.*;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
/**
* @author Max Medvedev
*/
public class PackagePanel {
private static void addPackageToPackages(JBTable table, PackageEntryTable list) {
int selected = table.getSelectedRow() + 1;
if (selected < 0) {
selected = list.getEntryCount();
}
PackageEntry entry = new PackageEntry(false, "", true);
list.insertEntryAt(entry, selected);
ImportLayoutPanel.refreshTableModel(selected, table);
}
private static void removeEntryFromPackages(JBTable table, PackageEntryTable list) {
int selected = table.getSelectedRow();
if (selected < 0) return;
TableUtil.stopEditing(table);
list.removeEntryAt(selected);
AbstractTableModel model = (AbstractTableModel)table.getModel();
model.fireTableRowsDeleted(selected, selected);
if (selected >= list.getEntryCount()) {
selected--;
}
if (selected >= 0) {
table.setRowSelectionInterval(selected, selected);
}
}
public static JPanel createPackagesPanel(final JBTable packageTable, final PackageEntryTable packageList) {
JPanel panel = ToolbarDecorator.createDecorator(packageTable)
.setAddAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
addPackageToPackages(packageTable, packageList);
}
}).setRemoveAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
removeEntryFromPackages(packageTable, packageList);
}
}).disableUpDownActions().setPreferredSize(new Dimension(-1, 150)).createPanel();
UIUtil.addBorder(panel, IdeBorderFactory.createTitledBorder(ApplicationBundle.message("title.packages.to.use.import.with"), false));
return panel;
}
}
@@ -28,7 +28,7 @@ import com.intellij.ide.DataManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.UndoUtil;
import com.intellij.openapi.command.undo.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
@@ -358,6 +358,18 @@ public class ExternalAnnotationsManagerImpl extends ExternalAnnotationsManager {
}
}
}.execute();
UndoManager.getInstance(project).undoableActionPerformed(new BasicUndoableAction() {
@Override
public void undo() throws UnexpectedUndoException {
dropCache();
}
@Override
public void redo() throws UnexpectedUndoException {
dropCache();
}
});
}
@Override
@@ -1,38 +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.codeInsight.completion;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.psi.PsiMethod;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author peter
*/
public class PreferLessParametersWeigher extends CompletionWeigher {
@Override
public Integer weigh(@NotNull LookupElement element, @NotNull CompletionLocation location) {
if (location == null) {
return null;
}
final Object o = element.getObject();
if (o instanceof PsiMethod) {
return ((PsiMethod)o).getParameterList().getParametersCount();
}
return 0;
}
}
@@ -143,7 +143,7 @@ public class PostHighlightingPass extends TextEditorHighlightingPass {
myInLibrary = fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile);
myRefCountHolder = RefCountHolder.endUsing(myFile);
if (myRefCountHolder == null || !myRefCountHolder.retrieveUnusedReferencesInfo((DaemonProgressIndicator)progress, new Runnable() {
if (myRefCountHolder == null || !myRefCountHolder.retrieveUnusedReferencesInfo(progress, new Runnable() {
@Override
public void run() {
boolean errorFound = collectHighlights(elementSet, highlights, progress);
@@ -16,6 +16,7 @@
package com.intellij.codeInsight.daemon.impl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
@@ -47,9 +48,9 @@ public class RefCountHolder {
private final Map<PsiNamedElement, Boolean> myDclsUsedMap = new ConcurrentHashMap<PsiNamedElement, Boolean>();
private final Map<PsiReference, PsiImportStatementBase> myImportStatements = new ConcurrentHashMap<PsiReference, PsiImportStatementBase>();
private final Map<PsiElement,Boolean> myPossiblyDuplicateElements = new ConcurrentHashMap<PsiElement, Boolean>();
private final AtomicReference<DaemonProgressIndicator> myState = new AtomicReference<DaemonProgressIndicator>(VIRGIN);
private static final DaemonProgressIndicator VIRGIN = new DaemonProgressIndicator(); // just created or cleared
private static final DaemonProgressIndicator READY = new DaemonProgressIndicator();
private final AtomicReference<ProgressIndicator> myState = new AtomicReference<ProgressIndicator>(VIRGIN);
private static final ProgressIndicator VIRGIN = new DaemonProgressIndicator(); // just created or cleared
private static final ProgressIndicator READY = new DaemonProgressIndicator();
private static class HolderReference extends SoftReference<RefCountHolder> {
@SuppressWarnings("UnusedDeclaration")
@@ -271,8 +272,8 @@ public class RefCountHolder {
return false;
}
public boolean analyze(@NotNull PsiFile file, TextRange dirtyScope, @NotNull Runnable analyze, @NotNull DaemonProgressIndicator indicator) {
DaemonProgressIndicator old = myState.get();
public boolean analyze(@NotNull PsiFile file, TextRange dirtyScope, @NotNull Runnable analyze, @NotNull ProgressIndicator indicator) {
ProgressIndicator old = myState.get();
if (old != VIRGIN && old != READY) return false;
if (!myState.compareAndSet(old, indicator)) {
log("a: failed to change " + old + "->" + indicator);
@@ -305,8 +306,8 @@ public class RefCountHolder {
//System.err.println("RFC: "+s);
}
public boolean retrieveUnusedReferencesInfo(@NotNull DaemonProgressIndicator indicator, @NotNull Runnable analyze) {
DaemonProgressIndicator old = myState.get();
public boolean retrieveUnusedReferencesInfo(@NotNull ProgressIndicator indicator, @NotNull Runnable analyze) {
ProgressIndicator old = myState.get();
if (!myState.compareAndSet(READY, indicator)) {
log("r: failed to change " + old + "->" + indicator);
return false;
@@ -497,6 +497,7 @@ public class HighlightMethodUtil {
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, new CreateConstructorFromSuperFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, new CreateConstructorFromThisFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, new CreatePropertyFromUsageFix(methodCall));
QuickFixAction.registerQuickFixAction(highlightInfo, fixRange, new CreateGetterSetterPropertyFromUsageFix(methodCall));
CandidateInfo[] methodCandidates = resolveHelper.getReferencedMethodCandidates(methodCall, false);
CastMethodArgumentFix.REGISTRAR.registerCastActions(methodCandidates, methodCall, highlightInfo, fixRange);
PermuteArgumentsFix.registerFix(highlightInfo, methodCall, methodCandidates, fixRange);
@@ -133,7 +133,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
Document document = PsiDocumentManager.getInstance(project).getDocument(file);
TextRange dirtyScope = document == null ? file.getTextRange() : fileStatusMap.getFileDirtyScope(document, Pass.UPDATE_ALL);
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
success = indicator instanceof DaemonProgressIndicator && refCountHolder.analyze(file, dirtyScope, action, (DaemonProgressIndicator)indicator);
success = indicator != null && refCountHolder.analyze(file, dirtyScope, action, indicator);
}
else {
myRefCountHolder = null;
@@ -20,7 +20,6 @@ import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil;
import com.intellij.codeInsight.intention.HighPriorityAction;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.find.FindManager;
import com.intellij.find.findUsages.FindUsagesHandler;
@@ -61,7 +60,7 @@ import java.util.*;
* @author cdr
* @since Nov 13, 2002
*/
public class ChangeMethodSignatureFromUsageFix implements IntentionAction, HighPriorityAction {
public class ChangeMethodSignatureFromUsageFix implements IntentionAction/*, HighPriorityAction*/ {
final PsiMethod myTargetMethod;
final PsiExpression[] myExpressions;
final PsiSubstitutor mySubstitutor;
@@ -0,0 +1,71 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiMethodCallExpression;
import com.intellij.psi.util.PropertyUtil;
import java.util.List;
/**
* User: anna
* Date: 7/12/12
*/
public class CreateGetterSetterPropertyFromUsageFix extends CreatePropertyFromUsageFix {
public CreateGetterSetterPropertyFromUsageFix(PsiMethodCallExpression methodCall) {
super(methodCall);
}
@Override
protected boolean isAvailableImpl(int offset) {
boolean available = super.isAvailableImpl(offset);
if (available) {
setText("Create Property");
}
return available;
}
@Override
protected boolean checkTargetClasses(List<PsiClass> classes, String methodName) {
String propertyName = PropertyUtil.getPropertyName(methodName);
if (propertyName == null) return false;
String getterName = PropertyUtil.suggestGetterName(propertyName, null);
String setterName = PropertyUtil.suggestSetterName(propertyName);
for (PsiClass aClass : classes) {
if (aClass.findMethodsByName(getterName, false).length > 0 || aClass.findMethodsByName(setterName, false).length > 0) return false;
}
return true;
}
@Override
protected void beforeTemplateFinished(PsiClass aClass, PsiField field) {
PsiMethod getterPrototype = PropertyUtil.generateGetterPrototype(field);
if (aClass.findMethodsBySignature(getterPrototype, false).length == 0) {
aClass.add(getterPrototype);
}
PsiMethod setterPrototype = PropertyUtil.generateSetterPrototype(field);
if (aClass.findMethodsBySignature(setterPrototype, false).length == 0) {
aClass.add(setterPrototype);
}
super.beforeTemplateFinished(aClass, field);
}
}
@@ -18,6 +18,7 @@ package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.completion.JavaLookupElementBuilder;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.HighPriorityAction;
import com.intellij.codeInsight.intention.impl.TypeExpression;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.template.*;
@@ -47,7 +48,7 @@ import java.util.Set;
/**
* @author ven
*/
public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix {
public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix implements HighPriorityAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.CreatePropertyFromUsageFix");
@NonNls private static final String FIELD_VARIABLE = "FIELD_NAME_VARIABLE";
@NonNls private static final String TYPE_VARIABLE = "FIELD_TYPE_VARIABLE";
@@ -59,7 +60,7 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix {
myMethodCall = methodCall;
}
private final PsiMethodCallExpression myMethodCall;
protected final PsiMethodCallExpression myMethodCall;
@Override
@NotNull
@@ -98,6 +99,8 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix {
List<PsiClass> classes = getTargetClasses(myMethodCall);
if (classes.isEmpty()) return false;
if (!checkTargetClasses(classes, methodName)) return false;
for (PsiClass aClass : classes) {
if (!aClass.isInterface()) {
setText(getterOrSetter);
@@ -108,6 +111,10 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix {
return false;
}
protected boolean checkTargetClasses(List<PsiClass> classes, String methodName) {
return true;
}
static class FieldExpression extends Expression {
private final String myDefaultFieldName;
private final PsiField myField;
@@ -266,15 +273,19 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix {
PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
if (aClass == null) return;
if (aClass.findFieldByName(fieldName, true) != null) return;
PsiField field = aClass.findFieldByName(fieldName, true);
if (field != null){
CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field);
return;
}
PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();
try {
PsiType type = factory.createTypeFromText(fieldType, aClass);
try {
PsiField field = factory.createField(fieldName, type);
field = factory.createField(fieldName, type);
field = (PsiField)aClass.add(field);
PsiUtil.setModifierProperty(field, PsiModifier.STATIC, isStatic1);
positionCursor(project, field.getContainingFile(), field);
CreatePropertyFromUsageFix.this.beforeTemplateFinished(aClass, field);
}
catch (IncorrectOperationException e) {
LOG.error(e);
@@ -303,6 +314,10 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix {
});
}
protected void beforeTemplateFinished(PsiClass aClass, PsiField field) {
positionCursor(myMethodCall.getProject(), myMethodCall.getContainingFile(), myMethodCall);
}
private static String getVariableName(PsiMethodCallExpression methodCall, boolean isStatic) {
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(methodCall.getProject());
String methodName = methodCall.getMethodExpression().getReferenceName();
@@ -105,12 +105,43 @@ class StatementMover extends LineMover {
return true;
}
private boolean calcInsertOffset(PsiFile file, final Editor editor, LineRange range, @NotNull final MoveInfo info, final boolean down) {
int line = down ? range.endLine+1 : range.startLine - 1;
private int getDestLineForAnon(PsiFile file, Editor editor, LineRange range, MoveInfo info, boolean down) {
int destLine = down ? range.endLine+1 : range.startLine - 1;
if (!(range.firstElement instanceof PsiStatement)) {
return destLine;
}
PsiElement sibling =
StatementUpDownMover.firstNonWhiteElement(down ? range.firstElement.getNextSibling() : range.firstElement.getPrevSibling(), down);
PsiElement toMove = sibling;
if (!(sibling instanceof PsiStatement)) {
return destLine;
}
if (sibling instanceof PsiDeclarationStatement) {
PsiElement[] elements = ((PsiDeclarationStatement)sibling).getDeclaredElements();
if (elements.length == 0) return destLine;
sibling = down ? elements[elements.length - 1] : elements[0];
}
if (sibling instanceof PsiVariable) {
sibling = ((PsiVariable)sibling).getInitializer();
}
if (sibling instanceof PsiExpressionStatement) {
sibling = ((PsiExpressionStatement)sibling).getExpression();
}
if (sibling instanceof PsiNewExpression) {
sibling = ((PsiNewExpression)sibling).getAnonymousClass();
}
if (!(sibling instanceof PsiClass)) return destLine;
destLine = editor.getDocument().getLineNumber(down ? toMove.getTextRange().getEndOffset() : toMove.getTextRange().getStartOffset());
return destLine;
}
private boolean calcInsertOffset(@NotNull PsiFile file, @NotNull Editor editor, @NotNull LineRange range, @NotNull final MoveInfo info, final boolean down) {
int destLine = getDestLineForAnon(file, editor, range, info, down);
int startLine = down ? range.endLine : range.startLine - 1;
if (line < 0 || startLine < 0) return false;
if (destLine < 0 || startLine < 0) return false;
while (true) {
final int offset = editor.logicalPositionToOffset(new LogicalPosition(line, 0));
final int offset = editor.logicalPositionToOffset(new LogicalPosition(destLine, 0));
PsiElement element = firstNonWhiteElement(offset, file, true);
while (element != null && !(element instanceof PsiFile)) {
@@ -133,7 +164,7 @@ class StatementMover extends LineMover {
if (found) {
statementToSurroundWithCodeBlock = elementToSurround;
info.toMove = range;
int endLine = line;
int endLine = destLine;
if (startLine > endLine) {
int tmp = endLine;
endLine = startLine;
@@ -146,8 +177,8 @@ class StatementMover extends LineMover {
}
element = element.getParent();
}
line += down ? 1 : -1;
if (line == 0 || line >= editor.getDocument().getLineCount()) {
destLine += down ? 1 : -1;
if (destLine == 0 || destLine >= editor.getDocument().getLineCount()) {
return false;
}
}
@@ -41,7 +41,8 @@ public class JavaExpressionSurroundDescriptor implements SurroundDescriptor {
new JavaWithNotSurrounder(),
new JavaWithNotInstanceofSurrounder(),
new JavaWithIfExpressionSurrounder(),
new JavaWithIfElseExpressionSurrounder()
new JavaWithIfElseExpressionSurrounder(),
new JavaWithNullCheckSurrounder()
};
@NotNull public PsiElement[] getElementsToSurround(PsiFile file, int startOffset, int endOffset) {
@@ -0,0 +1,66 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.generation.surroundWith;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
class JavaWithNullCheckSurrounder extends JavaExpressionSurrounder{
public boolean isApplicable(PsiExpression expr) {
PsiType type = expr.getType();
if (type instanceof PsiPrimitiveType) return false;
if (!expr.isPhysical()) return false;
if (expr.getParent() instanceof PsiExpressionStatement) return false;
PsiElement parent = PsiTreeUtil.getParentOfType(expr, PsiExpressionStatement.class);
if (parent == null) return false;
final PsiElement element = parent.getParent();
if (!(element instanceof PsiCodeBlock) && !(JspPsiUtil.isInJspFile(element) && element instanceof PsiFile)) return false;
return true;
}
public TextRange surroundExpression(Project project, Editor editor, PsiExpression expr) throws IncorrectOperationException {
PsiManager manager = expr.getManager();
PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
@NonNls String text = "if(a != null){\nst;\n}";
PsiIfStatement ifStatement = (PsiIfStatement)factory.createStatementFromText(text, null);
ifStatement = (PsiIfStatement)codeStyleManager.reformat(ifStatement);
((PsiBinaryExpression)ifStatement.getCondition()).getLOperand().replace(expr);
PsiExpressionStatement statement = PsiTreeUtil.getParentOfType(expr, PsiExpressionStatement.class);
String oldText = statement.getText();
ifStatement = (PsiIfStatement)statement.replace(ifStatement);
PsiCodeBlock block = ((PsiBlockStatement)ifStatement.getThenBranch()).getCodeBlock();
block = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(block);
PsiElement replace = block.getStatements()[0].replace(factory.createStatementFromText(oldText, block));
int offset = replace.getTextRange().getEndOffset();
return new TextRange(offset, offset);
}
public String getTemplateDescription() {
return "if (expr != null) {...}";
}
}
@@ -125,20 +125,18 @@ public class DeannotateIntentionAction implements IntentionAction {
@Override
public void invoke(@NotNull final Project project, Editor editor, final PsiFile file) throws IncorrectOperationException {
final PsiModifierListOwner listOwner = getContainer(editor, file);
LOG.assertTrue(listOwner != null);
final ExternalAnnotationsManager annotationsManager = ExternalAnnotationsManager.getInstance(project);
final PsiAnnotation[] externalAnnotations = annotationsManager.findExternalAnnotations(listOwner);
LOG.assertTrue(externalAnnotations != null && externalAnnotations.length > 0);
if (externalAnnotations.length == 1) {
deannotate(externalAnnotations[0], project, file, annotationsManager, listOwner);
return;
}
JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<PsiAnnotation>(CodeInsightBundle.message("deannotate.intention.chooser.title"), externalAnnotations) {
@Override
public PopupStep onChosen(final PsiAnnotation selectedValue, final boolean finalChoice) {
new WriteCommandAction(project){
@Override
protected void run(final Result result) throws Throwable {
final VirtualFile virtualFile = file.getVirtualFile();
if (annotationsManager.deannotate(listOwner, selectedValue.getQualifiedName()) && virtualFile != null && virtualFile.isInLocalFileSystem()) {
UndoUtil.markPsiFileForUndo(file);
}
}
}.execute();
deannotate(selectedValue, project, file, annotationsManager, listOwner);
return PopupStep.FINAL_CHOICE;
}
@@ -152,6 +150,24 @@ public class DeannotateIntentionAction implements IntentionAction {
}).showInBestPositionFor(editor);
}
private void deannotate(final PsiAnnotation annotation,
final Project project,
final PsiFile file,
final ExternalAnnotationsManager annotationsManager,
final PsiModifierListOwner listOwner) {
new WriteCommandAction(project, getText()) {
@Override
protected void run(final Result result) throws Throwable {
final VirtualFile virtualFile = file.getVirtualFile();
String qualifiedName = annotation.getQualifiedName();
LOG.assertTrue(qualifiedName != null);
if (annotationsManager.deannotate(listOwner, qualifiedName) && virtualFile != null && virtualFile.isInLocalFileSystem()) {
UndoUtil.markPsiFileForUndo(file);
}
}
}.execute();
}
@Override
public boolean startInWriteAction() {
return false;
@@ -26,6 +26,7 @@ package com.intellij.codeInspection.ex;
import com.intellij.ExtensionPoints;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInspection.reference.*;
import com.intellij.codeInspection.util.SpecialAnnotationsUtil;
import com.intellij.ide.DataManager;
@@ -367,6 +368,7 @@ public class EntryPointsManagerImpl implements PersistentStateComponent<Element>
protected void doOKAction() {
ADDITIONAL_ANNOTATIONS.clear();
ADDITIONAL_ANNOTATIONS.addAll(list);
DaemonCodeAnalyzer.getInstance(myProject).restart();
super.doOKAction();
}
}.show();
@@ -357,7 +357,8 @@ public class NullableStuffInspection extends BaseLocalInspectionTool {
if (!manager.isInProject(overriding)) continue;
if (!methodQuickFixSuggested
&& annotated.isDeclaredNotNull
&& !nullableManager.isNotNull(overriding, false)) {
&& !nullableManager.isNotNull(overriding, false)
&& (nullableManager.isNullable(overriding, false) || !nullableManager.isNullable(overriding, true))) {
method.getNameIdentifier(); //load tree
PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, nullableManager.getNotNulls());
final String defaultNotNull = nullableManager.getDefaultNotNull();
@@ -16,6 +16,7 @@
package com.intellij.codeInspection.util;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.InspectionsBundle;
@@ -31,6 +32,7 @@ import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
@@ -216,7 +218,8 @@ public class SpecialAnnotationsUtil {
for (PsiAnnotation psiAnnotation : psiAnnotations) {
@NonNls final String name = psiAnnotation.getQualifiedName();
if (name == null) continue;
if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("org.jetbrains.")) continue;
if (name.startsWith("java.") || name.startsWith("javax.") ||
(name.startsWith("org.jetbrains.") && !AnnotationUtil.isJetbrainsAnnotation(StringUtil.getShortName(name)))) continue;
if (!processor.process(name)) break;
}
}
@@ -167,7 +167,7 @@ public abstract class BaseConvertToLocalQuickFix<V extends PsiVariable> implemen
}
@Nullable
private static PsiAssignmentExpression searchAssignmentExpression(@NotNull PsiElement anchor) {
private static PsiAssignmentExpression searchAssignmentExpression(@Nullable PsiElement anchor) {
if (!(anchor instanceof PsiExpressionStatement)) {
return null;
}
@@ -226,6 +226,7 @@ public abstract class BaseConvertToLocalQuickFix<V extends PsiVariable> implemen
return getName();
}
@Nullable
private static PsiElement getAnchorElement(PsiCodeBlock anchorBlock, @NotNull PsiElement firstElement) {
PsiElement element = firstElement;
while (element != null && element.getParent() != anchorBlock) {
@@ -155,6 +155,13 @@ class DetectedJavaChangeInfo extends JavaChangeInfoImpl {
isReturnTypeChanged = true;
}
}
for (int i = 0, length = Math.min(newParms.length, oldParameterNames.length); i < length; i++) {
ParameterInfoImpl parm = newParms[i];
if (parm.getName().equals(oldParameterNames[i]) && parm.getTypeText().equals(oldParameterTypes[i])) {
parm.oldParameterIndex = i;
}
}
}
};
javaChangeInfo.setSuperMethod(getSuperMethod());
@@ -33,7 +33,7 @@ import java.util.List;
public class ParameterInfoImpl implements JavaParameterInfo {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.changeSignature.ParameterInfoImpl");
public final int oldParameterIndex;
public int oldParameterIndex;
boolean useAnySingleVariable;
private String name = "";
public static final ParameterInfoImpl[] EMPTY_ARRAY = new ParameterInfoImpl[0];
File diff suppressed because it is too large Load Diff
@@ -42,13 +42,16 @@ import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Pass;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.controlFlow.ControlFlowUtil;
import com.intellij.psi.impl.source.codeStyle.JavaCodeStyleManagerImpl;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
@@ -472,7 +475,8 @@ public class ExtractMethodProcessor implements MatchProvider {
protected AbstractExtractDialog createExtractMethodDialog(final boolean direct) {
return new ExtractMethodDialog(myProject, myTargetClass, myInputVariables, myReturnType, myTypeParameterList,
myThrownExceptions, myStatic, myCanBeStatic, myCanBeChainedConstructor, myInitialMethodName,
myThrownExceptions, myStatic, myCanBeStatic, myCanBeChainedConstructor,
suggestInitialMethodName(),
myRefactoringName, myHelpId, myElements) {
protected boolean areTypesDirected() {
return direct;
@@ -485,6 +489,41 @@ public class ExtractMethodProcessor implements MatchProvider {
};
}
protected String suggestInitialMethodName() {
if (StringUtil.isEmpty(myInitialMethodName)) {
final String initialMethodName;
final JavaCodeStyleManagerImpl codeStyleManager = (JavaCodeStyleManagerImpl)JavaCodeStyleManager.getInstance(myProject);
final String[] names = codeStyleManager.suggestVariableName(VariableKind.FIELD, null, myExpression, myReturnType).names;
if (names.length > 0) {
initialMethodName = codeStyleManager.variableNameToPropertyName(names[0], VariableKind.FIELD);
} else {
return myInitialMethodName;
}
if (myReturnType != null && !(myReturnType instanceof PsiPrimitiveType)) {
return PropertyUtil.suggestGetterName(initialMethodName, myReturnType);
} else if (myExpression != null) {
if (myExpression instanceof PsiMethodCallExpression) {
PsiExpression qualifierExpression = ((PsiMethodCallExpression)myExpression).getMethodExpression().getQualifierExpression();
if (qualifierExpression != null && PsiUtil.resolveGenericsClassInType(qualifierExpression.getType()) != myTargetClass) {
return initialMethodName;
}
} else {
return initialMethodName;
}
}
PsiElement prevSibling = PsiTreeUtil.skipSiblingsBackward(myElements[0], PsiWhiteSpace.class);
if (prevSibling instanceof PsiComment && ((PsiComment)prevSibling).getTokenType() == JavaTokenType.END_OF_LINE_COMMENT) {
final String text = prevSibling.getText().trim().replaceAll(" ", "").substring(2);
if (JavaPsiFacade.getInstance(myProject).getNameHelper().isIdentifier(text) && text.length() < 20) {
return text;
}
}
}
return myInitialMethodName;
}
public boolean isOutputVariable(PsiVariable var) {
return ArrayUtil.find(myOutputVariables, var) != -1;
}
@@ -49,6 +49,8 @@ import com.intellij.psi.impl.source.jsp.jspJava.JspCodeBlock;
import com.intellij.psi.impl.source.jsp.jspJava.JspHolderMethod;
import com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy;
import com.intellij.psi.impl.source.tree.java.ReplaceExpressionUtil;
import com.intellij.psi.scope.processor.VariablesProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.util.PsiExpressionTrimRenderer;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
@@ -522,21 +524,9 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase {
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file)) return false;
PsiElement containerParent = tempContainer;
PsiElement lastScope = tempContainer;
while (true) {
if (containerParent instanceof PsiFile) break;
if (containerParent instanceof PsiMethod) break;
containerParent = containerParent.getParent();
if (containerParent instanceof PsiCodeBlock) {
lastScope = containerParent;
}
}
final ExpressionOccurrenceManager occurenceManager = new ExpressionOccurrenceManager(expr, lastScope,
NotInSuperCallOccurrenceFilter.INSTANCE);
final PsiExpression[] occurrences = occurenceManager.getOccurrences();
final PsiElement anchorStatementIfAll = occurenceManager.getAnchorStatementForAll();
final ExpressionOccurrenceManager occurrenceManager = createOccurrenceManager(expr, tempContainer);
final PsiExpression[] occurrences = occurrenceManager.getOccurrences();
final PsiElement anchorStatementIfAll = occurrenceManager.getAnchorStatementForAll();
final LinkedHashMap<OccurrencesChooser.ReplaceChoice, List<PsiExpression>> occurrencesMap = ContainerUtil.newLinkedHashMap();
@@ -550,8 +540,8 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase {
supportProvider.isInplaceIntroduceAvailable(expr, nameSuggestionContext) &&
!ApplicationManager.getApplication().isUnitTestMode() &&
!isInJspHolderMethod(expr);
final boolean inFinalContext = occurenceManager.isInFinalContext();
final InputValidator validator = new InputValidator(this, project, anchorStatementIfAll, anchorStatement, occurenceManager);
final boolean inFinalContext = occurrenceManager.isInFinalContext();
final InputValidator validator = new InputValidator(this, project, anchorStatementIfAll, anchorStatement, occurrenceManager);
final TypeSelectorManagerImpl typeSelectorManager = new TypeSelectorManagerImpl(project, originalType, expr, occurrences);
final boolean[] wasSucceed = new boolean[]{true};
final Pass<OccurrencesChooser.ReplaceChoice> callback = new Pass<OccurrencesChooser.ReplaceChoice>() {
@@ -613,6 +603,35 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase {
return wasSucceed[0];
}
private static ExpressionOccurrenceManager createOccurrenceManager(PsiExpression expr, PsiElement tempContainer) {
boolean skipForStatement = true;
final PsiForStatement forStatement = PsiTreeUtil.getParentOfType(expr, PsiForStatement.class);
if (forStatement != null) {
final VariablesProcessor variablesProcessor = new VariablesProcessor(false) {
@Override
protected boolean check(PsiVariable var, ResolveState state) {
return PsiTreeUtil.isAncestor(forStatement.getInitialization(), var, true);
}
};
PsiScopesUtil.treeWalkUp(variablesProcessor, expr, null);
skipForStatement = variablesProcessor.size() == 0;
}
PsiElement containerParent = tempContainer;
PsiElement lastScope = tempContainer;
while (true) {
if (containerParent instanceof PsiFile) break;
if (containerParent instanceof PsiMethod) break;
if (!skipForStatement && containerParent instanceof PsiForStatement) break;
containerParent = containerParent.getParent();
if (containerParent instanceof PsiCodeBlock) {
lastScope = containerParent;
}
}
return new ExpressionOccurrenceManager(expr, lastScope, NotInSuperCallOccurrenceFilter.INSTANCE);
}
private static boolean isInJspHolderMethod(PsiExpression expr) {
final PsiElement parent1 = expr.getParent();
if (parent1 == null) {
@@ -27,10 +27,12 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.impl.content.BaseLabel;
import com.intellij.psi.*;
import com.intellij.refactoring.util.RefactoringDescriptionLocation;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import java.util.regex.Pattern;
@@ -118,7 +120,7 @@ public class SliceManager implements PersistentStateComponent<SliceManager.Store
public void slice(@NotNull PsiElement element, boolean dataFlowToThis, SliceHandler handler) {
String dialogTitle = getElementDescription((dataFlowToThis ? BACK_TOOLWINDOW_ID : FORTH_TOOLWINDOW_ID) + " ", element, null);
dialogTitle = Pattern.compile("<[^<>]*>").matcher(dialogTitle).replaceAll("");
dialogTitle = Pattern.compile("(<style>.*</style>)|<[^<>]*>").matcher(dialogTitle).replaceAll("");
SliceAnalysisParams params = handler.askForParams(element, dataFlowToThis, myStoredSettings, dialogTitle);
if (params == null) return;
@@ -172,7 +174,9 @@ public class SliceManager implements PersistentStateComponent<SliceManager.Store
if (element instanceof PsiReferenceExpression) elementToSlice = ((PsiReferenceExpression)element).resolve();
if (elementToSlice == null) elementToSlice = element;
String desc = ElementDescriptionUtil.getElementDescription(elementToSlice, RefactoringDescriptionLocation.WITHOUT_PARENT);
return "<html>"+ (prefix == null ? "" : prefix) + StringUtil.first(desc, 100, true)+(suffix == null ? "" : suffix) + "</html>";
return "<html><head>" + UIUtil.getCssFontDeclaration(BaseLabel.getLabelFont()) + "</head><body>" +
(prefix == null ? "" : prefix) + StringUtil.first(desc, 100, true)+(suffix == null ? "" : suffix) +
"</body></html>";
}
public static SliceUsage createRootUsage(@NotNull PsiElement element, @NotNull SliceAnalysisParams params) {