More cleanups
[gonvert] / src / gonvert_glade.py
1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
3
4 import os
5 import pickle
6 import string
7 import gettext
8 import logging
9
10 import gobject
11 import gtk
12 import gtk.glade
13 import gtk.gdk
14
15 import constants
16 import unit_data
17
18
19 _moduleLogger = logging.getLogger("gonvert_glade")
20
21 gettext.bindtextdomain('gonvert', '/usr/share/locale')
22 gettext.textdomain('gonvert')
23 _ = gettext.gettext
24
25
26 def change_menu_label(widgets, labelname, newtext):
27         item_label = widgets.get_widget(labelname).get_children()[0]
28         item_label.set_text(newtext)
29
30
31 class Gonvert(object):
32
33         _glade_files = [
34                 os.path.join(os.path.dirname(__file__), "gonvert.glade"),
35                 os.path.join(os.path.dirname(__file__), "../data/gonvert.glade"),
36                 os.path.join(os.path.dirname(__file__), "../lib/gonvert.glade"),
37                 '/usr/lib/gonvert/gonvert.glade',
38         ]
39
40         def __init__(self):
41                 self._unitDataInCategory = None
42                 self._unit_sort_direction = False
43                 self._value_sort_direction = False
44                 self._units_sort_direction = False
45                 self._isFullScreen = False
46
47                 self._find_result = [] # empty find result list
48                 self._findIndex = 0 # default to find result number zero
49
50                 self._selectedCategory = '' # preset to no selected category
51                 self._defaultUnitForCategory = {} # empty dictionary for later use
52
53                 #check to see if glade file is in current directory (user must be
54                 # running from download untar directory)
55                 for gladePath in self._glade_files:
56                         if os.path.isfile(gladePath):
57                                 homepath = os.path.dirname(gladePath)
58                                 pixmapspath = "/".join((homepath, "pixmaps"))
59                                 widgets = gtk.glade.XML(gladePath)
60                                 break
61                 else:
62                         _moduleLogger.error("UI Descriptor not found!")
63                         gtk.main_quit()
64                         return
65
66                 self._mainWindow = widgets.get_widget('mainWindow')
67
68                 change_menu_label(widgets, 'fileMenuItem', _('File'))
69                 change_menu_label(widgets, 'exitMenuItem', _('Exit'))
70                 change_menu_label(widgets, 'toolsMenuItem', _('Tools'))
71                 change_menu_label(widgets, 'clearSelectionMenuItem', _('Clear selections'))
72                 change_menu_label(widgets, 'writeUnitsMenuItem', _('Write Units'))
73                 change_menu_label(widgets, 'helpMenuItem', _('Help'))
74                 change_menu_label(widgets, 'aboutMenuItem', _('About'))
75                 change_menu_label(widgets, 'findButton', _('Find'))
76
77                 self._shortlistcheck = widgets.get_widget('shortlistcheck')
78                 self._toggleShortList = widgets.get_widget('toggleShortList')
79
80                 self._categoryView = widgets.get_widget('categoryView')
81
82                 self._unitsView = widgets.get_widget('unitsView')
83                 self._unitsView.set_property('rules_hint', 1)
84                 self._unitsView_selection = self._unitsView.get_selection()
85
86                 self._unitName = widgets.get_widget('unitName')
87                 self._unitValue = widgets.get_widget('unitValue')
88                 self._previousUnitName = widgets.get_widget('previousUnitName')
89                 self._previousUnitValue = widgets.get_widget('previousUnitValue')
90                 messagebox = widgets.get_widget('msgbox')
91                 messageboxtext = widgets.get_widget('msgboxtext')
92
93                 self._unitSymbol = widgets.get_widget('unitSymbol')
94                 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
95
96                 self._unitDescription = widgets.get_widget('unitDescription')
97
98                 self._searchLayout = widgets.get_widget('searchLayout')
99                 self._searchLayout.hide()
100                 self._findEntry = widgets.get_widget('findEntry')
101                 self._findLabel = widgets.get_widget('findLabel')
102                 self._findButton = widgets.get_widget('findButton')
103                 ToolTips = gtk.Tooltips()
104                 ToolTips.set_tip(self._findButton, _(u'Find unit (F6)'))
105
106                 #insert a self._categoryColumnumn into the units list even though the heading will not be seen
107                 renderer = gtk.CellRendererText()
108                 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
109                 self._unitNameColumn.set_property('resizable', 1)
110                 self._unitNameColumn.add_attribute(renderer, 'text', 0)
111                 self._unitNameColumn.set_clickable(True)
112                 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
113                 self._unitsView.append_column(self._unitNameColumn)
114
115                 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
116                 self._unitValueColumn.set_property('resizable', 1)
117                 self._unitValueColumn.add_attribute(renderer, 'text', 1)
118                 self._unitValueColumn.set_clickable(True)
119                 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
120                 self._unitsView.append_column(self._unitValueColumn)
121
122                 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
123                 self._unitSymbolColumn.set_property('resizable', 1)
124                 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
125                 self._unitSymbolColumn.set_clickable(True)
126                 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
127                 self._unitsView.append_column(self._unitSymbolColumn)
128
129                 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
130                 self._sortedUnitModel = gtk.TreeModelSort(self._unitModel)
131                 columns = self._get_column_sort_stuff()
132                 for columnIndex, (column, sortDirection, col_cmp) in enumerate(columns):
133                         self._sortedUnitModel.set_sort_func(columnIndex, col_cmp)
134                 self._unitsView.set_model(self._sortedUnitModel)
135
136                 #Insert a column into the category list even though the heading will not be seen
137                 renderer = gtk.CellRendererText()
138                 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
139                 self._categoryColumn.set_property('resizable', 1)
140                 self._categoryColumn.add_attribute(renderer, 'text', 0)
141                 self._categoryView.append_column(self._categoryColumn)
142
143                 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
144                 self._categoryView.set_model(self._categoryModel)
145                 #colourize each row differently for easier reading
146                 self._categoryView.set_property('rules_hint', 1)
147
148                 #Populate the catagories list
149                 for key in unit_data.UNIT_CATEGORIES:
150                         iter = self._categoryModel.append()
151                         self._categoryModel.set(iter, 0, key)
152
153                 #--------- connections to GUI ----------------
154                 dic = {
155                         "on_exit_menu_activate": self._on_user_exit,
156                         "on_main_window_destroy": self._on_user_exit,
157                         "on_categoryView_select_row": self._on_click_category,
158                         "on_unitValue_changed": self._on_unit_value_changed,
159                         "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
160                         "on_writeUnitsMenuItem_activate": self._on_user_write_units,
161                         "on_findButton_clicked": self._on_find_activate,
162                         "on_findEntry_activated": self._on_find_activate,
163                         "on_findEntry_changed": self._on_findEntry_changed,
164                         "on_aboutMenuItem_activate": self._on_about_clicked,
165                         "on_messagebox_ok_clicked": self.messagebox_ok_clicked,
166                         "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
167                         "on_unitsView_cursor_changed": self._on_click_unit,
168                         "on_shortlistcheck_toggled": self._on_shortlist_changed,
169                         "on_toggleShortList_activate": self._on_edit_shortlist,
170                 }
171                 widgets.signal_autoconnect(dic)
172                 self._mainWindow.connect("key-press-event", self._on_key_press)
173                 self._mainWindow.connect("window-state-event", self._on_window_state_change)
174
175                 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
176                 iconPath = pixmapspath + '/gonvert.png'
177                 if os.path.exists(iconPath):
178                         self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
179                 else:
180                         _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
181
182                 self._load_settings()
183
184         def _load_settings(self):
185                 #Restore window size from previously saved settings if it exists and is valid.
186                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
187                 if os.path.exists(windowDatPath):
188                         #Retrieving previous window settings from ~/.gonvert/window.dat
189                         saved_window = pickle.load(open(windowDatPath, "r"))
190                         #If the 'size' has been stored, then extract size from saved_window.
191                         if 'size' in saved_window:
192                                 a, b = saved_window['size']
193                                 self._mainWindow.resize(a, b)
194                         else:
195                                 #Maximize if no previous size was found
196                                 #self._mainWindow.maximize()
197                                 pass
198                 else:
199                         #Maximize if no previous window.dat file was found
200                         #self._mainWindow.maximize()
201                         pass
202
203                 #Restore selections from previously saved settings if it exists and is valid.
204                 historical_catergory_found = False
205                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
206                 if os.path.exists(selectionsDatPath):
207                         #Retrieving previous selections from ~/.gonvert/selections.dat
208                         selections = pickle.load(open(selectionsDatPath, 'r'))
209                         #Restoring previous selections.
210                         #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
211                         if 'selected_units' in selections:
212                                 self._defaultUnitForCategory = selections['selected_units']
213                         #Make sure that the 'self._selectedCategory' has been stored.
214                         if 'selected_category' in selections:
215                                 #Match an available category to the previously selected category.
216                                 for counter in range(len(unit_data.UNIT_CATEGORIES)):
217                                         if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
218                                                 # Restore the previously selected category.
219                                                 self._categoryView.set_cursor(counter, self._categoryColumn, False)
220                                                 self._categoryView.grab_focus()
221                                 historical_catergory_found = True
222
223                 if not historical_catergory_found:
224                         print "Couldn't find saved category, using default."
225                         #If historical records were not kept then default to
226                         # put the focus on the first category
227                         self._categoryView.set_cursor(0, self._categoryColumn, False)
228                         self._categoryView.grab_focus()
229
230                 self._select_default_unit()
231
232         def _save_settings(self):
233                 """
234                 This routine saves the selections to a file, and
235                 should therefore only be called when exiting the program.
236
237                 Update selections dictionary which consists of the following keys:
238                 'self._selectedCategory': full name of selected category
239                 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
240                 [categoryname: #1 displayed unit, #2 displayed unit]
241                 """
242                 #Determine the contents of the selected category row
243                 selected, iter = self._categoryView.get_selection().get_selected()
244                 self._selectedCategory = self._categoryModel.get_value(iter, 0)
245
246                 selections = {
247                         'selected_category': self._selectedCategory,
248                         'selected_units': self._defaultUnitForCategory
249                 }
250                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
251                 pickle.dump(selections, open(selectionsDatPath, 'w'))
252
253                 #Get last size of app and save it
254                 window_settings = {
255                         'size': self._mainWindow.get_size()
256                 }
257                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
258                 pickle.dump(window_settings, open(windowDatPath, 'w'))
259
260         def _clear_find(self):
261                 # switch to "new find" state
262                 self._find_result = []
263                 self._findIndex = 0
264
265                 # Clear our user message
266                 self._findLabel.set_text('')
267
268         def _find_first(self):
269                 assert len(self._find_result) == 0
270                 assert self._findIndex == 0
271                 findString = string.lower(string.strip(self._findEntry.get_text()))
272                 if not findString:
273                         return
274
275                 # Gather info on all the matching units from all categories
276                 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
277                         units = unit_data.get_units(category)
278                         for unitIndex, unit in enumerate(units):
279                                 loweredUnit = unit.lower()
280                                 if loweredUnit in findString or findString in loweredUnit:
281                                         self._find_result.append((category, unit, catIndex, unitIndex))
282
283         def _update_find_selection(self):
284                 assert 0 < len(self._find_result)
285
286                 #check if next find is in a new category (prevent category changes when unnecessary
287                 if self._selectedCategory != self._find_result[self._findIndex][0]:
288                         self._categoryView.set_cursor(
289                                 self._find_result[self._findIndex][2], self._categoryColumn, False
290                         )
291
292                 self._unitsView.set_cursor(
293                         self._find_result[self._findIndex][3], self._unitNameColumn, True
294                 )
295
296         def _find_next(self):
297                 """
298                 check if 'new find' or 'last find' or 'next-find'
299
300                 new-find = run the find algorithm which also selects the first found unit
301                          = self._findIndex = 0 and self._find_result = []
302
303                 last-find = restart from top again
304                           = self._findIndex = len(self._find_result)
305
306                 next-find = continue to next found location
307                            = self._findIndex = 0 and len(self._find_result)>0
308                 """
309                 if len(self._find_result) == 0:
310                         self._find_first()
311                 else:
312                         if self._findIndex == len(self._find_result)-1:
313                                 self._findIndex = 0
314                         else:
315                                 self._findIndex += 1
316
317                 if not self._find_result:
318                         self._findLabel.set_text('Text not found')
319                 else:
320                         self._update_find_selection()
321                         resultsLeft = len(self._find_result) - self._findIndex - 1
322                         self._findLabel.set_text(
323                                 '%s result(s) left' % (resultsLeft, )
324                         )
325
326         def _find_previous(self):
327                 """
328                 check if 'new find' or 'last find' or 'next-find'
329
330                 new-find = run the find algorithm which also selects the first found unit
331                          = self._findIndex = 0 and self._find_result = []
332
333                 last-find = restart from top again
334                           = self._findIndex = len(self._find_result)
335
336                 next-find = continue to next found location
337                            = self._findIndex = 0 and len(self._find_result)>0
338                 """
339                 if len(self._find_result) == 0:
340                         self._find_first()
341                 else:
342                         if self._findIndex == 0:
343                                 self._findIndex = len(self._find_result)-1
344                         else:
345                                 self._findIndex -= 1
346
347                 if not self._find_result:
348                         self._findLabel.set_text('Text not found')
349                 else:
350                         self._update_find_selection()
351                         resultsLeft = len(self._find_result) - self._findIndex - 1
352                         self._findLabel.set_text(
353                                 '%s result(s) left' % (resultsLeft, )
354                         )
355
356         def _toggle_find(self):
357                 if self._searchLayout.get_property("visible"):
358                         self._searchLayout.hide()
359                 else:
360                         self._searchLayout.show()
361
362         def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
363                 leftUnitText = self._unitModel.get_value(leftItr, 0)
364                 rightUnitText = self._unitModel.get_value(rightItr, 0)
365                 return cmp(leftUnitText, rightUnitText)
366
367         def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
368                 leftSymbolText = self._unitModel.get_value(leftItr, 2)
369                 rightSymbolText = self._unitModel.get_value(rightItr, 2)
370                 return cmp(leftSymbolText, rightSymbolText)
371
372         def _value_model_cmp(self, sortedModel, leftItr, rightItr):
373                 #special sorting exceptions for ascii values (instead of float values)
374                 if self._selectedCategory == "Computer Numbers":
375                         leftValue = self._unitModel.get_value(leftItr, 1)
376                         rightValue = self._unitModel.get_value(rightItr, 1)
377                 else:
378                         leftValueText = self._unitModel.get_value(leftItr, 1)
379                         leftValue = float(leftValueText) if leftValueText else 0.0
380
381                         rightValueText = self._unitModel.get_value(rightItr, 1)
382                         rightValue = float(rightValueText) if rightValueText else 0.0
383                 return cmp(leftValue, rightValue)
384
385         def _get_column_sort_stuff(self):
386                 columns = (
387                         (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
388                         (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
389                         (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
390                 )
391                 return columns
392
393         def _switch_category(self, category):
394                 self._selectedCategory = category
395                 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategory]
396
397                 #Fill up the units descriptions and clear the value cells
398                 self._clear_visible_unit_data()
399                 for key in unit_data.get_units(self._selectedCategory):
400                         iter = self._unitModel.append()
401                         self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
402                 self._sortedUnitModel.sort_column_changed()
403
404                 self._select_default_unit()
405
406         def _clear_visible_unit_data(self):
407                 self._unitDescription.get_buffer().set_text("")
408                 self._unitName.set_text('')
409                 self._unitValue.set_text('')
410                 self._unitSymbol.set_text('')
411
412                 self._previousUnitName.set_text('')
413                 self._previousUnitValue.set_text('')
414                 self._previousUnitSymbol.set_text('')
415
416                 self._unitModel.clear()
417
418         def _select_default_unit(self):
419                 # Restore the previous historical settings of previously selected units
420                 # in this newly selected category
421                 if self._selectedCategory in self._defaultUnitForCategory:
422                         units = unit_data.get_units(self._selectedCategory)
423
424                         #Restore oldest selection first.
425                         if self._defaultUnitForCategory[self._selectedCategory][1]:
426                                 unitIndex = units.index(self._defaultUnitForCategory[self._selectedCategory][1])
427                                 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
428
429                         #Restore newest selection second.
430                         if self._defaultUnitForCategory[self._selectedCategory][0]:
431                                 unitIndex = units.index(self._defaultUnitForCategory[self._selectedCategory][0])
432                                 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
433
434                 # select the text so user can start typing right away
435                 self._unitValue.grab_focus()
436                 self._unitValue.select_region(0, -1)
437
438         def _sanitize_value(self, userEntry):
439                 if self._selectedCategory == "Computer Numbers":
440                         if userEntry == '':
441                                 value = '0'
442                         else:
443                                 value = userEntry
444                 else:
445                         if userEntry == '':
446                                 value = 0.0
447                         else:
448                                 value = float(userEntry)
449                 return value
450
451         def _on_shortlist_changed(self, *args):
452                 try:
453                         raise NotImplementedError("%s" % self._shortlistcheck.get_active())
454                 except Exception:
455                         _moduleLogger.exception("")
456
457         def _on_edit_shortlist(self, *args):
458                 try:
459                         raise NotImplementedError("%s" % self._toggleShortList.get_active())
460                 except Exception:
461                         _moduleLogger.exception("")
462
463         def _on_user_clear_selections(self, *args):
464                 try:
465                         selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
466                         os.remove(selectionsDatPath)
467                         self._defaultUnitForCategory = {}
468                 except Exception:
469                         _moduleLogger.exception("")
470
471         def _on_key_press(self, widget, event, *args):
472                 """
473                 @note Hildon specific
474                 """
475                 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
476                 try:
477                         if (
478                                 event.keyval == gtk.keysyms.F6 or
479                                 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
480                         ):
481                                 if self._isFullScreen:
482                                         self._mainWindow.unfullscreen()
483                                 else:
484                                         self._mainWindow.fullscreen()
485                         elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
486                                 self._toggle_find()
487                         elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
488                                 self._find_previous()
489                         elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
490                                 self._find_next()
491                 except Exception, e:
492                         _moduleLogger.exception("")
493
494         def _on_window_state_change(self, widget, event, *args):
495                 """
496                 @note Hildon specific
497                 """
498                 try:
499                         if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
500                                 self._isFullScreen = True
501                         else:
502                                 self._isFullScreen = False
503                 except Exception, e:
504                         _moduleLogger.exception("")
505
506         def _on_findEntry_changed(self, *args):
507                 """
508                 Clear out find results since the user wants to look for something new
509                 """
510                 try:
511                         self._clear_find()
512                 except Exception:
513                         _moduleLogger.exception("")
514
515         def _on_find_activate(self, *args):
516                 try:
517                         self._find_next()
518                         self._findButton.grab_focus()
519                 except Exception:
520                         _moduleLogger.exception("")
521
522         def _on_click_unit_column(self, col):
523                 """
524                 Sort the contents of the col when the user clicks on the title.
525                 """
526                 try:
527                         #Determine which column requires sorting
528                         columns = self._get_column_sort_stuff()
529                         for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
530                                 if col is maybeCol:
531                                         direction = getattr(self, directionName)
532                                         gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
533
534                                         # cause a sort
535                                         self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
536
537                                         # set the visual for sorting
538                                         col.set_sort_indicator(True)
539                                         col.set_sort_order(not direction)
540
541                                         setattr(self, directionName, not direction)
542                                         break
543                                 else:
544                                         maybeCol.set_sort_indicator(False)
545                         else:
546                                 assert False, "Unknown column: %s" % (col.get_title(), )
547                 except Exception:
548                         _moduleLogger.exception("")
549
550         def _on_click_category(self, *args):
551                 try:
552                         selected, iter = self._categoryView.get_selection().get_selected()
553                         selectedCategory = self._categoryModel.get_value(iter, 0)
554                         self._switch_category(selectedCategory)
555                 except Exception:
556                         _moduleLogger.exception("")
557
558         def _on_click_unit(self, *args):
559                 try:
560                         selected, iter = self._unitsView.get_selection().get_selected()
561                         selected_unit = selected.get_value(iter, 0)
562                         unit_spec = self._unitDataInCategory[selected_unit]
563
564                         if self._unitName.get_text() != selected_unit:
565                                 self._previousUnitName.set_text(self._unitName.get_text())
566                                 self._previousUnitValue.set_text(self._unitValue.get_text())
567                                 self._previousUnitSymbol.set_text(self._unitSymbol.get())
568
569                         self._unitName.set_text(selected_unit)
570                         self._unitValue.set_text(selected.get_value(iter, 1))
571                         buffer = self._unitDescription.get_buffer()
572                         buffer.set_text(unit_spec[2])
573                         self._unitSymbol.set_text(unit_spec[1]) # put units into label text
574
575                         if self._unitValue.get_text() == '':
576                                 if self._selectedCategory == "Computer Numbers":
577                                         self._unitValue.set_text("0")
578                                 else:
579                                         self._unitValue.set_text("0.0")
580
581                         self._defaultUnitForCategory[self._selectedCategory] = [
582                                 self._unitName.get_text(), self._previousUnitName.get_text()
583                         ]
584
585                         # select the text so user can start typing right away
586                         self._unitValue.grab_focus()
587                         self._unitValue.select_region(0, -1)
588                 except Exception:
589                         _moduleLogger.exception("")
590
591         def _on_unit_value_changed(self, *args):
592                 try:
593                         if self._unitName.get_text() == '':
594                                 return
595                         if not self._unitValue.is_focus():
596                                 return
597
598                         #retrieve the conversion function and value from the selected unit
599                         value = self._sanitize_value(self._unitValue.get_text())
600                         func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
601                         base = func.to_base(value, arg)
602
603                         #point to the first row
604                         for row in self._unitModel:
605                                 func, arg = self._unitDataInCategory[row[0]][0]
606                                 row[1] = str(func.from_base(base, arg))
607
608                         # Update the secondary unit entry
609                         if self._previousUnitName.get_text() != '':
610                                 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
611                                 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
612                 except Exception:
613                         _moduleLogger.exception("")
614
615         def _on_previous_unit_value_changed(self, *args):
616                 try:
617                         if self._previousUnitName.get_text() == '':
618                                 return
619                         if not self._previousUnitValue.is_focus():
620                                 return
621
622                         #retrieve the conversion function and value from the selected unit
623                         value = self._sanitize_value(self._previousUnitValue.get_text())
624                         func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
625                         base = func.to_base(value, arg)
626
627                         #point to the first row
628                         for row in self._unitModel:
629                                 func, arg = self._unitDataInCategory[row[0]][0]
630                                 row[1] = str(func.from_base(base, arg))
631
632                         # Update the primary unit entry
633                         func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
634                         self._unitValue.set_text(str(func.from_base(base, arg, )))
635                 except Exception:
636                         _moduleLogger.exception("")
637
638         def messagebox_ok_clicked(self, a):
639                 messagebox.hide()
640
641         def _on_user_write_units(self, a):
642                 ''"Write the list of categories and units to stdout for documentation purposes.''"
643                 messagebox_model = gtk.TextBuffer(None)
644                 messageboxtext.set_buffer(messagebox_model)
645                 messagebox_model.insert_at_cursor(_(u'The units are being written to stdout. You can capture this printout by starting gonvert from the command line as follows: \n$ gonvert > file.txt'), -1)
646                 messagebox.show()
647                 while gtk.events_pending():
648                         gtk.mainiteration(False)
649
650                 total_categories = 0
651                 total_units = 0
652                 print 'gonvert-%s%s' % (
653                         constants.__version__,
654                         _(u' - Unit Conversion Utility  - Convertible units listing: ')
655                 )
656                 for category_key in unit_data.UNIT_CATEGORIES:
657                         total_categories = total_categories + 1
658                         print category_key, ": "
659                         self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[category_key]
660                         unit_keys = unit_data.get_units_from_category(self._unitDataInCategory)
661                         for unit_key in unit_keys:
662                                 total_units = total_units + 1
663                                 print "\t", unit_key
664                 print total_categories, ' categories'
665                 print total_units, ' units'
666
667         def _on_about_clicked(self, a):
668                 dlg = gtk.AboutDialog()
669                 dlg.set_name(constants.__pretty_app_name__)
670                 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
671                 dlg.set_copyright("Copyright 2009 - GPL")
672                 dlg.set_comments("")
673                 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
674                 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
675                 dlg.run()
676                 dlg.destroy()
677
678         def _on_user_exit(self, *args):
679                 try:
680                         self._save_settings()
681                 except Exception:
682                         _moduleLogger.exception("")
683                 finally:
684                         gtk.main_quit()
685
686
687 def main():
688         logging.basicConfig(level = logging.DEBUG)
689         try:
690                 os.makedirs(constants._data_path_)
691         except OSError, e:
692                 if e.errno != 17:
693                         raise
694
695         gonvert = Gonvert()
696         gtk.main()
697
698
699 if __name__ == "__main__":
700         main()