3f1033fa5d34b479c5f846ff0dc5a39cdac7c03d
[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                 #Insert a column into the category list even though the heading will not be seen
126                 renderer = gtk.CellRendererText()
127                 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
128                 self._categoryColumn.set_property('resizable', 1)
129                 self._categoryColumn.add_attribute(renderer, 'text', 0)
130                 self._categoryView.append_column(self._categoryColumn)
131
132                 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
133                 self._categoryView.set_model(self._categoryModel)
134                 #colourize each row differently for easier reading
135                 self._categoryView.set_property('rules_hint', 1)
136
137                 #Populate the catagories list
138                 for key in unit_data.UNIT_CATEGORIES:
139                         iter = self._categoryModel.append()
140                         self._categoryModel.set(iter, 0, key)
141
142                 #--------- connections to GUI ----------------
143                 dic = {
144                         "on_exit_menu_activate": self._on_user_exit,
145                         "on_main_window_destroy": self._on_user_exit,
146                         "on_categoryView_select_row": self._on_click_category,
147                         "on_unitsView__on_click_unit_column": self._on_click_unit_column,
148                         "on_unitValue_changed": self._on_unit_value_changed,
149                         "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
150                         "on_writeUnitsMenuItem_activate": self._on_user_write_units,
151                         "on_findButton_clicked": self._on_user_find_units,
152                         "on_findEntry_key_press_event": self._on_find_key_press,
153                         "on_findEntry_changed": self._on_findEntry_changed,
154                         "on_aboutMenuItem_activate": self._on_about_clicked,
155                         "on_messagebox_ok_clicked": self.messagebox_ok_clicked,
156                         "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
157                         "on_unitsView_cursor_changed": self._on_click_unit,
158                         "on_unitsView_button_released": self._on_button_released,
159                         "on_shortlistcheck_toggled": self._on_shortlist_changed,
160                         "on_toggleShortList_activate": self._on_edit_shortlist,
161                 }
162                 widgets.signal_autoconnect(dic)
163
164                 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
165                 iconPath = pixmapspath + '/gonvert.png'
166                 if os.path.exists(iconPath):
167                         self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
168                 else:
169                         _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
170
171                 #Restore window size from previously saved settings if it exists and is valid.
172                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
173                 if os.path.exists(windowDatPath):
174                         #Retrieving previous window settings from ~/.gonvert/window.dat
175                         saved_window = pickle.load(open(windowDatPath, "r"))
176                         #If the 'size' has been stored, then extract size from saved_window.
177                         if 'size' in saved_window:
178                                 a, b = saved_window['size']
179                                 self._mainWindow.resize(a, b)
180                         else:
181                                 #Maximize if no previous size was found
182                                 #self._mainWindow.maximize()
183                                 pass
184                 else:
185                         #Maximize if no previous window.dat file was found
186                         #self._mainWindow.maximize()
187                         pass
188
189                 #Restore selections from previously saved settings if it exists and is valid.
190                 historical_catergory_found = False
191                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
192                 if os.path.exists(selectionsDatPath):
193                         #Retrieving previous selections from ~/.gonvert/selections.dat
194                         selections = pickle.load(open(selectionsDatPath, 'r'))
195                         #Restoring previous selections.
196                         #If the 'selected_unts' has been stored, then extract self._selected_units from selections.
197                         if 'selected_units' in selections:
198                                 self._selected_units = selections['selected_units']
199                         #Make sure that the 'self._selected_category' has been stored.
200                         if 'selected_category' in selections:
201                                 #Match an available category to the previously selected category.
202                                 for counter in range(len(unit_data.UNIT_CATEGORIES)):
203                                         if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
204                                                 # Restore the previously selected category.
205                                                 self._categoryView.set_cursor(counter, self._categoryColumn, False)
206                                                 self._categoryView.grab_focus()
207                                 historical_catergory_found = True
208
209                 if not historical_catergory_found:
210                         print "Couldn't find saved category, using default."
211                         #If historical records were not kept then default to
212                         # put the focus on the first category
213                         self._categoryView.set_cursor(0, self._categoryColumn, False)
214                         self._categoryView.grab_focus()
215
216                 self.restore_units()
217
218         def _on_shortlist_changed(self, a):
219                 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
220
221         def _on_edit_shortlist(self, a):
222                 raise NotImplementedError("%s" % self._toggleShortList.get_active())
223
224         def _on_user_clear_selections(self, a):
225                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
226                 os.remove(selectionsDatPath)
227                 self._selected_units = {}
228
229         def _on_user_exit(self, a):
230                 """
231                 This routine saves the selections to a file, and
232                 should therefore only be called when exiting the program.
233
234                 Update selections dictionary which consists of the following keys:
235                 'self._selected_category': full name of selected category
236                 'self._selected_units': self._selected_units dictionary which contains:
237                 [categoryname: #1 displayed unit, #2 displayed unit]
238                 """
239                 #Determine the contents of the selected category row
240                 selected, iter = self._categoryView.get_selection().get_selected()
241                 self._selected_category = self._categoryModel.get_value(iter, 0)
242
243                 selections = {
244                         'selected_category': self._selected_category,
245                         'selected_units': self._selected_units
246                 }
247                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
248                 pickle.dump(selections, open(selectionsDatPath, 'w'))
249
250                 #Get last size of app and save it
251                 window_settings = {
252                         'size': self._mainWindow.get_size()
253                 }
254                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
255                 pickle.dump(window_settings, open(windowDatPath, 'w'))
256
257                 gtk.mainquit
258                 sys.exit()
259
260         def _on_findEntry_changed(self, a):
261                 #Clear out find results since the user wants to look for something new
262                 self._find_result = [] #empty find result list
263                 self._find_count = 0 #default to find result number zero
264                 self._findLabel.set_text('') #clear result
265
266         def _on_find_key_press(self, a, b):
267                 #Check if the key pressed was an ASCII key
268                 if len(b.string)>0:
269                         #Check if the key pressed was the 'Enter' key
270                         if ord(b.string[0]) == 13:
271                                 #Execute the find units function
272                                 self._on_user_find_units(1)
273
274         def _on_about_clicked(self, a):
275                 dlg = gtk.AboutDialog()
276                 dlg.set_name(constants.__pretty_app_name__)
277                 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
278                 dlg.set_copyright("Copyright 2009 - GPL")
279                 dlg.set_comments("")
280                 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
281                 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
282                 dlg.run()
283                 dlg.destroy()
284
285         def messagebox_ok_clicked(self, a):
286                 messagebox.hide()
287
288         def _on_user_find_units(self, a):
289                 #check if 'new find' or 'last find' or 'next-find'
290
291                 #new-find = run the find algorithm which also selects the first found unit
292                 #         = self._find_count = 0 and self._find_result = []
293
294                 #last-find = restart from top again
295                 #          = self._find_count = len(self._find_result)
296
297                 #next-find = continue to next found location
298                 #           = self._find_count = 0 and len(self._find_result)>0
299
300                 #check for new-find
301                 if len(self._find_result) == 0:
302                         find_string = string.lower(string.strip(self._findEntry.get_text()))
303                         #Make sure that a valid find string has been requested
304                         if len(find_string)>0:
305                                 found_a_unit = 0 #reset the 'found-a-unit' flag
306                                 cat_no = 0
307                                 for category in unit_data.UNIT_CATEGORIES:
308                                         units = unit_data.UNIT_DESCRIPTIONS[category].keys()
309                                         units.sort()
310                                         del units[0] # do not display .base_unit description key
311                                         unit_no = 0
312                                         for unit in units:
313                                                 if string.find(string.lower(unit), find_string) >= 0:
314                                                         found_a_unit = 1 #indicate that a unit was found
315                                                         #print "'", find_string, "'", " found at category = ", category, " unit = ", unit
316                                                         self._find_result.append((category, unit, cat_no, unit_no))
317                                                 unit_no = unit_no+1
318                                         cat_no = cat_no+1
319
320                                 if found_a_unit == 1:
321                                         #select the first found unit
322                                         self._find_count = 0
323                                         #check if next find is in a new category (prevent category changes when unnecessary
324                                         if self._selected_category != self._find_result[self._find_count][0]:
325                                                 self._categoryView.set_cursor(self._find_result[0][2], self._categoryColumn, False)
326                                                 self._unitsView.set_cursor(self._find_result[0][3], self._unitNameColumn, True)
327                                                 if len(self._find_result)>1:
328                                                         self._findLabel.set_text(('Press Find for next unit. '+ str(len(self._find_result))+' result(s).'))
329                                                 else:
330                                                         self._findLabel.set_text('Text not found') #Display error
331                 else: #must be next-find or last-find
332                         #check for last-find
333                         if self._find_count == len(self._find_result)-1:
334                                 #select first result
335                                 self._find_count = 0
336                                 self._categoryView.set_cursor(self._find_result[self._find_count][2], self._categoryColumn, False)
337                                 self._unitsView.set_cursor(self._find_result[self._find_count][3], self._unitNameColumn, True)
338                         else: #must be next-find
339                                 self._find_count = self._find_count+1
340                                 #check if next find is in a new category (prevent category changes when unnecessary
341                                 if self._selected_category != self._find_result[self._find_count][0]:
342                                         self._categoryView.set_cursor(self._find_result[self._find_count][2], self._categoryColumn, False)
343                                 self._unitsView.set_cursor(self._find_result[self._find_count][3], self._unitNameColumn, True)
344
345         def _on_click_unit_column(self, col):
346                 """
347                 Sort the contents of the col when the user clicks on the title.
348                 """
349                 #Determine which column requires sorting
350                 if col is self._unitNameColumn:
351                         selectedUnitColumn = 0
352                         self._unitNameColumn.set_sort_indicator(True)
353                         self._unitValueColumn.set_sort_indicator(False)
354                         self._unitSymbolColumn.set_sort_indicator(False)
355                         self._unitNameColumn.set_sort_order(not self._unit_sort_direction)
356                 elif col is self._unitValueColumn:
357                         selectedUnitColumn = 1
358                         self._unitNameColumn.set_sort_indicator(False)
359                         self._unitValueColumn.set_sort_indicator(True)
360                         self._unitSymbolColumn.set_sort_indicator(False)
361                         self._unitValueColumn.set_sort_order(not self._value_sort_direction)
362                 elif col is self._unitSymbolColumn:
363                         selectedUnitColumn = 2
364                         self._unitNameColumn.set_sort_indicator(False)
365                         self._unitValueColumn.set_sort_indicator(False)
366                         self._unitSymbolColumn.set_sort_indicator(True)
367                         self._unitSymbolColumn.set_sort_order(not self._units_sort_direction)
368                 else:
369                         assert False, "Unknown column: %s" % (col.get_title(), )
370
371                 #declare a spot to hold the sorted list
372                 sorted_list = []
373
374                 #point to the first row
375                 iter = self._unitModel.get_iter_first()
376                 row = 0
377
378                 while iter:
379                         #grab all text from columns for sorting
380
381                         #get the text from each column
382                         unit_text = self._unitModel.get_value(iter, 0)
383                         units_text = self._unitModel.get_value(iter, 2)
384
385                         #do not bother sorting if the value column is empty
386                         if self._unitModel.get_value(iter, 1) == '' and selectedUnitColumn == 1:
387                                 return
388
389                         #special sorting exceptions for ascii values (instead of float values)
390                         if self._selected_category == "Computer Numbers":
391                                 value_text = self._unitModel.get_value(iter, 1)
392                         else:
393                                 if self._unitModel.get_value(iter, 1) == None or self._unitModel.get_value(iter, 1) == '':
394                                         value_text = ''
395                                 else:
396                                         value_text = float(self._unitModel.get_value(iter, 1))
397
398                         if selectedUnitColumn == 0:
399                                 sorted_list.append((unit_text, value_text, units_text))
400                         elif selectedUnitColumn == 1:
401                                 sorted_list.append((value_text, unit_text, units_text))
402                         else:
403                                 sorted_list.append((units_text, value_text, unit_text))
404
405                         #point to the next row in the self._unitModel
406                         iter = self._unitModel.iter_next(iter)
407                         row = row+1
408
409                 #check if no calculations have been made yet (don't bother sorting)
410                 if row == 0:
411                         return
412                 else:
413                         if selectedUnitColumn == 0:
414                                 if not self._unit_sort_direction:
415                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
416                                         self._unit_sort_direction = True
417                                 else:
418                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(y), string.lower(x)))
419                                         self._unit_sort_direction = False
420                         elif selectedUnitColumn == 1:
421                                 sorted_list.sort()
422                                 if not self._value_sort_direction:
423                                         self._value_sort_direction = True
424                                 else:
425                                         sorted_list.reverse()
426                                         self._value_sort_direction = False
427                         else:
428                                 if not self._units_sort_direction:
429                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
430                                         self._units_sort_direction = True
431                                 else:
432                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(y), string.lower(x)))
433                                         self._units_sort_direction = False
434
435                         #Clear out the previous list of units
436                         self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
437                         self._unitsView.set_model(self._unitModel)
438
439                         #colourize each row differently for easier reading
440                         self._unitsView.set_property('rules_hint', 1)
441
442                         #Clear out the description
443                         text_model = gtk.TextBuffer(None)
444                         self._unitDescription.set_buffer(text_model)
445
446                         if selectedUnitColumn == 0:
447                                 for unit, value, units in sorted_list:
448                                         iter = self._unitModel.append()
449                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
450                         elif selectedUnitColumn == 1:
451                                 for value, unit, units in sorted_list:
452                                         iter = self._unitModel.append()
453                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
454                         else:
455                                 for units, value, unit in sorted_list:
456                                         iter = self._unitModel.append()
457                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
458                 return
459
460         def _on_click_category(self, row):
461                 #Clear out the previous list of units
462                 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
463                 self._unitsView.set_model(self._unitModel)
464
465                 #Colourize each row alternately for easier reading
466                 self._unitsView.set_property('rules_hint', 1)
467
468                 #Clear out the description
469                 text_model = gtk.TextBuffer(None)
470                 self._unitDescription.set_buffer(text_model)
471
472                 #Determine the contents of the selected category row
473                 selected, iter = row.get_selection().get_selected()
474
475                 self._selected_category = self._categoryModel.get_value(iter, 0)
476
477                 self._unit_sort_direction = False
478                 self._value_sort_direction = False
479                 self._units_sort_direction = False
480                 self._unitNameColumn.set_sort_indicator(False)
481                 self._unitValueColumn.set_sort_indicator(False)
482                 self._unitSymbolColumn.set_sort_indicator(False)
483
484                 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[selected.get_value(iter, 0)]
485                 keys = self._unitDataInCategory.keys()
486                 keys.sort()
487                 del keys[0] # do not display .base_unit description key
488
489                 #Fill up the units descriptions and clear the value cells
490                 for key in keys:
491                         iter = self._unitModel.append()
492                         self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
493
494                 self._unitName.set_text('')
495                 self._unitValue.set_text('')
496                 self._previousUnitName.set_text('')
497                 self._previousUnitValue.set_text('')
498                 self._unitSymbol.set_text('')
499                 self._previousUnitSymbol.set_text('')
500
501                 self.restore_units()
502
503         def restore_units(self):
504                 # Restore the previous historical settings of previously selected units in this newly selected category
505                 #Since category has just been clicked, the list will be sorted already.
506                 if self._selected_category in self._selected_units:
507                         if self._selected_units[self._selected_category][0]:
508                                 ''"debug ''"
509                                 #self._selected_units[self._selected_category] = [selected_unit, self._selected_units[self._selected_category][0]]
510
511                                 units = unit_data.UNIT_DESCRIPTIONS[self._selected_category].keys()
512                                 units.sort()
513                                 del units[0] # do not display .base_unit description key
514
515                                 #Restore oldest selection first.
516                                 if self._selected_units[self._selected_category][1]:
517                                         unit_no = 0
518                                         for unit in units:
519                                                 if unit == self._selected_units[self._selected_category][1]:
520                                                         self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
521                                                 unit_no = unit_no+1
522
523                                 #Restore newest selection second.
524                                 unit_no = 0
525                                 for unit in units:
526                                         if unit == self._selected_units[self._selected_category][0]:
527                                                 self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
528                                         unit_no = unit_no+1
529
530                 # select the text so user can start typing right away
531                 self._unitValue.grab_focus()
532                 self._unitValue.select_region(0, -1)
533
534         def _on_button_released(self, row, a):
535                 self._on_click_unit(row)
536
537         def _on_click_unit(self, row):
538                 self._calcsuppress = True #suppress calculations
539
540                 #Determine the contents of the selected row.
541                 selected, iter = self._unitsView.get_selection().get_selected()
542
543                 selected_unit = selected.get_value(iter, 0)
544
545                 unit_spec = self._unitDataInCategory[selected_unit]
546
547                 #Clear out the description
548                 text_model = gtk.TextBuffer(None)
549                 self._unitDescription.set_buffer(text_model)
550
551                 enditer = text_model.get_end_iter()
552                 text_model.insert(enditer, unit_spec[2])
553
554                 if self._unitName.get_text() != selected_unit:
555                         self._previousUnitName.set_text(self._unitName.get_text())
556                         self._previousUnitValue.set_text(self._unitValue.get_text())
557                         if self._unitSymbol.get() == None:
558                                 self._previousUnitSymbol.set_text('')
559                         else:
560                                 self._previousUnitSymbol.set_text(self._unitSymbol.get())
561                 self._unitName.set_text(selected_unit)
562
563                 self._unitValue.set_text(selected.get_value(iter, 1))
564
565                 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
566                 if self._unitValue.get_text() == '':
567                         if self._selected_category == "Computer Numbers":
568                                 self._unitValue.set_text("0")
569                         else:
570                                 self._unitValue.set_text("0.0")
571
572                 #For historical purposes, record this unit as the most recent one in this category.
573                 # Also, if a previous unit exists, then shift that previous unit to oldest unit.
574                 if self._selected_category in self._selected_units:
575                         if self._selected_units[self._selected_category][0]:
576                                 self._selected_units[self._selected_category] = [selected_unit, self._selected_units[self._selected_category][0]]
577                 else:
578                         self._selected_units[self._selected_category] = [selected_unit, '']
579
580                 # select the text so user can start typing right away
581                 self._unitValue.grab_focus()
582                 self._unitValue.select_region(0, -1)
583
584                 self._calcsuppress = False #enable calculations
585
586         def _on_user_write_units(self, a):
587                 ''"Write the list of categories and units to stdout for documentation purposes.''"
588                 messagebox_model = gtk.TextBuffer(None)
589                 messageboxtext.set_buffer(messagebox_model)
590                 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)
591                 messagebox.show()
592                 while gtk.events_pending():
593                         gtk.mainiteration(False)
594
595                 total_categories = 0
596                 total_units = 0
597                 print 'gonvert-%s%s' % (
598                         constants.__version__,
599                         _(u' - Unit Conversion Utility  - Convertible units listing: ')
600                 )
601                 for category_key in unit_data.UNIT_CATEGORIES:
602                         total_categories = total_categories + 1
603                         print category_key, ": "
604                         self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[category_key]
605                         unit_keys = self._unitDataInCategory.keys()
606                         unit_keys.sort()
607                         del unit_keys[0] # do not display .base_unit description key
608                         for unit_key in unit_keys:
609                                 total_units = total_units + 1
610                                 print "\t", unit_key
611                 print total_categories, ' categories'
612                 print total_units, ' units'
613
614         def _on_unit_value_changed(self, a):
615                 if self._calcsuppress:
616                         #self._calcsuppress = False
617                         return
618                 # determine if value to be calculated is empty
619                 if self._selected_category == "Computer Numbers":
620                         if self._unitValue.get_text() == '':
621                                 value = '0'
622                         else:
623                                 value = self._unitValue.get_text()
624                 else:
625                         if self._unitValue.get_text() == '':
626                                 value = 0.0
627                         else:
628                                 value = float(self._unitValue.get_text())
629
630                 if self._unitName.get_text() != '':
631                         func, arg = self._unitDataInCategory[self._unitName.get_text()][0] #retrieve the conversion function and value from the selected unit
632                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
633
634                         keys = self._unitDataInCategory.keys()
635                         keys.sort()
636                         del keys[0]
637                         row = 0
638
639                         #point to the first row
640                         iter = self._unitModel.get_iter_first()
641
642                         while iter:
643                                 #get the formula from the name at the row
644                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
645
646                                 #set the result in the value column
647                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
648
649                                 #point to the next row in the self._unitModel
650                                 iter = self._unitModel.iter_next(iter)
651
652                         # if the second row has a unit then update its value
653                         if self._previousUnitName.get_text() != '':
654                                 self._calcsuppress = True
655                                 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
656                                 self._previousUnitValue.set_text(str(apply(func.from_base, (base, arg, ))))
657                                 self._calcsuppress = False
658
659         def _on_previous_unit_value_changed(self, a):
660                 if self._calcsuppress == True:
661                         #self._calcsuppress = False
662                         return
663                 # determine if value to be calculated is empty
664                 if self._selected_category == "Computer Numbers":
665                         if self._previousUnitValue.get_text() == '':
666                                 value = '0'
667                         else:
668                                 value = self._previousUnitValue.get_text()
669                 else:
670                         if self._previousUnitValue.get_text() == '':
671                                 value = 0.0
672                         else:
673                                 value = float(self._previousUnitValue.get_text())
674
675                 if self._previousUnitName.get_text() != '':
676                         func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0] #retrieve the conversion function and value from the selected unit
677                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
678
679                         keys = self._unitDataInCategory.keys()
680                         keys.sort()
681                         del keys[0]
682                         row = 0
683
684                         #point to the first row
685                         iter = self._unitModel.get_iter_first()
686
687                         while iter:
688                                 #get the formula from the name at the row
689                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
690
691                                 #set the result in the value column
692                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
693
694                                 #point to the next row in the self._unitModel
695                                 iter = self._unitModel.iter_next(iter)
696
697                         # if the second row has a unit then update its value
698                         if self._unitName.get_text() != '':
699                                 self._calcsuppress = True
700                                 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
701                                 self._unitValue.set_text(str(apply(func.from_base, (base, arg, ))))
702                                 self._calcsuppress = False
703
704
705 def main():
706         logging.basicConfig(level = logging.DEBUG)
707         try:
708                 os.makedirs(constants._data_path_)
709         except OSError, e:
710                 if e.errno != 17:
711                         raise
712
713         gonvert = Gonvert()
714         gtk.main()
715
716
717 if __name__ == "__main__":
718         main()