e45d78ff61f46c18e7c6be2699fa4e231129c3e4
[gonvert] / src / gonvert_glade.py
1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
3
4 import os
5 import pickle
6 import gettext
7 import logging
8
9 import gobject
10 import gtk
11 import gtk.glade
12 import gtk.gdk
13
14 import constants
15 import unit_data
16
17
18 _moduleLogger = logging.getLogger("gonvert_glade")
19 PROFILE_STARTUP = False
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
190                 #Restore selections from previously saved settings if it exists and is valid.
191                 historical_catergory_found = False
192                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
193                 if os.path.exists(selectionsDatPath):
194                         #Retrieving previous selections from ~/.gonvert/selections.dat
195                         selections = pickle.load(open(selectionsDatPath, 'r'))
196                         #Restoring previous selections.
197                         #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
198                         if 'selected_units' in selections:
199                                 self._defaultUnitForCategory = selections['selected_units']
200                         #Make sure that the 'self._selectedCategoryName' has been stored.
201                         if 'selected_category' in selections:
202                                 #Match an available category to the previously selected category.
203                                 for counter in range(len(unit_data.UNIT_CATEGORIES)):
204                                         if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
205                                                 # Restore the previously selected category.
206                                                 self._categoryView.set_cursor(counter, self._categoryColumn, False)
207                                                 self._categoryView.grab_focus()
208                                 historical_catergory_found = True
209
210                 if not historical_catergory_found:
211                         print "Couldn't find saved category, using default."
212                         #If historical records were not kept then default to
213                         # put the focus on the first category
214                         self._categoryView.set_cursor(0, self._categoryColumn, False)
215                         self._categoryView.grab_focus()
216
217                 self._select_default_unit()
218
219         def _save_settings(self):
220                 """
221                 This routine saves the selections to a file, and
222                 should therefore only be called when exiting the program.
223
224                 Update selections dictionary which consists of the following keys:
225                 'self._selectedCategoryName': full name of selected category
226                 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
227                 [categoryname: #1 displayed unit, #2 displayed unit]
228                 """
229                 #Determine the contents of the selected category row
230                 selected, iter = self._categoryView.get_selection().get_selected()
231                 self._selectedCategoryName = self._categoryModel.get_value(iter, 0)
232
233                 selections = {
234                         'selected_category': self._selectedCategoryName,
235                         'selected_units': self._defaultUnitForCategory
236                 }
237                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
238                 pickle.dump(selections, open(selectionsDatPath, 'w'))
239
240                 #Get last size of app and save it
241                 window_settings = {
242                         'size': self._mainWindow.get_size()
243                 }
244                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
245                 pickle.dump(window_settings, open(windowDatPath, 'w'))
246
247         def _clear_find(self):
248                 # switch to "new find" state
249                 self._find_result = []
250                 self._findIndex = 0
251
252                 # Clear our user message
253                 self._findLabel.set_text('')
254
255         def _find_first(self):
256                 assert len(self._find_result) == 0
257                 assert self._findIndex == 0
258                 findString = self._findEntry.get_text().strip().lower()
259                 if not findString:
260                         return
261
262                 # Gather info on all the matching units from all categories
263                 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
264                         units = unit_data.get_units(category)
265                         for unitIndex, unit in enumerate(units):
266                                 loweredUnit = unit.lower()
267                                 if loweredUnit in findString or findString in loweredUnit:
268                                         self._find_result.append((category, unit, catIndex, unitIndex))
269
270         def _update_find_selection(self):
271                 assert 0 < len(self._find_result)
272
273                 #check if next find is in a new category (prevent category changes when unnecessary
274                 if self._selectedCategoryName != self._find_result[self._findIndex][0]:
275                         self._categoryView.set_cursor(
276                                 self._find_result[self._findIndex][2], self._categoryColumn, False
277                         )
278
279                 self._unitsView.set_cursor(
280                         self._find_result[self._findIndex][3], self._unitNameColumn, True
281                 )
282
283         def _find_next(self):
284                 if len(self._find_result) == 0:
285                         self._find_first()
286                 else:
287                         if self._findIndex == len(self._find_result)-1:
288                                 self._findIndex = 0
289                         else:
290                                 self._findIndex += 1
291
292                 if not self._find_result:
293                         self._findLabel.set_text('Text not found')
294                 else:
295                         self._update_find_selection()
296                         resultsLeft = len(self._find_result) - self._findIndex - 1
297                         self._findLabel.set_text(
298                                 '%s result(s) left' % (resultsLeft, )
299                         )
300
301         def _find_previous(self):
302                 if len(self._find_result) == 0:
303                         self._find_first()
304                 else:
305                         if self._findIndex == 0:
306                                 self._findIndex = len(self._find_result)-1
307                         else:
308                                 self._findIndex -= 1
309
310                 if not self._find_result:
311                         self._findLabel.set_text('Text not found')
312                 else:
313                         self._update_find_selection()
314                         resultsLeft = len(self._find_result) - self._findIndex - 1
315                         self._findLabel.set_text(
316                                 '%s result(s) left' % (resultsLeft, )
317                         )
318
319         def _toggle_find(self):
320                 if self._searchLayout.get_property("visible"):
321                         self._searchLayout.hide()
322                 else:
323                         self._searchLayout.show()
324
325         def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
326                 leftUnitText = self._unitModel.get_value(leftItr, 0)
327                 rightUnitText = self._unitModel.get_value(rightItr, 0)
328                 return cmp(leftUnitText, rightUnitText)
329
330         def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
331                 leftSymbolText = self._unitModel.get_value(leftItr, 2)
332                 rightSymbolText = self._unitModel.get_value(rightItr, 2)
333                 return cmp(leftSymbolText, rightSymbolText)
334
335         def _value_model_cmp(self, sortedModel, leftItr, rightItr):
336                 #special sorting exceptions for ascii values (instead of float values)
337                 if self._selectedCategoryName == "Computer Numbers":
338                         leftValue = self._unitModel.get_value(leftItr, 1)
339                         rightValue = self._unitModel.get_value(rightItr, 1)
340                 else:
341                         leftValueText = self._unitModel.get_value(leftItr, 1)
342                         leftValue = float(leftValueText) if leftValueText else 0.0
343
344                         rightValueText = self._unitModel.get_value(rightItr, 1)
345                         rightValue = float(rightValueText) if rightValueText else 0.0
346                 return cmp(leftValue, rightValue)
347
348         def _get_column_sort_stuff(self):
349                 columns = (
350                         (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
351                         (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
352                         (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
353                 )
354                 return columns
355
356         def _switch_category(self, category):
357                 self._selectedCategoryName = category
358                 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategoryName]
359
360                 #Fill up the units descriptions and clear the value cells
361                 self._clear_visible_unit_data()
362                 for key in unit_data.get_units(self._selectedCategoryName):
363                         iter = self._unitModel.append()
364                         self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
365                 self._sortedUnitModel.sort_column_changed()
366
367                 self._select_default_unit()
368
369         def _clear_visible_unit_data(self):
370                 self._unitDescription.get_buffer().set_text("")
371                 self._unitName.set_text('')
372                 self._unitValue.set_text('')
373                 self._unitSymbol.set_text('')
374
375                 self._previousUnitName.set_text('')
376                 self._previousUnitValue.set_text('')
377                 self._previousUnitSymbol.set_text('')
378
379                 self._unitModel.clear()
380
381         def _select_default_unit(self):
382                 # Restore the previous historical settings of previously selected units
383                 # in this newly selected category
384                 defaultPrimary = unit_data.get_base_unit(self._selectedCategoryName)
385                 defaultSecondary = ""
386                 if self._selectedCategoryName in self._defaultUnitForCategory:
387                         if self._defaultUnitForCategory[self._selectedCategoryName][0]:
388                                 defaultPrimary = self._defaultUnitForCategory[self._selectedCategoryName][0]
389                         if self._defaultUnitForCategory[self._selectedCategoryName][1]:
390                                 defaultSecondary = self._defaultUnitForCategory[self._selectedCategoryName][1]
391
392                 units = unit_data.get_units(self._selectedCategoryName)
393
394                 #Restore oldest selection first.
395                 if defaultPrimary:
396                         unitIndex = units.index(defaultPrimary)
397                         self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
398
399                 #Restore newest selection second.
400                 if defaultSecondary:
401                         unitIndex = units.index(defaultSecondary)
402                         self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
403
404                 # select the text so user can start typing right away
405                 self._unitValue.grab_focus()
406                 self._unitValue.select_region(0, -1)
407
408         def _sanitize_value(self, userEntry):
409                 if self._selectedCategoryName == "Computer Numbers":
410                         if userEntry == '':
411                                 value = '0'
412                         else:
413                                 value = userEntry
414                 else:
415                         if userEntry == '':
416                                 value = 0.0
417                         else:
418                                 value = float(userEntry)
419                 return value
420
421         def _on_shortlist_changed(self, *args):
422                 try:
423                         raise NotImplementedError("%s" % self._shortlistcheck.get_active())
424                 except Exception:
425                         _moduleLogger.exception("")
426
427         def _on_edit_shortlist(self, *args):
428                 try:
429                         raise NotImplementedError("%s" % self._toggleShortList.get_active())
430                 except Exception:
431                         _moduleLogger.exception("")
432
433         def _on_user_clear_selections(self, *args):
434                 try:
435                         selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
436                         os.remove(selectionsDatPath)
437                         self._defaultUnitForCategory = {}
438                 except Exception:
439                         _moduleLogger.exception("")
440
441         def _on_key_press(self, widget, event, *args):
442                 """
443                 @note Hildon specific
444                 """
445                 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
446                 try:
447                         if (
448                                 event.keyval == gtk.keysyms.F6 or
449                                 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
450                         ):
451                                 if self._isFullScreen:
452                                         self._mainWindow.unfullscreen()
453                                 else:
454                                         self._mainWindow.fullscreen()
455                         elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
456                                 self._toggle_find()
457                         elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
458                                 self._find_previous()
459                         elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
460                                 self._find_next()
461                 except Exception, e:
462                         _moduleLogger.exception("")
463
464         def _on_window_state_change(self, widget, event, *args):
465                 """
466                 @note Hildon specific
467                 """
468                 try:
469                         if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
470                                 self._isFullScreen = True
471                         else:
472                                 self._isFullScreen = False
473                 except Exception, e:
474                         _moduleLogger.exception("")
475
476         def _on_findEntry_changed(self, *args):
477                 """
478                 Clear out find results since the user wants to look for something new
479                 """
480                 try:
481                         self._clear_find()
482                 except Exception:
483                         _moduleLogger.exception("")
484
485         def _on_find_activate(self, *args):
486                 try:
487                         self._find_next()
488                         self._findButton.grab_focus()
489                 except Exception:
490                         _moduleLogger.exception("")
491
492         def _on_click_unit_column(self, col):
493                 """
494                 Sort the contents of the col when the user clicks on the title.
495                 """
496                 try:
497                         #Determine which column requires sorting
498                         columns = self._get_column_sort_stuff()
499                         for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
500                                 if col is maybeCol:
501                                         direction = getattr(self, directionName)
502                                         gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
503
504                                         # cause a sort
505                                         self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
506
507                                         # set the visual for sorting
508                                         col.set_sort_indicator(True)
509                                         col.set_sort_order(not direction)
510
511                                         setattr(self, directionName, not direction)
512                                         break
513                                 else:
514                                         maybeCol.set_sort_indicator(False)
515                         else:
516                                 assert False, "Unknown column: %s" % (col.get_title(), )
517                 except Exception:
518                         _moduleLogger.exception("")
519
520         def _on_click_category(self, *args):
521                 try:
522                         selected, iter = self._categoryView.get_selection().get_selected()
523                         if iter is None:
524                                 # User is typing in an invalid string, not selecting any category
525                                 return
526                         selectedCategory = self._categoryModel.get_value(iter, 0)
527                         self._switch_category(selectedCategory)
528                 except Exception:
529                         _moduleLogger.exception("")
530
531         def _on_click_unit(self, *args):
532                 try:
533                         selected, iter = self._unitsView.get_selection().get_selected()
534                         selected_unit = selected.get_value(iter, 0)
535                         unit_spec = self._unitDataInCategory[selected_unit]
536
537                         if self._unitName.get_text() != selected_unit:
538                                 self._previousUnitName.set_text(self._unitName.get_text())
539                                 self._previousUnitValue.set_text(self._unitValue.get_text())
540                                 self._previousUnitSymbol.set_text(self._unitSymbol.get())
541
542                         self._unitName.set_text(selected_unit)
543                         self._unitValue.set_text(selected.get_value(iter, 1))
544                         buffer = self._unitDescription.get_buffer()
545                         buffer.set_text(unit_spec[2])
546                         self._unitSymbol.set_text(unit_spec[1]) # put units into label text
547
548                         if self._unitValue.get_text() == '':
549                                 if self._selectedCategoryName == "Computer Numbers":
550                                         self._unitValue.set_text("0")
551                                 else:
552                                         self._unitValue.set_text("0.0")
553
554                         self._defaultUnitForCategory[self._selectedCategoryName] = [
555                                 self._unitName.get_text(), self._previousUnitName.get_text()
556                         ]
557
558                         # select the text so user can start typing right away
559                         self._unitValue.grab_focus()
560                         self._unitValue.select_region(0, -1)
561                 except Exception:
562                         _moduleLogger.exception("")
563
564         def _on_unit_value_changed(self, *args):
565                 try:
566                         if self._unitName.get_text() == '':
567                                 return
568                         if not self._unitValue.is_focus():
569                                 return
570
571                         #retrieve the conversion function and value from the selected unit
572                         value = self._sanitize_value(self._unitValue.get_text())
573                         func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
574                         base = func.to_base(value, arg)
575
576                         #point to the first row
577                         for row in self._unitModel:
578                                 func, arg = self._unitDataInCategory[row[0]][0]
579                                 row[1] = str(func.from_base(base, arg))
580
581                         # Update the secondary unit entry
582                         if self._previousUnitName.get_text() != '':
583                                 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
584                                 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
585                 except Exception:
586                         _moduleLogger.exception("")
587
588         def _on_previous_unit_value_changed(self, *args):
589                 try:
590                         if self._previousUnitName.get_text() == '':
591                                 return
592                         if not self._previousUnitValue.is_focus():
593                                 return
594
595                         #retrieve the conversion function and value from the selected unit
596                         value = self._sanitize_value(self._previousUnitValue.get_text())
597                         func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
598                         base = func.to_base(value, arg)
599
600                         #point to the first row
601                         for row in self._unitModel:
602                                 func, arg = self._unitDataInCategory[row[0]][0]
603                                 row[1] = str(func.from_base(base, arg))
604
605                         # Update the primary unit entry
606                         func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
607                         self._unitValue.set_text(str(func.from_base(base, arg, )))
608                 except Exception:
609                         _moduleLogger.exception("")
610
611         def _on_about_clicked(self, a):
612                 dlg = gtk.AboutDialog()
613                 dlg.set_name(constants.__pretty_app_name__)
614                 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
615                 dlg.set_copyright("Copyright 2009 - GPL")
616                 dlg.set_comments("")
617                 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
618                 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
619                 dlg.run()
620                 dlg.destroy()
621
622         def _on_user_exit(self, *args):
623                 try:
624                         self._save_settings()
625                 except Exception:
626                         _moduleLogger.exception("")
627                 finally:
628                         gtk.main_quit()
629
630
631 def main():
632         logging.basicConfig(level = logging.DEBUG)
633         try:
634                 os.makedirs(constants._data_path_)
635         except OSError, e:
636                 if e.errno != 17:
637                         raise
638
639         gonvert = Gonvert()
640         if not PROFILE_STARTUP:
641                 gtk.main()
642
643
644 if __name__ == "__main__":
645         main()