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