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