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