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