001: package org.acm.seguin.completer;
002:
003: /*
004: * Copyright (c) 2002, Beau Tateyama
005: *
006: * This program is free software; you can redistribute it and/or
007: * modify it under the terms of the GNU General Public License
008: * as published by the Free Software Foundation; either version 2
009: * of the License, or any later version.
010: *
011: * This program is distributed in the hope that it will be useful,
012: * but WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014: * GNU General Public License for more details.
015: *
016: * You should have received a copy of the GNU General Public License
017: * along with this program; if not, write to the Free Software
018: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
019: */
020: //import anthelper.ui.ClassBrowserPanel;
021: //import anthelper.ui.ClassInfoDialog;
022: //import anthelper.ui.ClassSelectionDialog;
023: //import anthelper.utils.JEditLogger;
024: //import anthelper.utils.SrcInfoUtils;
025: import java.awt.Frame;
026: import java.io.File;
027: import java.io.FilenameFilter;
028: import java.util.ArrayList;
029: import java.util.Collections;
030: import java.util.Iterator;
031: import java.util.List;
032: import java.util.Set;
033: import java.util.StringTokenizer;
034: import java.util.TreeSet;
035: import javax.swing.JOptionPane;
036: import org.gjt.sp.jedit.Macros;
037: import org.gjt.sp.jedit.View;
038: import org.gjt.sp.jedit.gui.DockableWindowManager;
039: import org.gjt.sp.jedit.jEdit;
040: import org.gjt.sp.jedit.search.CurrentBufferSet;
041: import org.gjt.sp.jedit.search.SearchAndReplace;
042: import org.gjt.sp.jedit.search.SearchFileSet;
043: import org.gjt.sp.jedit.textarea.JEditTextArea;
044: import org.gjt.sp.jedit.textarea.Selection;
045: import org.acm.seguin.ide.jedit.Navigator;
046:
047: /**
048: * Description of the Class
049: *
050: * @author btateyama@yahoo.com
051: * @created September 12, 2002
052: */
053: public class JavaUtils {
054: final static Navigator.NavigatorLogger logger = Completer
055: .getLogger(ClassPathSrcMgr.class);
056:
057: /**
058: * View class info in a ClassInfoDialog
059: *
060: * @param argView Description of the Parameter
061: */
062: /*
063: public static void viewClassInfo(View argView) {
064: // try to select word first...if nothing found, use enclosing class name
065: JEditTextArea textArea = argView.getTextArea();
066: int iPos = textArea.getCaretPosition();
067: textArea.selectWord();
068: String strClassName = textArea.getSelectedText();
069: textArea.setCaretPosition(iPos);
070:
071: if (strClassName == null || strClassName.trim().equals("")){
072: strClassName = SrcInfoUtils.getClassName(argView);
073: }
074: //strClassName.
075: String strClass = selectClass(argView, strClassName, false);
076: if (strClass != null && !strClass.equals("")) {
077: viewClassInfo(argView, strClass);
078: }
079: }
080: */
081:
082: /**
083: * View class info in a ClassInfoDialog
084: *
085: * @param argClassName Description of the Parameter
086: * @param argParent Description of the Parameter
087: */
088: /*
089: public static void viewClassInfo(Frame argParent, String argClassName) {
090: try {
091: View view = (argParent instanceof View ?
092: (View) argParent :
093: jEdit.getActiveView());
094: DockableWindowManager winMgr = view.getDockableWindowManager();
095: if (!winMgr.isDockableWindowVisible(AntHelperPlugin.DOCKABLE_NAME)){
096: winMgr.toggleDockableWindow(AntHelperPlugin.DOCKABLE_NAME);
097: }
098:
099: ClassBrowserPanel panelCB =
100: (ClassBrowserPanel) winMgr.getDockableWindow(AntHelperPlugin.DOCKABLE_NAME);
101: panelCB.setSelectedClass(argClassName);
102: //ClassInfoDialog cid = new ClassInfoDialog(argParent, argClassName, true);
103: //cid.show();
104: } catch (Exception e) {
105: logger.error("Could not view class info for (" + argClassName + ")", e);
106: }
107: }
108: */
109: /**
110: * Select the full class name (or package) from the partial class name.
111: * (i.e. java.util.Vector from Vector) Uses the java.class.path
112: *
113: * @param argView Description of the Parameter
114: * @param argIncludePackages Description of the Parameter
115: * @param argClassName Description of the Parameter
116: * @return Description of the Return Value
117: */
118: public static String selectClass(View argView, String argClassName,
119: boolean argIncludePackages) {
120: String strClass = null;
121: Context context = ContextMgr.getContext(argView);
122: if (context != null) {
123: // get selected word
124: JEditTextArea textArea = argView.getTextArea();
125: String strClassName = argClassName == null ? extractClassNameFromTextArea(textArea)
126: : argClassName;
127: strClass = selectClass(argView, strClassName, context
128: .getClassNameCache(), argIncludePackages);
129: }
130: return strClass;
131: }
132:
133: /**
134: * Select the full class name (or package) from the partial class name.
135: * (i.e. java.util.Vector from Vector) Uses the java.class.path
136: *
137: * @param argParent Description of the Parameter
138: * @param argClassName Description of the Parameter
139: * @param argIncludePackages Description of the Parameter
140: * @return Description of the Return Value
141: */
142: public static String selectClass(Frame argParent,
143: String argClassName, boolean argIncludePackages) {
144: return selectClass(argParent, argClassName, System
145: .getProperty("java.class.path"), argIncludePackages);
146: }
147:
148: /**
149: * Select the full class name (or package) from the partial class name.
150: * (i.e. java.util.Vector from Vector) Uses the given ClassNameCache
151: *
152: * @param argParent Description of the Parameter
153: * @param argClassName Description of the Parameter
154: * @param argClassPath Description of the Parameter
155: * @param argIncludePackages Description of the Parameter
156: * @return Description of the Return Value
157: */
158: public static String selectClass(Frame argParent,
159: String argClassName, String argClassPath,
160: boolean argIncludePackages) {
161: return selectClass(argParent, argClassName, new ClassNameCache(
162: argClassPath), argIncludePackages);
163: }
164:
165: /**
166: * Select the full class name (or package) from the partial class name.
167: * (i.e. java.util.Vector from Vector)
168: *
169: * @param argParent Description of the Parameter
170: * @param argClassName Description of the Parameter
171: * @param argCnc Description of the Parameter
172: * @param argIncludePackages Description of the Parameter
173: * @return Description of the Return Value
174: */
175: public static String selectClass(Frame argParent,
176: String argClassName, ClassNameCache argCnc,
177: boolean argIncludePackages) {
178:
179: String strSelectedVal = null;
180:
181: String strClassName = argClassName == null ? "" : argClassName;
182:
183: // first, optimistically, check to see if the class is found
184: Set setClasses = argCnc.getClassListForClassName(strClassName);
185: String strMsg = null;
186: if (setClasses == null || setClasses.size() == 0) {
187: if (strClassName.equals("")) {
188: // nothing inputted
189: strMsg = "";
190: } else if (strClassName.indexOf(".") != -1) {
191: // a full class name was sent
192: strMsg = "";
193: } else {
194: // some kind of class fragment/name inputted
195: strMsg = "No Classes found.";
196: }
197: setClasses = setClasses == null ? new TreeSet()
198: : setClasses;
199: } else if (setClasses.size() == 1) {
200: strMsg = "1 class found.";
201: strClassName = setClasses.iterator().next().toString();
202: } else {
203: strMsg = setClasses.size() + " classes found.";
204: }
205:
206: // now ask for user input to verify the class
207: // strClassName = JOptionPane.showInputDialog(argParent, "",
208: // "Enter class to import\n" + strMsg, strClassName);
209: strClassName = Macros.input(argParent, "Input class name:\n"
210: + strMsg, strClassName);
211: logger.msg("class", (String) strClassName);
212:
213: // check result
214: if (strClassName == null || strClassName.equals("")) {
215: logger.msg("No class input, exiting...");
216: } else if (strClassName.endsWith(".*")) {
217: logger.msg("Package import", strClassName);
218: strSelectedVal = strClassName;
219: } else if (strClassName.indexOf(".") > -1) {
220: logger.msg("Full class name found", strClassName);
221: strSelectedVal = strClassName;
222: } else {
223: // display dialog to select the class from a list
224: setClasses = argCnc.getClassListForClassName(strClassName);
225: setClasses = setClasses == null ? new TreeSet()
226: : setClasses;
227: logger.msg(setClasses.size() + " classes found.");
228:
229: // add package level imports, if desired, then class itself
230: if (argIncludePackages) {
231: addPackageImports(setClasses);
232: }
233:
234: // display the 2nd dialog
235: //FIXME: ClassSelectionDialog csd = new ClassSelectionDialog(argParent, strClassName, setClasses);
236: //FIXME: csd.show();
237: //FIXME: if (csd.getReturnVal() == null) {
238: //FIXME: logger.msg("Cancel import request of (" + strClassName + ")");
239: //FIXME: } else {
240: //FIXME: strSelectedVal = (String) csd.getReturnVal();
241: //FIXME: }
242: }
243: return strSelectedVal;
244: }
245:
246: /**
247: * Import a class.
248: *
249: * @param argView Description of the Parameter
250: */
251: public static void importClass(View argView) {
252: importClass(argView, null);
253: }
254:
255: /**
256: * Bring up import class dialogs to import a class.
257: * the provided class name, argClassName, will be used
258: * as an initial guess for the class name. null may be used
259: * when no guess is available.
260: *
261: * @param argView Description of the Parameter
262: * @param argClassName Description of the Parameter
263: */
264: public static void importClass(View argView, String argClassName) {
265: String strImport = selectClass(argView, argClassName, true);
266: if (strImport != null && !strImport.equals("")) {
267: doImport(argView, strImport);
268: }
269: }
270:
271: /**
272: * Adds a feature to the PackageImports attribute of the JavaUtils class
273: *
274: * @param argClasses The feature to be added to the PackageImports
275: * attribute
276: */
277: static void addPackageImports(Set argClasses) {
278: String strVal = null;
279: int iDot = -1;
280: Set setPackageImports = new TreeSet();
281: for (Iterator it = argClasses.iterator(); it.hasNext();) {
282: strVal = it.next().toString();
283: iDot = strVal.lastIndexOf(".");
284: if (iDot != -1) {
285: setPackageImports.add(strVal.substring(0, iDot + 1)
286: + "*");
287: }
288: }
289: argClasses.addAll(setPackageImports);
290: }
291:
292: /**
293: * Gets the className attribute of the JavaUtils class
294: *
295: * @param arg Description of the Parameter
296: * @return The className value
297: */
298: static boolean isClassName(String arg) {
299: if (arg == null || arg.equals(".")) {
300: return false;
301: }
302: boolean bRes = true;
303: char c;
304: for (int i = 0; i < arg.length(); i++) {
305: c = arg.charAt(i);
306: if ((0 == i && !Character.isJavaIdentifierStart(c))
307: || !Character.isJavaIdentifierPart(c)) {
308: bRes = false;
309: break;
310: }
311: }
312: return bRes;
313: }
314:
315: /**
316: * Description of the Method
317: *
318: * @param arg Description of the Parameter
319: * @return Description of the Return Value
320: */
321: static String filterTag(String arg) {
322: if (arg == null || arg.trim().equals("")
323: || !isClassName(arg.trim())) {
324: return "";
325: } else {
326: return arg.trim();
327: }
328: }
329:
330: /**
331: * Description of the Method
332: *
333: * @param argTextArea Description of the Parameter
334: * @return Description of the Return Value
335: */
336: static String extractClassNameFromTextArea(JEditTextArea argTextArea) {
337: // get the selected word
338:
339: int iOldPos = argTextArea.getCaretPosition();
340: // get selection, if any exists
341: String strClass = argTextArea.getSelectedText();
342: if (strClass == null) {
343: // no selected text so select word
344: argTextArea.selectWord();
345: strClass = argTextArea.getSelectedText();
346: }
347: argTextArea.setCaretPosition(iOldPos);
348: return filterTag(strClass);
349: }
350:
351: /**
352: * Gets the simpleName attribute of the JavaUtils object
353: *
354: * @param className Description of the Parameter
355: * @return The simpleName value
356: */
357: String getSimpleName(String className) {
358: int i = className.lastIndexOf('$');
359: int j = className.lastIndexOf('.');
360:
361: return className.substring(Math.max(i, j) + 1);
362: }
363:
364: /**
365: * Description of the Method
366: *
367: * @param argView Description of the Parameter
368: * @param argClassToImport Description of the Parameter
369: */
370: public static void doImport(View argView, String argClassToImport) {
371: JEditTextArea textArea = argView.getTextArea();
372: argView.getBuffer().addMarker('i', textArea.getCaretPosition());
373:
374: textArea.setCaretPosition(0);
375:
376: SearchAndReplaceOriginalValuesHolder orgValuesHolder = new SearchAndReplaceOriginalValuesHolder();
377:
378: SearchAndReplace.setAutoWrapAround(true);
379: SearchAndReplace.setReverseSearch(false);
380: SearchAndReplace.setIgnoreCase(false);
381: SearchAndReplace.setRegexp(true);
382: SearchAndReplace.setSearchString("^package .*;$");
383: SearchAndReplace.setSearchFileSet(new CurrentBufferSet());
384:
385: String strResult = "import " + argClassToImport + ";";
386: boolean bPackageFound = SearchAndReplace.find(argView);
387: if (bPackageFound) {
388: // if package is found...
389: textArea.goToStartOfWhiteSpace(false);
390: textArea.goToNextLine(false);
391: //textArea.setSelectedText("\n");// + strResult);
392: } else {
393: // move to import of it exists, else will be at top anyway;
394: textArea.setCaretPosition(0);
395: }
396:
397: SearchAndReplace.setSearchString("^import .*;$");
398: if (!SearchAndReplace.find(argView) && bPackageFound) {
399: // if no import found
400: strResult = "\n" + strResult;
401: }
402: textArea.goToStartOfWhiteSpace(false);
403: textArea.setSelectedText(strResult + "\n");
404: textArea.goToMarker('i', false);
405: textArea.addMarker();
406:
407: orgValuesHolder.restore();
408: }
409:
410: /**
411: * A unit test for JUnit
412: */
413: static void test() {
414: ClassNameCache cnc = new ClassNameCache(System
415: .getProperty("java.class.path"));
416: logger.msg("selected.class", selectClass(null, "jEdit", cnc,
417: true));
418: logger.msg("selected.class", selectClass(null, "Context", cnc,
419: true));
420: logger.msg("selected.class", selectClass(null, "Foobar", cnc,
421: true));
422: }
423:
424: public static class JavaFileFilter implements FilenameFilter {
425: public boolean accept(File argDir, String argName) {
426: return argName.toLowerCase().endsWith(".java")
427: || (new File(argDir, argName)).isDirectory();
428: }
429: }
430:
431: public static void listAllJavaFiles(File argDir, List argList) {
432: listAllFiles(argDir, new JavaFileFilter(), argList);
433: }
434:
435: /**
436: * Add all files in the given directory (and sub-directories) to argFileList
437: * The filter can be used to narrow the results.
438: * @param argDir Description of the Parameter
439: * @param argFilter Description of the Parameter
440: * @param argFileList Description of the Parameter
441: */
442: public static void listAllFiles(File argDir,
443: FilenameFilter argFilter, List argFileList) {
444: if (argDir == null) {
445: return;
446: }
447: File[] files = null;
448: if (argFilter == null) {
449: files = argDir.listFiles();
450: } else {
451: files = argDir.listFiles(argFilter);
452: }
453: for (int i = 0; i < files.length; i++) {
454: //System.out.println("file[i]=" + files[i]);
455: if (files[i].isDirectory()) {
456: listAllFiles(files[i], argFilter, argFileList);
457: } else {
458: argFileList.add(files[i]);
459: }
460: }
461: }
462:
463: /**
464: * Description of the Method
465: *
466: * @param selectedText Description of the Parameter
467: * @return Description of the Return Value
468: */
469: static String sort(String selectedText) {
470:
471: StringTokenizer tokens = new StringTokenizer(selectedText, "\n");
472: List lines = new ArrayList();
473: while (tokens.hasMoreTokens()) {
474: lines.add(tokens.nextToken());
475: }
476: Collections.sort(lines);
477: // insert your favorite comparator here...
478: StringBuffer result = new StringBuffer();
479: for (Iterator it = lines.iterator(); it.hasNext();) {
480: result.append(it.next()).append('\n');
481: }
482: result.append('\n');
483: return result.toString();
484: }
485:
486: /**
487: * Sort import statements. Based on macro by Richard Wan,
488: * rwan@palmtreebusiness.com
489: *
490: * @param argView Description of the Parameter
491: */
492: public static void sortImports(View argView) {
493:
494: JEditTextArea textArea = argView.getTextArea();
495: int iOldPos = textArea.getCaretPosition();
496:
497: SearchAndReplaceOriginalValuesHolder orgValuesHolder = new SearchAndReplaceOriginalValuesHolder();
498:
499: textArea.setCaretPosition(0);
500: SearchAndReplace.setSearchString("import .+;");
501: SearchAndReplace.setAutoWrapAround(false);
502: SearchAndReplace.setReverseSearch(false);
503: SearchAndReplace.setIgnoreCase(false);
504: SearchAndReplace.setRegexp(true);
505: SearchAndReplace.setSearchFileSet(new CurrentBufferSet());
506: SearchAndReplace.find(argView);
507: textArea.goToStartOfLine(false);
508: int startPos = textArea.getCaretPosition();
509:
510: SearchAndReplace.setSearchString("(/\\*\\*)|(public class)");
511: SearchAndReplace.setAutoWrapAround(false);
512: SearchAndReplace.setReverseSearch(false);
513: SearchAndReplace.setIgnoreCase(false);
514: SearchAndReplace.setRegexp(true);
515: SearchAndReplace.setSearchFileSet(new CurrentBufferSet());
516: SearchAndReplace.find(argView);
517: textArea.goToStartOfLine(false);
518: int endPos = textArea.getCaretPosition();
519:
520: textArea.setSelection(new Selection.Range(startPos, endPos));
521: String oldImports = textArea.getSelectedText();
522: String newImports = sort(oldImports);
523: textArea.setSelectedText(newImports);
524: textArea.setCaretPosition(iOldPos);
525:
526: orgValuesHolder.restore();
527: }
528:
529: private static class SearchAndReplaceOriginalValuesHolder {
530: boolean orgAutoWrapAround = SearchAndReplace
531: .getAutoWrapAround();
532: boolean orgReverseSearch = SearchAndReplace.getReverseSearch();
533: boolean orgIgnoreCase = SearchAndReplace.getIgnoreCase();
534: boolean orgRegexp = SearchAndReplace.getRegexp();
535: String orgSearchString = SearchAndReplace.getSearchString();
536: SearchFileSet orgSearchFileSet = SearchAndReplace
537: .getSearchFileSet();
538:
539: public void restore() {
540: SearchAndReplace.setAutoWrapAround(orgAutoWrapAround);
541: SearchAndReplace.setReverseSearch(orgReverseSearch);
542: SearchAndReplace.setIgnoreCase(orgIgnoreCase);
543: SearchAndReplace.setRegexp(orgRegexp);
544: SearchAndReplace.setSearchString(orgSearchString);
545: SearchAndReplace.setSearchFileSet(orgSearchFileSet);
546: }
547: }
548:
549: /**
550: * The main program for the JavaUtils class
551: *
552: * @param args The command line arguments
553: */
554: //public static void main(String[] args) {
555: // try {
556: // viewClassInfo(null, "java.lang.String");
557: // } catch (Throwable t) {
558: // t.printStackTrace();
559: // }
560: //}
561: }
|