cleaning up and formatting

This commit is contained in:
Ben Fry
2015-04-14 19:40:31 -04:00
parent c64b39b2b5
commit 59d32321fd
3 changed files with 163 additions and 195 deletions

View File

@@ -33,7 +33,6 @@ import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
@@ -42,7 +41,6 @@ import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.Painter;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
@@ -51,7 +49,6 @@ import javax.swing.plaf.basic.BasicScrollBarUI;
import javax.swing.text.BadLocationException;
import processing.app.Base;
import processing.app.Mode;
import processing.app.syntax.JEditTextArea;
import processing.mode.java.JavaEditor;
import processing.mode.java.JavaMode;
@@ -62,7 +59,7 @@ import processing.mode.java.JavaMode;
* @author Manindra Moharana <me@mkmoharana.com>
*/
public class CompletionPanel {
/**
* The completion list generated by ASTGenerator
*/
@@ -89,10 +86,13 @@ public class CompletionPanel {
* Scroll pane in which the completion list is displayed
*/
private JScrollPane scrollPane;
protected JavaEditor editor;
public static final int MOUSE_COMPLETION = 10, KEYBOARD_COMPLETION = 20;
static protected final int MOUSE_COMPLETION = 10, KEYBOARD_COMPLETION = 20;
private boolean horizontalScrollBarVisible = false;
/**
* Triggers the completion popup
@@ -123,12 +123,11 @@ public class CompletionPanel {
popupMenu.setPopupSize(calcWidth(), calcHeight(items.getSize())); //TODO: Eradicate this evil
this.textarea.errorCheckerService.getASTGenerator().updateJavaDoc(completionList.getSelectedValue());
textarea.requestFocusInWindow();
popupMenu.show(textarea, location.x, textarea.getBaseline(0, 0)
+ location.y);
popupMenu.show(textarea, location.x, textarea.getBaseline(0, 0) + location.y);
//log("Suggestion shown: " + System.currentTimeMillis());
}
private void styleScrollPane() {
String laf = UIManager.getLookAndFeel().getID();
if (!laf.equals("Nimbus") && !laf.equals("Windows")) return;
@@ -153,7 +152,8 @@ public class CompletionPanel {
scrollPane.getVerticalScrollBar().setUI(new CompletionScrollBarUI(thumbColor));
}
public static class CompletionScrollBarUI extends BasicScrollBarUI {
private static class CompletionScrollBarUI extends BasicScrollBarUI {
private String thumbColorName;
protected CompletionScrollBarUI(String thumbColorName) {
@@ -185,48 +185,49 @@ public class CompletionPanel {
}
}
public boolean isVisible() {
return popupMenu.isVisible();
}
public void setVisible(boolean v){
//log("Pred popup visible.");
popupMenu.setVisible(v);
public void setInvisible() {
popupMenu.setVisible(false);
}
/**
* Dynamic height of completion panel depending on item count
* @param itemCount
* @return - height
*/
private int calcHeight(int itemCount) {
int maxHeight = 250;
FontMetrics fm = textarea.getGraphics().getFontMetrics();
float itemHeight = Math.max((fm.getHeight() + (fm.getDescent()) * 0.5f),
JavaMode.classIcon.getIconHeight() * 1.2f);
if (horizontalScrollBarVisible)
itemCount++;
if (itemCount < 4)
if (horizontalScrollBarVisible) {
itemCount++;
}
if (itemCount < 4) {
itemHeight *= 1.3f; //Sorry, but it works.
}
float h = itemHeight * (itemCount);
if (itemCount >= 4)
if (itemCount >= 4) {
h += itemHeight * 0.3; // a bit of offset
}
return Math.min(maxHeight, (int) h); // popup menu height
}
private boolean horizontalScrollBarVisible = false;
/**
* Dynamic width of completion panel
* @return - width
*/
private int calcWidth() {
horizontalScrollBarVisible = false;
int maxWidth = 300;
float min = 0;
FontMetrics fm = textarea.getGraphics().getFontMetrics();
@@ -235,16 +236,16 @@ public class CompletionPanel {
min = Math.max(min, h);
}
int w = Math.min((int) min, maxWidth);
if(w == maxWidth)
horizontalScrollBarVisible = true;
horizontalScrollBarVisible = (w == maxWidth);
w += JavaMode.classIcon.getIconWidth(); // add icon width too!
w += fm.stringWidth(" "); // a bit of offset
//log("popup width " + w);
return w; // popup menu width
}
/**
* Created the popup list to be displayed
* Created the popup list to be displayed
* @param position
* @param items
* @return
@@ -261,7 +262,7 @@ public class CompletionPanel {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
insertSelection(MOUSE_COMPLETION);
hide();
setInvisible();
}
}
});
@@ -269,9 +270,11 @@ public class CompletionPanel {
list.setFocusable(false);
return list;
}
/*
// possibly defunct
public boolean updateList(final DefaultListModel<CompletionCandidate> items, String newSubword,
private boolean updateList(final DefaultListModel<CompletionCandidate> items, String newSubword,
final Point location, int position) {
this.subWord = new String(newSubword);
if (subWord.indexOf('.') != -1)
@@ -296,13 +299,15 @@ public class CompletionPanel {
});
return true;
}
*/
/**
* Inserts the CompletionCandidate chosen from the suggestion list
* @param completionSource - whether being completed via keypress or mouse click.
* @return true - if code was successfully inserted at the caret position
*/
public boolean insertSelection(int completionSource) {
protected boolean insertSelection(int completionSource) {
if (completionList.getSelectedValue() != null) {
try {
// If user types 'abc.', subword becomes '.' and null is returned
@@ -310,16 +315,16 @@ public class CompletionPanel {
int currentSubwordLen = currentSubword == null ? 0 : currentSubword
.length();
//logE(currentSubword + " <= subword,len => " + currentSubword.length());
String selectedSuggestion =
String selectedSuggestion =
completionList.getSelectedValue().getCompletionString();
if (currentSubword != null) {
selectedSuggestion = selectedSuggestion.substring(currentSubwordLen);
} else {
currentSubword = "";
}
String completionString =
String completionString =
completionList.getSelectedValue().getCompletionString();
if (selectedSuggestion.endsWith(" )")) { // the case of single param methods
// selectedSuggestion = ")";
@@ -329,7 +334,7 @@ public class CompletionPanel {
+ ")";
}
}
boolean mouseClickOnOverloadedMethods = false;
if (completionSource == MOUSE_COMPLETION) {
// The case of overloaded methods, displayed as 'foo(...)'
@@ -338,14 +343,14 @@ public class CompletionPanel {
mouseClickOnOverloadedMethods = true;
}
}
Base.loge(subWord + " <= subword, Inserting suggestion=> "
+ selectedSuggestion + " Current sub: " + currentSubword);
if (currentSubword.length() > 0) {
textarea.getDocument().remove(insertionPosition - currentSubwordLen,
currentSubwordLen);
}
textarea.getDocument()
.insertString(insertionPosition - currentSubwordLen,
completionString, null);
@@ -359,38 +364,39 @@ public class CompletionPanel {
textarea.setCaretPosition(insertionPosition + x);
}
}
Base.log("Suggestion inserted: " + System.currentTimeMillis());
if (completionList.getSelectedValue().getLabel().contains("...")) {
// log("No hide");
// log("No hide");
// Why not hide it? Coz this is the case of
// overloaded methods. See #2755
} else {
hide();
setInvisible();
}
if(mouseClickOnOverloadedMethods) {
// See #2755
SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
((JavaTextArea) editor.getTextArea()).fetchPhrase(null);
((JavaTextArea) editor.getTextArea()).fetchPhrase(null);
return null;
}
};
worker.execute();
}
return true;
} catch (BadLocationException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
hide();
setInvisible();
}
return false;
}
private String fetchCurrentSubword() {
//log("Entering fetchCurrentSubword");
JEditTextArea ta = editor.getTextArea();
@@ -409,7 +415,7 @@ public class CompletionPanel {
if (x >= s.length() || x < 0)
return null; //TODO: Does this check cause problems? Verify.
if (Base.DEBUG) System.out.print(" x char: " + s.charAt(x));
//int xLS = off - getLineStartNonWhiteSpaceOffset(line);
//int xLS = off - getLineStartNonWhiteSpaceOffset(line);
String word = (x < s.length() ? s.charAt(x) : "") + "";
if (s.trim().length() == 1) {
@@ -419,7 +425,7 @@ public class CompletionPanel {
word = word.trim();
if (word.endsWith("."))
word = word.substring(0, word.length() - 1);
return word;
}
//log("fetchCurrentSubword 1 " + word);
@@ -463,80 +469,60 @@ public class CompletionPanel {
//}
}
/**
* Hide the suggestion list
*/
public void hide() {
popupMenu.setVisible(false);
//log("Suggestion hidden" + System.nanoTime());
//textarea.errorCheckerService.getASTGenerator().jdocWindowVisible(false);
}
/**
* When up arrow key is pressed, moves the highlighted selection up in the list
*/
public void moveUp() {
protected void moveUp() {
if (completionList.getSelectedIndex() == 0) {
scrollPane.getVerticalScrollBar().setValue(scrollPane.getVerticalScrollBar().getMaximum());
selectIndex(completionList.getModel().getSize() - 1);
return;
} else {
int index = Math.max(completionList.getSelectedIndex() - 1, 0);
selectIndex(index);
int step = scrollPane.getVerticalScrollBar().getMaximum()
/ completionList.getModel().getSize();
scrollPane.getVerticalScrollBar().setValue(scrollPane
.getVerticalScrollBar()
.getValue()
- step);
textarea.errorCheckerService.getASTGenerator().updateJavaDoc(completionList.getSelectedValue());
}
int step = scrollPane.getVerticalScrollBar().getMaximum()
/ completionList.getModel().getSize();
scrollPane.getVerticalScrollBar().setValue(scrollPane
.getVerticalScrollBar()
.getValue()
- step);
textarea.errorCheckerService.getASTGenerator().updateJavaDoc(completionList.getSelectedValue());
}
/**
* When down arrow key is pressed, moves the highlighted selection down in the list
*/
public void moveDown() {
protected void moveDown() {
if (completionList.getSelectedIndex() == completionList.getModel().getSize() - 1) {
scrollPane.getVerticalScrollBar().setValue(0);
selectIndex(0);
return;
} else {
int index = Math.min(completionList.getSelectedIndex() + 1, completionList.getModel()
.getSize() - 1);
int index = Math.min(completionList.getSelectedIndex() + 1,
completionList.getModel().getSize() - 1);
selectIndex(index);
textarea.errorCheckerService.getASTGenerator().updateJavaDoc(completionList.getSelectedValue());
int step = scrollPane.getVerticalScrollBar().getMaximum() / completionList.getModel().getSize();
scrollPane.getVerticalScrollBar().setValue(scrollPane.getVerticalScrollBar().getValue() + step);
}
textarea.errorCheckerService.getASTGenerator().updateJavaDoc(completionList.getSelectedValue());
int step = scrollPane.getVerticalScrollBar().getMaximum()
/ completionList.getModel().getSize();
scrollPane.getVerticalScrollBar().setValue(scrollPane
.getVerticalScrollBar()
.getValue()
+ step);
}
private void selectIndex(int index) {
completionList.setSelectedIndex(index);
// final int position = textarea.getCaretPosition();
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
// textarea.setCaretPosition(position);
// };
// });
}
/**
* Custom cell renderer to display icons along with the completion candidates
* Custom cell renderer to display icons along with the completion candidates
* @author Manindra Moharana <me@mkmoharana.com>
*
*/
private class CustomListRenderer extends
javax.swing.DefaultListCellRenderer {
//protected final ImageIcon classIcon, fieldIcon, methodIcon;
private static class CustomListRenderer extends javax.swing.DefaultListCellRenderer {
public Component getListCellRendererComponent(JList<?> list, Object value,
int index,
boolean isSelected,

View File

@@ -28,9 +28,9 @@ import java.util.TreeMap;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblem;
import processing.app.Base;
import processing.app.Language;
public class ErrorMessageSimplifier {
/**
* Mapping between ProblemID constant and the constant name. Holds about 650
@@ -41,6 +41,7 @@ public class ErrorMessageSimplifier {
*/
private static TreeMap<Integer, String> constantsMap;
public ErrorMessageSimplifier() {
new Thread() {
@@ -50,6 +51,7 @@ public class ErrorMessageSimplifier {
}.start();
}
private static void prepareConstantsList() {
constantsMap = new TreeMap<Integer, String>();
Class<DefaultProblem> probClass = DefaultProblem.class;
@@ -70,22 +72,21 @@ public class ErrorMessageSimplifier {
//System.out.println("Total items: " + constantsMap.size());
}
public static String getIDName(int id) {
if (constantsMap == null){
prepareConstantsList();
}
return constantsMap.get(id);
}
/**
* Tones down the jargon in the ecj reported errors.
*
* @param problem
* @return
* Tones down the jargon in the ecj reported errors.
*/
public static String getSimplifiedErrorMessage(Problem problem) {
if (problem == null)
return null;
if (problem == null) return null;
IProblem iprob = problem.getIProblem();
String args[] = iprob.getArguments();
// Base.log("Simplifying message: " + problem.getMessage() + " ID: "
@@ -96,56 +97,54 @@ public class ErrorMessageSimplifier {
// }
String result = null;
switch (iprob.getID()) {
case IProblem.ParsingError:
if (args.length > 0) {
result = Language.text("editor.status.error_on") + " \"" + args[0]
+ "\"";
result = Language.text("editor.status.error_on") + qs(args[0]);
}
break;
case IProblem.ParsingErrorDeleteToken:
if (args.length > 0) {
result = Language.text("editor.status.error_on") + " \"" + args[0]
+ "\"";
result = Language.text("editor.status.error_on") + qs(args[0]);
}
break;
case IProblem.ParsingErrorInsertToComplete:
if (args.length > 0) {
if (args[0].length() == 1) {
result = getErrorMessageForBracket(args[0].charAt(0));
}
else {
if(args[0].equals("AssignmentOperator Expression")){
result = Language.text("editor.status.missing.add") + " \"=\"";
}
else if (args[0].equalsIgnoreCase(") Statement")){
} else {
if (args[0].equals("AssignmentOperator Expression")) {
result = Language.text("editor.status.missing.add") + qs("=");
} else if (args[0].equalsIgnoreCase(") Statement")) {
result = getErrorMessageForBracket(args[0].charAt(0));
}
else {
result = Language.text("editor.status.error_on") + " \"" + args[0]
+ "\"";
} else {
result = Language.text("editor.status.error_on") + qs(args[0]);
}
}
}
break;
case IProblem.ParsingErrorInvalidToken:
if (args.length > 0) {
if (args[1].equals("VariableDeclaratorId")) {
if(args[0].equals("int")) {
if (args[0].equals("int")) {
result = Language.text ("editor.status.reserved_words");
} else {
result = Language.text("editor.status.error_on") + qs(args[0]);
}
else {
result = Language.text("editor.status.error_on") + " \""
+ args[0] + "\"";
}
}
else {
result = Language.text("editor.status.error_on") + " \"" + args[0]
+ "\"";
} else {
result = Language.text("editor.status.error_on") + qs(args[0]);
}
}
break;
case IProblem.ParsingErrorInsertTokenAfter:
if (args.length > 0) {
if (args[1].length() == 1) {
@@ -153,17 +152,16 @@ public class ErrorMessageSimplifier {
}
else {
if(args[1].equalsIgnoreCase("Statement")){ // See #3104
result = Language.text("editor.status.error_on") + " \""
+ args[0] + "\"";
result = Language.text("editor.status.error_on") + qs(args[0]);
}
else {
result = Language.text("editor.status.error_on") + " \""
+ args[0] + Language.text("editor.status.missing.add") + args[1]
+ "\"";
result = Language.text("editor.status.error_on") +
" \"" + args[0] + Language.text("editor.status.missing.add") + args[1] + "\"";
}
}
}
break;
case IProblem.UndefinedMethod:
if (args.length > 2) {
result = Language.text("editor.status.undefined_method");
@@ -172,6 +170,7 @@ public class ErrorMessageSimplifier {
result = result.replace("methoddef", methodDef);
}
break;
case IProblem.ParameterMismatch:
if (args.length > 3) {
// 2nd arg is method name, 3rd arg is correct param list
@@ -180,71 +179,67 @@ public class ErrorMessageSimplifier {
result = Language.text("editor.status.empty_param");
String methodDef = "\"" + args[1] + "()\"";
result = result.replace("methoddef", methodDef);
} else {
result = Language.text("editor.status.wrong_param");
String method = "\"" + args[1] + "\"";
String methodDef = " \"" + args[1] + "(" + getSimpleName(args[2])
+ ")\"";
String method = q(args[1]);
String methodDef = " \"" + args[1] + "(" + getSimpleName(args[2]) + ")\"";
result = result.replace("method", method);
result += methodDef;
}
}
break;
case IProblem.UndefinedField:
if (args.length > 0) {
result = Language.text("editor.status.undef_global_var");
String variableName = "\"" + args[0] + "\"";
result = result.replace("varname", variableName);
result = result.replace("varname", q(args[0]));
}
break;
case IProblem.UndefinedType:
if (args.length > 0) {
String className = "\"" + args[0] + "\"";
result = Language.text("editor.status.undef_class");
result = result.replace("classname", className);
result = result.replace("classname", q(args[0]));
}
break;
case IProblem.UnresolvedVariable:
if (args.length > 0) {
String variableName = "\"" + args[0] + "\"";
result = Language.text("editor.status.undef_var");
result = result.replace("varname", variableName);
result = result.replace("varname", q(args[0]));
}
break;
case IProblem.UndefinedName:
if (args.length > 0) {
String name = "\"" + args[0] + "\"";
result = Language.text("editor.status.undef_name");
result = result.replace("namefield", name);
result = result.replace("namefield", q(args[0]));
}
break;
case IProblem.TypeMismatch:
if (args.length > 1) {
String typeA = "\"" + args[0] + "\"";
String typeB = "\"" + args[1] + "\"";
result = Language.text("editor.status.type_mismatch");
result = result.replace("typeA", typeA);
result = result.replace("typeB", typeB);
result = result.replace("typeA", q(args[0]));
result = result.replace("typeB", q(args[1]));
}
break;
}
// log("Simplified Error Msg: " + result);
if (result == null)
result = problem.getMessage();
return result;
//log("Simplified Error Msg: " + result);
return (result == null) ? problem.getMessage() : result;
}
/**
* Converts java.lang.String into String, etc
*
* @param inp
* @return
*/
private static String getSimpleName(String inp) {
if (inp.indexOf('.') < 0)
static private String getSimpleName(String inp) {
if (inp.indexOf('.') < 0) {
return inp;
}
String res = "";
ArrayList<String> names = new ArrayList<String>();
if (inp.indexOf(',') >= 0) {
@@ -252,8 +247,9 @@ public class ErrorMessageSimplifier {
for (int i = 0; i < arr.length; i++) {
names.add(arr[i]);
}
} else
} else {
names.add(inp);
}
for (String n : names) {
int x = n.lastIndexOf('.');
if (x >= 0) {
@@ -263,42 +259,28 @@ public class ErrorMessageSimplifier {
}
return res.substring(2, res.length());
}
private static String getErrorMessageForBracket(char c){
String result = null;
static private String getErrorMessageForBracket(char c) {
switch (c) {
case ';':
result = Language.text("editor.status.missing.semi_colon") + " \";\"";
break;
case '[':
result = Language.text("editor.status.missing.open_sq_bracket") +
" \"[\"";
break;
case ']':
result = Language.text("editor.status.missing.closing_sq_bracket") +
" \"]\"";
break;
case '(':
result = Language.text("editor.status.missing.open_paren") + " \"(\"";
break;
case ')':
result = Language.text("editor.status.missing.close_paren") + " \")\"";
break;
case '{':
result = Language.text("editor.status.missing.open_curly_bracket") +
" \"{\"";
break;
case '}':
result = Language.text("editor.status.missing.closing_curly_bracket") +
" \"}\"";
break;
default:
result = Language.text("editor.status.missing.default") + " \"" + c +
"\"";
case ';': return Language.text("editor.status.missing.semi_colon") + qs(";");
case '[': return Language.text("editor.status.missing.open_sq_bracket") + qs("[");
case ']': return Language.text("editor.status.missing.closing_sq_bracket") + qs("]");
case '(': return Language.text("editor.status.missing.open_paren") + qs("(");
case ')': return Language.text("editor.status.missing.close_paren") + qs(")");
case '{': return Language.text("editor.status.missing.open_curly_bracket") + qs("{");
case '}': return Language.text("editor.status.missing.closing_curly_bracket") + qs("}");
}
return result;
return Language.text("editor.status.missing.default") + qs(c);
}
static private final String q(Object quotable) {
return "\"" + quotable + "\"";
}
static private final String qs(Object quotable) {
return " " + q(quotable);
}
}

View File

@@ -210,7 +210,7 @@ public class JavaTextArea extends JEditTextArea {
if (suggestion != null)
if (suggestion.isVisible()) {
Base.log("Space bar, hide completion list");
suggestion.hide();
suggestion.setInvisible();
}
break;
default:
@@ -836,7 +836,7 @@ public class JavaTextArea extends JEditTextArea {
/** Hides suggestion popup */
public void hideSuggestion() {
if (suggestion != null) {
suggestion.hide();
suggestion.setInvisible();
//log("Suggestion hidden.");
suggestion = null;
}