01: /*
02: * This is free software, licensed under the Gnu Public License (GPL)
03: * get a copy from <http://www.gnu.org/licenses/gpl.html>
04: * $Id: NameCompleter.java,v 1.5 2004/03/23 11:05:38 magrokosmos Exp $
05: * author: Henner Zeller <H.Zeller@acm.org>
06: */
07: package henplus.view.util;
08:
09: import java.util.Collection;
10: import java.util.Iterator;
11: import java.util.SortedSet;
12: import java.util.SortedMap;
13: import java.util.TreeSet;
14: import java.util.TreeMap;
15:
16: /**
17: * a Completer for names that are only given partially. This is used for
18: * tab-completion or to automatically correct names.
19: */
20: public class NameCompleter {
21: private final SortedSet nameSet;
22: private final SortedMap canonicalNames;
23:
24: public NameCompleter() {
25: nameSet = new TreeSet();
26: canonicalNames = new TreeMap();
27: }
28:
29: public NameCompleter(Iterator names) {
30: this ();
31: while (names.hasNext()) {
32: addName((String) names.next());
33: }
34: }
35:
36: public NameCompleter(Collection c) {
37: this (c.iterator());
38: }
39:
40: public NameCompleter(String names[]) {
41: this ();
42: for (int i = 0; i < names.length; ++i) {
43: addName(names[i]);
44: }
45: }
46:
47: public void addName(String name) {
48: nameSet.add(name);
49: canonicalNames.put(name.toLowerCase(), name);
50: }
51:
52: public Iterator getAllNamesIterator() {
53: return nameSet.iterator();
54: }
55:
56: public SortedSet getAllNames() {
57: return nameSet;
58: }
59:
60: public String findCaseInsensitive(String name) {
61: if (name == null)
62: return null;
63: name = name.toLowerCase();
64: return (String) canonicalNames.get(name);
65: }
66:
67: /**
68: * returns an iterator with alternatives that match the partial name
69: * given or 'null' if there is no alternative.
70: */
71: public Iterator getAlternatives(String partialName) {
72: // first test, if we find the name directly
73: Iterator testIt = nameSet.tailSet(partialName).iterator();
74: String testMatch = (testIt.hasNext()) ? (String) testIt.next()
75: : null;
76: if (testMatch == null || !testMatch.startsWith(partialName)) {
77: String canonical = partialName.toLowerCase();
78: testIt = canonicalNames.tailMap(canonical).keySet()
79: .iterator();
80: testMatch = (testIt.hasNext()) ? (String) testIt.next()
81: : null;
82: if (testMatch == null || !testMatch.startsWith(canonical))
83: return null; // nope.
84: String foundName = (String) canonicalNames.get(testMatch);
85: partialName = foundName.substring(0, partialName.length());
86: }
87:
88: return new SortedMatchIterator(partialName, nameSet);
89: }
90: }
91:
92: /*
93: * Local variables:
94: * c-basic-offset: 4
95: * compile-command: "ant -emacs -find build.xml"
96: * End:
97: */
|