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