Initial checkin
[ejpi] / src / ejpi_glade.py
1 #!/usr/bin/python
2
3 """
4 @todo Add preference file
5         @li enable/disable plugins
6         @li plugin search path
7         @li Number format
8         @li Current tab
9 @todo Expand operations to support
10         @li mathml then to cairo?
11         @li cairo directly?
12 @todo Expanded copy/paste (Unusure how far to go)
13         @li Copy formula, value, serialized, mathml, latex?
14         @li Paste serialized, value?
15
16 Some useful things on Maemo
17 @li http://maemo.org/api_refs/4.1/libosso-2.16-1/group__Statesave.html
18 @li http://maemo.org/api_refs/4.1/libosso-2.16-1/group__Autosave.html
19 """
20
21
22 from __future__ import with_statement
23
24
25 import sys
26 import gc
27 import os
28 import string
29 import warnings
30
31 import gtk
32 import gtk.glade
33
34 try:
35         import hildon
36 except ImportError:
37         hildon = None
38
39 from libraries import gtkpie
40 from libraries import gtkpieboard
41 import plugin_utils
42 import history
43 import gtkhistory
44
45
46 PLUGIN_SEARCH_PATHS = [
47         os.path.join(os.path.dirname(__file__), "plugins/"),
48 ]
49
50
51 class ValueEntry(object):
52
53         def __init__(self, widget):
54                 self.__widget = widget
55                 self.__actualEntryDisplay = ""
56
57         def get_value(self):
58                 value = self.__actualEntryDisplay.strip()
59                 if any(
60                         0 < value.find(whitespace)
61                         for whitespace in string.whitespace
62                 ):
63                         self.clear()
64                         raise ValueError('Invalid input "%s"' % value)
65                 return value
66
67         def set_value(self, value):
68                 value = value.strip()
69                 if any(
70                         0 < value.find(whitespace)
71                         for whitespace in string.whitespace
72                 ):
73                         raise ValueError('Invalid input "%s"' % value)
74                 self.__actualEntryDisplay = value
75                 self.__widget.set_text(value)
76
77         def append(self, value):
78                 value = value.strip()
79                 if any(
80                         0 < value.find(whitespace)
81                         for whitespace in string.whitespace
82                 ):
83                         raise ValueError('Invalid input "%s"' % value)
84                 self.set_value(self.get_value() + value)
85
86         def pop(self):
87                 value = self.get_value()[0:-1]
88                 self.set_value(value)
89
90         def clear(self):
91                 self.set_value("")
92
93         value = property(get_value, set_value, clear)
94
95
96 class ErrorDisplay(history.ErrorReporting):
97
98         def __init__(self, widgetTree):
99                 super(ErrorDisplay, self).__init__()
100                 self.__errorBox = widgetTree.get_widget("errorEventBox")
101                 self.__errorDescription = widgetTree.get_widget("errorDescription")
102                 self.__errorClose = widgetTree.get_widget("errorClose")
103                 self.__parentBox = self.__errorBox.get_parent()
104
105                 self.__errorBox.connect("button_release_event", self._on_close)
106
107                 self.__messages = []
108                 self.__parentBox.remove(self.__errorBox)
109
110         def push_message(self, message):
111                 if 0 < len(self.__messages):
112                         self.__messages.append(message)
113                 else:
114                         self.__show_message(message)
115
116         def pop_message(self):
117                 if 0 < len(self.__messages):
118                         self.__show_message(self.__messages[0])
119                         del self.__messages[0]
120                 else:
121                         self.__hide_message()
122
123         def _on_close(self, *args):
124                 self.pop_message()
125
126         def __show_message(self, message):
127                 self.__errorDescription.set_text(message)
128                 self.__parentBox.pack_start(self.__errorBox, False, False)
129                 self.__parentBox.reorder_child(self.__errorBox, 1)
130
131         def __hide_message(self):
132                 self.__errorDescription.set_text("")
133                 self.__parentBox.remove(self.__errorBox)
134
135
136 class Calculator(object):
137
138         __pretty_app_name__ = "e^(j pi) + 1 = 0"
139         __app_name__ = "ejpi"
140         __version__ = "0.1.0"
141         __app_magic__ = 0xdeadbeef
142
143         _glade_files = [
144                 '/usr/lib/ejpi/calc.glade',
145                 os.path.join(os.path.dirname(__file__), "calc.glade"),
146                 os.path.join(os.path.dirname(__file__), "../lib/calc.glade"),
147         ]
148
149         _plugin_search_paths = [
150                 os.path.join(os.path.dirname(__file__), "plugins/")
151         ]
152
153         _user_data = os.path.expanduser("~/.%s/" % __app_name__)
154         _user_settings = "%s/settings.ini" % _user_data
155         _user_history = "%s/history.stack" % _user_data
156
157         def __init__(self):
158                 self.__constantPlugins = plugin_utils.ConstantPluginManager()
159                 self.__constantPlugins.add_path(*self._plugin_search_paths)
160                 self.__constantPlugins.enable_plugin(self.__constantPlugins.lookup_plugin("Builtin"))
161                 self.__constantPlugins.enable_plugin(self.__constantPlugins.lookup_plugin("Trigonometry"))
162                 self.__constantPlugins.enable_plugin(self.__constantPlugins.lookup_plugin("Computer"))
163                 self.__constantPlugins.enable_plugin(self.__constantPlugins.lookup_plugin("Alphabet"))
164
165                 self.__operatorPlugins = plugin_utils.OperatorPluginManager()
166                 self.__operatorPlugins.add_path(*self._plugin_search_paths)
167                 self.__operatorPlugins.enable_plugin(self.__operatorPlugins.lookup_plugin("Builtin"))
168                 self.__operatorPlugins.enable_plugin(self.__operatorPlugins.lookup_plugin("Trigonometry"))
169                 self.__operatorPlugins.enable_plugin(self.__operatorPlugins.lookup_plugin("Computer"))
170                 self.__operatorPlugins.enable_plugin(self.__operatorPlugins.lookup_plugin("Alphabet"))
171
172                 self.__keyboardPlugins = plugin_utils.KeyboardPluginManager()
173                 self.__keyboardPlugins.add_path(*self._plugin_search_paths)
174                 self.__activeKeyboards = {}
175
176                 for path in self._glade_files:
177                         if os.path.isfile(path):
178                                 self._widgetTree = gtk.glade.XML(path)
179                                 break
180                 else:
181                         self.display_error_message("Cannot find calc.glade")
182                         gtk.main_quit()
183                 try:
184                         os.makedirs(self._user_data)
185                 except OSError, e:
186                         if e.errno != 17:
187                                 raise
188
189                 self._clipboard = gtk.clipboard_get()
190                 self.__window = self._widgetTree.get_widget("mainWindow")
191
192                 global hildon
193                 self._app = None
194                 self._isFullScreen = False
195                 if hildon is not None and self.__window is gtk.Window:
196                         warnings.warn("Hildon installed but glade file not updated to work with hildon", UserWarning, 2)
197                         hildon = None
198                 elif hildon is not None:
199                         self._app = hildon.Program()
200                         self.__window = hildon.Window()
201                         self._widgetTree.get_widget("mainLayout").reparent(self.__window)
202                         self._app.add_window(self.__window)
203                         hildon.hildon_helper_set_thumb_scrollbar(self._widgetTree.get_widget('scrollingHistory'), True)
204
205                         gtkMenu = self._widgetTree.get_widget("mainMenubar")
206                         menu = gtk.Menu()
207                         for child in gtkMenu.get_children():
208                                 child.reparent(menu)
209                         self.__window.set_menu(menu)
210                         gtkMenu.destroy()
211
212                         self.__window.connect("key-press-event", self._on_key_press)
213                         self.__window.connect("window-state-event", self._on_window_state_change)
214                 else:
215                         warnings.warn("No Hildon", UserWarning, 2)
216
217                 self.__errorDisplay = ErrorDisplay(self._widgetTree)
218                 self.__userEntry = ValueEntry(self._widgetTree.get_widget("entryView"))
219                 self.__stackView = self._widgetTree.get_widget("historyView")
220
221                 self.__historyStore = gtkhistory.GtkCalcHistory(self.__stackView)
222                 self.__history = history.RpnCalcHistory(
223                         self.__historyStore,
224                         self.__userEntry, self.__errorDisplay,
225                         self.__constantPlugins.constants, self.__operatorPlugins.operators
226                 )
227                 self.__load_history()
228
229                 self.__sliceStyle = gtkpie.generate_pie_style(self.__window)
230                 self.__handler = gtkpieboard.KeyboardHandler(self._on_entry_direct)
231                 self.__handler.register_command_handler("push", self._on_push)
232                 self.__handler.register_command_handler("unpush", self._on_unpush)
233                 self.__handler.register_command_handler("backspace", self._on_entry_backspace)
234                 self.__handler.register_command_handler("clear", self._on_entry_clear)
235
236                 builtinKeyboardId = self.__keyboardPlugins.lookup_plugin("Builtin")
237                 self.__keyboardPlugins.enable_plugin(builtinKeyboardId)
238                 self.__builtinPlugin = self.__keyboardPlugins.keyboards["Builtin"].construct_keyboard()
239                 self.__builtinKeyboard = self.__builtinPlugin.setup(self.__history, self.__sliceStyle, self.__handler)
240                 self._widgetTree.get_widget("functionLayout").pack_start(self.__builtinKeyboard)
241                 self._widgetTree.get_widget("functionLayout").reorder_child(self.__builtinKeyboard, 0)
242                 self.enable_plugin(self.__keyboardPlugins.lookup_plugin("Trigonometry"))
243                 self.enable_plugin(self.__keyboardPlugins.lookup_plugin("Computer"))
244                 self.enable_plugin(self.__keyboardPlugins.lookup_plugin("Alphabet"))
245
246                 callbackMapping = {
247                         "on_calculator_quit": self._on_close,
248                         "on_paste": self._on_paste,
249                         "on_clear_entry": self._on_clear_all,
250                         "on_about": self._on_about_activate,
251                 }
252                 self._widgetTree.signal_autoconnect(callbackMapping)
253
254                 if self.__window:
255                         if hildon is None:
256                                 self.__window.set_title("%s" % self.__pretty_app_name__)
257                         self.__window.connect("destroy", self._on_close)
258                         self.__window.show_all()
259
260                 try:
261                         import osso
262                 except ImportError:
263                         osso = None
264
265                 self._osso = None
266                 if osso is not None:
267                         self._osso = osso.Context(Calculator.__app_name__, Calculator.__version__, False)
268                         device = osso.DeviceState(self._osso)
269                         device.set_device_state_callback(self._on_device_state_change, 0)
270                 else:
271                         warnings.warn("No OSSO", UserWarning, 2)
272
273         def display_error_message(self, msg):
274                 error_dialog = gtk.MessageDialog(None, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, msg)
275
276                 def close(dialog, response, editor):
277                         editor.about_dialog = None
278                         dialog.destroy()
279                 error_dialog.connect("response", close, self)
280                 error_dialog.run()
281
282         def enable_plugin(self, pluginId):
283                 self.__keyboardPlugins.enable_plugin(pluginId)
284                 pluginData = self.__keyboardPlugins.plugin_info(pluginId)
285                 pluginName = pluginData[0]
286                 plugin = self.__keyboardPlugins.keyboards[pluginName].construct_keyboard()
287                 pluginKeyboard = plugin.setup(self.__history, self.__sliceStyle, self.__handler)
288
289                 keyboardTabs = self._widgetTree.get_widget("pluginKeyboards")
290                 keyboardTabs.append_page(pluginKeyboard, gtk.Label(pluginName))
291                 keyboardPageNum = keyboardTabs.page_num(pluginKeyboard)
292                 assert keyboardPageNum not in self.__activeKeyboards
293                 self.__activeKeyboards[keyboardPageNum] = {
294                         "pluginName": pluginName,
295                         "plugin": plugin,
296                         "pluginKeyboard": pluginKeyboard,
297                 }
298
299         def __load_history(self):
300                 serialized = []
301                 try:
302                         with open(self._user_history, "rU") as f:
303                                 serialized = (
304                                         (part.strip() for part in line.split(" "))
305                                         for line in f.readlines()
306                                 )
307                 except IOError, e:
308                         if e.errno != 2:
309                                 raise
310                 self.__history.deserialize_stack(serialized)
311
312         def __save_history(self):
313                 serialized = self.__history.serialize_stack()
314                 with open(self._user_history, "w") as f:
315                         for lineData in serialized:
316                                 line = " ".join(data for data in lineData)
317                                 f.write("%s\n" % line)
318
319         def _on_device_state_change(self, shutdown, save_unsaved_data, memory_low, system_inactivity, message, userData):
320                 """
321                 For system_inactivity, we have no background tasks to pause
322
323                 @note Hildon specific
324                 """
325                 if memory_low:
326                         gc.collect()
327
328                 if save_unsaved_data or shutdown:
329                         self.__save_history()
330
331         def _on_window_state_change(self, widget, event, *args):
332                 """
333                 @note Hildon specific
334                 """
335                 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
336                         self._isFullScreen = True
337                 else:
338                         self._isFullScreen = False
339
340         def _on_close(self, *args, **kwds):
341                 try:
342                         self.__save_history()
343                 finally:
344                         gtk.main_quit()
345
346         def _on_paste(self, *args):
347                 contents = self._clipboard.wait_for_text()
348                 self.__userEntry.append(contents)
349
350         def _on_key_press(self, widget, event, *args):
351                 """
352                 @note Hildon specific
353                 """
354                 if event.keyval == gtk.keysyms.F6:
355                         if self._isFullScreen:
356                                 self.__window.unfullscreen()
357                         else:
358                                 self.__window.fullscreen()
359
360         def _on_push(self, *args):
361                 self.__history.push_entry()
362
363         def _on_unpush(self, *args):
364                 self.__historyStore.unpush()
365
366         def _on_entry_direct(self, keys, modifiers):
367                 if "shift" in modifiers:
368                         keys = keys.upper()
369                 self.__userEntry.append(keys)
370
371         def _on_entry_backspace(self, *args):
372                 self.__userEntry.pop()
373
374         def _on_entry_clear(self, *args):
375                 self.__userEntry.clear()
376
377         def _on_clear_all(self, *args):
378                 self.__history.clear()
379
380         def _on_about_activate(self, *args):
381                 dlg = gtk.AboutDialog()
382                 dlg.set_name(self.__pretty_app_name__)
383                 dlg.set_version(self.__version__)
384                 dlg.set_copyright("Copyright 2008 - LGPL")
385                 dlg.set_comments("")
386                 dlg.set_website("")
387                 dlg.set_authors([""])
388                 dlg.run()
389                 dlg.destroy()
390
391
392 def run_doctest():
393         import doctest
394
395         failureCount, testCount = doctest.testmod()
396         if not failureCount:
397                 print "Tests Successful"
398                 sys.exit(0)
399         else:
400                 sys.exit(1)
401
402
403 def run_calculator():
404         gtk.gdk.threads_init()
405
406         if hildon is not None:
407                 gtk.set_application_name(Calculator.__pretty_app_name__)
408         handle = Calculator()
409         gtk.main()
410
411
412 class DummyOptions(object):
413
414         def __init__(self):
415                 self.test = False
416
417
418 if __name__ == "__main__":
419         if len(sys.argv) > 1:
420                 try:
421                         import optparse
422                 except ImportError:
423                         optparse = None
424
425                 if optparse is not None:
426                         parser = optparse.OptionParser()
427                         parser.add_option("-t", "--test", action="store_true", dest="test", help="Run tests")
428                         (commandOptions, commandArgs) = parser.parse_args()
429         else:
430                 commandOptions = DummyOptions()
431                 commandArgs = []
432
433         if commandOptions.test:
434                 run_doctest()
435         else:
436                 gtkpie.IMAGES.add_path(os.path.join(os.path.dirname(__file__), "libraries/images"), )
437                 run_calculator()