Import sys before using it in default.py
[matthijs/upstream/mobilegtd.git] / src / gui / gui.py
1 from config.config import *
2 from model.projects import Projects
3
4 import appuifw
5 import thread
6 from log.logging import logger
7 from e32 import Ao_lock, in_emulator
8 from key_codes import *
9 import key_codes
10
11
12 def show_config(cfg):        
13     fields = []
14     for k, v in cfg.items():
15         v = cfg.format_value(v)
16         if isinstance(v, int) or isinstance(v, long):
17             tname = 'number'
18             v = int(v)
19         elif isinstance(v, list) or isinstance(v, tuple):
20             for item in v[0]:
21                 if not isinstance(item, unicode):
22                     raise Exception("list can contain only unicode objects, "\
23                                     "object %r is not supported" % item)
24             
25             tname = 'combo'
26         elif isinstance(v, unicode):
27             tname = 'text'
28         else:
29             raise Exception("%s has non-supported value" % k)
30
31         fields.append((unicode(k), tname, v))
32
33
34     form = appuifw.Form(fields=fields, flags=appuifw.FFormEditModeOnly | \
35                         appuifw.FFormDoubleSpaced)
36
37     saved = [False]
38     def save_hook(param):
39         saved[0] = True
40     form.save_hook = save_hook
41     
42     form.execute()
43
44     # return true if user saved, false otherwise
45     if not saved[0]:
46         return False
47     
48     for label, tname, value in form:
49         if tname == 'combo':
50             value = (value[0], int(value[1]))
51
52         cfg[str(label)] = cfg.parse_value(value)
53
54     return True
55
56
57 def no_action():
58     pass
59
60 def applicable_functions(obj,allowed_function_names):
61     function_names = [function_name for function_name in dir(obj) if function_name in allowed_function_names]
62     return [eval('obj.%s'%function_name) for function_name in function_names]
63
64 def get_key(key_name):
65     if key_name == '':
66         key = None
67     else:
68         key=eval('EKey%s'%key_name)
69     return key
70
71 def all_key_names():
72     return filter(lambda entry:entry[0:4]=='EKey',dir(key_codes))
73 def all_key_values():
74     key_values=[
75                 EKey0,
76                 EKey1,
77                 EKey2,
78                 EKey3,
79                 EKey4,
80                 EKey5,
81                 EKey6,
82                 EKey7,
83                 EKey8,
84                 EKey9,
85                 EKeyStar,
86                 EKeyHash,
87                 ]
88     return key_values
89
90
91 def save_gui(object):
92     object.old_gui = appuifw.app.body
93     object.old_menu = appuifw.app.menu
94     object.old_exit_key_handler = appuifw.app.exit_key_handler
95     object.old_title=appuifw.app.title
96     object.lock = Ao_lock()
97
98 def restore_gui(object):
99     appuifw.app.body = object.old_gui
100     appuifw.app.menu = object.old_menu
101     appuifw.app.exit_key_handler = object.old_exit_key_handler
102     appuifw.app.title = object.old_title
103
104
105 class ListView(object):
106     def __init__(self,title):
107         self.title = title
108         self.view = appuifw.Listbox(self.items(),self.change_entry)
109     
110     def change_entry(self):
111         pass
112     
113     def run(self):
114         self.adjustment = None
115         appuifw.app.screen=COMMON_CONFIG['screen'].encode('utf-8')
116         save_gui(self)
117         appuifw.app.title=self.title
118         appuifw.app.body=self.view
119         appuifw.app.exit_key_handler=self.exit
120         try:
121             self.lock.wait()
122             while not self.exit_flag:
123                 self.refresh()
124                 self.lock.wait()
125         except:
126             pass
127         restore_gui(self)
128     def exit(self):
129         self.exit_flag = True
130         self.lock.signal()
131
132     def update(self,subject=None):
133         #logger.log(u'Updated %s'%repr(self))
134         if self.lock:
135             self.lock.signal()
136         #pass
137
138     def index_changed(self,adjustment=None):
139         if adjustment:
140             index = self.selected_index() + adjustment
141         else:
142             index = self.selected_index()
143         if index < 0:
144             index = len(self.widgets) - 1
145         if index >= len(self.widgets):
146             index = 0
147         self.set_bindings_for_selection(index)
148
149     def refresh(self):
150         appuifw.app.menu=self.get_menu_entries()
151
152     def set_index(self,index):
153         if index > len(self.widgets):
154             index = len(self.widgets)
155         if index < 0:
156             index = 0
157         self.view.set_list(self.items(),index)
158
159     def selected_index(self):
160         return self.view.current()
161
162
163 class WidgetBasedListView(ListView):
164     def __init__(self,title):
165         self.widgets = self.generate_widgets()
166         super(WidgetBasedListView,self).__init__(title)
167         self.exit_flag = False
168
169     def run(self):
170         self.refresh()
171         self.set_bindings_for_selection(0)
172         ListView.run(self)
173
174     def notify(self,object,attribute,new=None,old=None):
175         self.refresh()
176     def refresh(self):
177         self.widgets = self.generate_widgets()
178         self.redisplay_widgets()
179         super(WidgetBasedListView,self).refresh()
180     def redisplay_widgets(self):
181         self.set_index(self.selected_index())
182     def items(self):
183         return self.all_widget_texts()
184     def all_widget_texts(self):
185         return [entry.list_repr() for entry in self.widgets]
186
187     
188
189     def current_widget(self):
190         return self.widgets[self.selected_index()]
191         
192
193 class KeyBindingView(object):
194     
195     def __init__(self,binding_map):
196         self.binding_map = binding_map
197
198     def get_menu_entries(self):
199         menu_entries=[]
200         for key,key_name,description,function in self.key_and_menu_bindings(self.selected_index()):
201             if description != '':
202                 if key:
203                     if key_name == 'Backspace': key_name='C'
204                     description='[%s] '%key_name +description
205                 else:
206                     description='    '+description
207                 menu_entries.append((description,function)) 
208         menu_entries.append((u'Exit', self.exit))
209         return menu_entries       
210     def set_bindings_for_selection(self,selected_index):
211         self.remove_all_key_bindings()
212         
213         for key,key_name,description,function in self.key_and_menu_bindings(selected_index):
214             if key:
215                 self.view.bind(key,function)
216         self.view.bind(EKeyUpArrow,lambda: self.index_changed(-1))
217         self.view.bind(EKeyDownArrow,lambda: self.index_changed(1))
218         
219     def remove_all_key_bindings(self):
220         for key in all_key_values():
221             self.view.bind(key,no_action)
222
223 class SearchableListView(WidgetBasedListView):
224     def __init__(self,title,entry_filters):
225         self.current_entry_filter_index = 0
226         self.entry_filters = entry_filters
227         self.filtered_list = self.entry_filters[0]
228         self.lock = None
229         super(SearchableListView,self).__init__(title)
230
231
232     def search_item(self):
233         selected_item = appuifw.selection_list(self.all_widget_texts(),search_field=1)
234         if selected_item == None or selected_item == -1:
235             selected_item = self.selected_index()
236         self.view.set_list(self.items(),selected_item)
237         self.set_bindings_for_selection(selected_item)
238     def switch_entry_filter(self):
239         self.current_entry_filter_index += 1
240         self.filtered_list = self.entry_filters[self.current_entry_filter_index % len(self.entry_filters)]
241         self.refresh()
242
243
244 class EditableListView(SearchableListView,KeyBindingView):
245     def __init__(self,title,entry_filters,binding_map):
246         KeyBindingView.__init__(self,binding_map)
247         super(EditableListView, self).__init__(title,entry_filters)
248
249     def key_and_menu_bindings(self,selected_index):
250         key_and_menu_bindings=[]
251         for function in applicable_functions(self.widgets[selected_index],self.binding_map)+\
252             applicable_functions(self,self.binding_map):
253             execute_and_update_function = self.execute_and_update(function)
254             (key,description) = self.binding_map[function.__name__]
255             key_and_menu_bindings.append((get_key(key),key,description,execute_and_update_function))
256         return key_and_menu_bindings
257
258     def change_entry(self):
259         self.current_widget().change()
260         self.refresh()
261     def execute_and_update(self,function):
262         return lambda: (function(),self.refresh(),self.index_changed())
263
264     def notify(self,item,attribute,new=None,old=None):
265         self.refresh()
266
267 #class DisplayableFunction:
268 #    def __init__(self,display_name,function):
269 #        self.display_name = display_name
270 #        self.function = function
271 #    def list_repr(self):
272 #        return self.display_name
273 #    def execute(self):
274 #        function()
275
276 # Public API
277 __all__= ('EditableListView','show_config')