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