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