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