55254c5a0e75c5898b96bffaa5a231c263c14b05
[jalview.git] / src / jalview / io / cache / JvCacheableInputBox.java
1 package jalview.io.cache;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.LinkedHashSet;
6 import java.util.List;
7 import java.util.Set;
8
9 import javax.swing.JComboBox;
10 import javax.swing.SwingUtilities;
11
12 public class JvCacheableInputBox<E> extends JComboBox<String>
13 {
14
15   private static final long serialVersionUID = 5774610435079326695L;
16
17   private String cacheKey;
18
19   private AppCache appCache;
20
21   public JvCacheableInputBox(String cacheKey)
22   {
23     super();
24     this.cacheKey = cacheKey;
25     setEditable(true);
26     setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
27     appCache = AppCache.getInstance();
28     appCache.initCache(cacheKey);
29     updateCache();
30   }
31
32
33   /**
34    * Answers true if input text is an integer
35    * 
36    * @param text
37    * @return
38    */
39   private boolean isInteger(String text)
40   {
41     try
42     {
43       Integer.parseInt(text);
44       return true;
45     } catch (NumberFormatException e)
46     {
47       return false;
48     }
49   }
50
51   /**
52    * Method called to update the cache with the last user input
53    */
54   public void updateCache()
55   {
56     SwingUtilities.invokeLater(new Runnable()
57     {
58       @Override
59       public void run()
60       {
61         String userInput = getUserInput();
62         if (userInput != null && !userInput.isEmpty())
63         {
64           LinkedHashSet<String> foundCache = appCache
65                   .getAllCachedItemsFor(cacheKey);
66           // remove old cache item so as to place current input at the top of
67           // the result
68           foundCache.remove(userInput);
69           foundCache.add(userInput);
70           appCache.putCache(cacheKey, foundCache);
71         }
72
73         String lastSearch = userInput;
74         if (getItemCount() > 0)
75         {
76           removeAllItems();
77         }
78         Set<String> cacheItems = appCache.getAllCachedItemsFor(cacheKey);
79         List<String> reversedCacheItems = new ArrayList<String>();
80         reversedCacheItems.addAll(cacheItems);
81         cacheItems = null;
82         Collections.reverse(reversedCacheItems);
83         if (lastSearch.isEmpty())
84         {
85           addItem("");
86         }
87         if (reversedCacheItems != null && !reversedCacheItems.isEmpty())
88         {
89           for (String cacheItem : reversedCacheItems)
90           {
91             addItem(cacheItem);
92           }
93         }
94         setSelectedItem(lastSearch.isEmpty() ? "" : lastSearch);
95       }
96     });
97   }
98
99
100   public String getUserInput()
101   {
102     return getEditor().getItem() == null ? "" : getEditor().getItem()
103             .toString().trim();
104   }
105
106 }