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