Add ListView.selected_item helper.
[matthijs/upstream/mobilegtd.git] / src / gui / gui.py
index 94ade0689c9a09b1a4a212d9f38a61660a579c4b..3d4e6fb9e605627ad789dcbe7ce00b4398c88b35 100644 (file)
@@ -142,7 +142,9 @@ class View(object):
                 self.refresh()
                 self.lock.wait()
         except:
-            pass
+            # TODO: Find out which exceptions to catch here. Catching
+            # and silencing all exceptions is not a good idea.
+            raise
         restore_gui(self)
 
     def exit(self):
@@ -217,7 +219,7 @@ class ListView(View):
         we'll have to adjust the index with the direction of the
         keypress (-1 for up, +1 for down).
         """
-        self.current_index = (self.selected_index() + dir) % len(self.items())
+        self.current_index = self.wrap_index(self.selected_index() + dir)
         self.index_changed()
         self.current_index = None
 
@@ -249,6 +251,13 @@ class ListView(View):
         """ Changes the currently selected item to index. """
         self.view.set_list(self.items(),index % len(self.items()))
 
+    def selected_item(self):
+        """ Returns the (title of the) currently selected list item. """
+        if not self.items_cache:
+            return None # No items, so none is selected.
+        return self.items_cache[self.selected_index()]
+
+
     def selected_index(self):
         """ Returns the currently selected index. """
         if not self.current_index is None:
@@ -258,6 +267,24 @@ class ListView(View):
         else:
             return self.view.current()
 
+    def clip_index(self, index):
+        """
+        Make sure the given index fits within the bounds of this
+        list. If it doesn't, clip it off at the ends of the list (e.g,
+        -1 becomes 0).
+        """
+        max_index = len(self.items_cache) - 1
+        return max (0, min(max_index, index))
+
+    def wrap_index(self, index):
+        """
+        Make sure the given index fits within the bounds of this
+        list. If it doesn't, wrap it around (e.g., -1 becomes 5 in a
+        6-element list).
+        """
+        count = len(self.items_cache)
+        return index % count
+    
 class WidgetBasedListView(ListView):
     def __init__(self):
         self.binding_map = {}