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