679f70b40410cfb826bcd439a177d93894ab0362
[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 evil_globals
18 import unit_data
19
20
21 _moduleLogger = logging.getLogger("gonvert_glade")
22
23 gettext.bindtextdomain('gonvert', '/usr/share/locale')
24 gettext.textdomain('gonvert')
25 _ = gettext.gettext
26
27
28 def change_menu_label(widgets, labelname, newtext):
29         item_label = widgets.get_widget(labelname).get_children()[0]
30         item_label.set_text(newtext)
31
32
33 class Gonvert(object):
34
35         _glade_files = [
36                 os.path.join(os.path.dirname(__file__), "gonvert.glade"),
37                 os.path.join(os.path.dirname(__file__), "../data/gonvert.glade"),
38                 os.path.join(os.path.dirname(__file__), "../lib/gonvert.glade"),
39                 '/usr/lib/gonvert/gonvert.glade',
40         ]
41
42         def __init__(self):
43                 self._unitDataInCategory = None
44
45                 #check to see if glade file is in current directory (user must be
46                 # running from download untar directory)
47                 for gladePath in self._glade_files:
48                         if os.path.isfile(gladePath):
49                                 homepath = os.path.dirname(gladePath)
50                                 pixmapspath = "/".join((homepath, "pixmaps"))
51                                 widgets = gtk.glade.XML(gladePath)
52                                 break
53                 else:
54                         return
55
56                 self._mainWindow = widgets.get_widget('mainWindow')
57
58                 change_menu_label(widgets, 'fileMenuItem', _('File'))
59                 change_menu_label(widgets, 'exitMenuItem', _('Exit'))
60                 change_menu_label(widgets, 'toolsMenuItem', _('Tools'))
61                 change_menu_label(widgets, 'clearSelectionMenuItem', _('Clear selections'))
62                 change_menu_label(widgets, 'writeUnitsMenuItem', _('Write Units'))
63                 change_menu_label(widgets, 'helpMenuItem', _('Help'))
64                 change_menu_label(widgets, 'aboutMenuItem', _('About'))
65                 change_menu_label(widgets, 'findButton', _('Find'))
66
67                 self._shortlistcheck = widgets.get_widget('shortlistcheck')
68                 self._toggleShortList = widgets.get_widget('toggleShortList')
69
70                 self._categoryView = widgets.get_widget('categoryView')
71
72                 self._unitsView = widgets.get_widget('unitsView')
73                 self._unitsView_selection = self._unitsView.get_selection()
74
75                 self._unitName = widgets.get_widget('unitName')
76                 self._unitValue = widgets.get_widget('unitValue')
77                 self._previousUnitName = widgets.get_widget('previousUnitName')
78                 self._previousUnitValue = widgets.get_widget('previousUnitValue')
79                 self._about_box = widgets.get_widget('about_box')
80                 messagebox = widgets.get_widget('msgbox')
81                 messageboxtext = widgets.get_widget('msgboxtext')
82
83                 about_image = widgets.get_widget('about_image')
84                 about_image.set_from_file(pixmapspath +'gonvert.png')
85                 versionlabel = widgets.get_widget('versionlabel')
86                 versionlabel.set_text(constants.__version__)
87
88                 self._unitSymbol = widgets.get_widget('unitSymbol')
89                 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
90
91                 self._unitDescription = widgets.get_widget('unitDescription')
92
93                 self._findEntry = widgets.get_widget('findEntry')
94                 self._findLabel = widgets.get_widget('findLabel')
95                 findButton = widgets.get_widget('findButton')
96
97                 #insert a self._categoryColumnumn into the units list even though the heading will not be seen
98                 renderer = gtk.CellRendererText()
99                 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
100                 self._unitNameColumn.set_property('resizable', 1)
101                 self._unitNameColumn.add_attribute(renderer, 'text', 0)
102                 self._unitNameColumn.set_clickable(True)
103                 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
104                 self._unitsView.append_column(self._unitNameColumn)
105
106                 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
107                 self._unitValueColumn.set_property('resizable', 1)
108                 self._unitValueColumn.add_attribute(renderer, 'text', 1)
109                 self._unitValueColumn.set_clickable(True)
110                 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
111                 self._unitsView.append_column(self._unitValueColumn)
112
113                 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
114                 self._unitSymbolColumn.set_property('resizable', 1)
115                 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
116                 self._unitSymbolColumn.set_clickable(True)
117                 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
118                 self._unitsView.append_column(self._unitSymbolColumn)
119
120                 #Insert a column into the category list even though the heading will not be seen
121                 renderer = gtk.CellRendererText()
122                 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
123                 self._categoryColumn.set_property('resizable', 1)
124                 self._categoryColumn.add_attribute(renderer, 'text', 0)
125                 self._categoryView.append_column(self._categoryColumn)
126
127                 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
128                 self._categoryView.set_model(self._categoryModel)
129                 #colourize each row differently for easier reading
130                 self._categoryView.set_property('rules_hint', 1)
131
132                 #Populate the catagories list
133                 keys = unit_data.list_dic.keys()
134                 keys.sort()
135                 for key in keys:
136                         iter = self._categoryModel.append()
137                         self._categoryModel.set(iter, 0, key)
138
139                 ToolTips = gtk.Tooltips()
140                 ToolTips.set_tip(findButton, _(u'Find unit (F6)'))
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.top,
149                         "on_previousUnitValue_changed": self.bottom,
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._findEntry_changed,
154                         "on_aboutMenuItem_activate": self._on_about_clicked,
155                         "on_about_close_clicked": self._on_about_hide,
156                         "on_messagebox_ok_clicked": self.messagebox_ok_clicked,
157                         "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
158                         "on_unitsView_cursor_changed": self._on_click_unit,
159                         "on_unitsView_button_released": self._on_button_released,
160                         "on_shortlistcheck_toggled": self._on_shortlist_changed,
161                         "on_toggleShortList_activate": self._on_edit_shortlist,
162                 }
163                 widgets.signal_autoconnect(dic)
164
165                 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
166                 iconPath = pixmapspath + '/gonvert.png'
167                 if os.path.exists(iconPath):
168                         self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
169                 else:
170                         _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
171
172                 #Restore window size from previously saved settings if it exists and is valid.
173                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
174                 if os.path.exists(windowDatPath):
175                         #Retrieving previous window settings from ~/.gonvert/window.dat
176                         saved_window = pickle.load(open(windowDatPath, "r"))
177                         #If the 'size' has been stored, then extract size from saved_window.
178                         if 'size' in saved_window:
179                                 a, b = saved_window['size']
180                                 self._mainWindow.resize(a, b)
181                         else:
182                                 #Maximize if no previous size was found
183                                 #self._mainWindow.maximize()
184                                 pass
185                 else:
186                         #Maximize if no previous window.dat file was found
187                         #self._mainWindow.maximize()
188                         pass
189
190                 #Restore selections from previously saved settings if it exists and is valid.
191                 historical_catergory_found = False
192                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
193                 if os.path.exists(selectionsDatPath):
194                         #Retrieving previous selections from ~/.gonvert/selections.dat
195                         selections = pickle.load(open(selectionsDatPath, 'r'))
196                         #Restoring previous selections.
197                         #
198                         #Make a list of categories to determine which one to select
199                         categories = unit_data.list_dic.keys()
200                         categories.sort()
201                         #
202                         #If the 'selected_unts' has been stored, then extract evil_globals.selected_units from selections.
203                         if 'selected_units' in selections:
204                                 evil_globals.selected_units = selections['selected_units']
205                         #Make sure that the 'evil_globals.selected_category' has been stored.
206                         if 'selected_category' in selections:
207                                 #Match an available category to the previously selected category.
208                                 for counter in range(len(categories)):
209                                         if selections['selected_category'] == categories[counter]:
210                                                 # Restore the previously selected category.
211                                                 self._categoryView.set_cursor(counter, self._categoryColumn, False)
212                                                 self._categoryView.grab_focus()
213                                 historical_catergory_found = True
214
215                 if not historical_catergory_found:
216                         print "Couldn't find saved category, using default."
217                         #If historical records were not kept then default to
218                         # put the focus on the first category
219                         self._categoryView.set_cursor(0, self._categoryColumn, False)
220                         self._categoryView.grab_focus()
221
222                 self.restore_units()
223
224         def _on_shortlist_changed(self, a):
225                 print "shortlist"
226                 if self._shortlistcheck.get_active():
227                         print "1"
228                 else:
229                         print "0"
230
231         def _on_edit_shortlist(self, a):
232                 print "edit shortlist"
233                 if self._toggleShortList.get_active():
234                         print "1"
235                 else:
236                         print "0"
237
238         def _on_user_clear_selections(self, a):
239                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
240                 os.remove(selectionsDatPath)
241                 evil_globals.selected_units = {}
242
243         def _on_user_exit(self, a):
244                 """
245                 This routine saves the selections to a file, and
246                 should therefore only be called when exiting the program.
247
248                 Update selections dictionary which consists of the following keys:
249                 'evil_globals.selected_category': full name of selected category
250                 'evil_globals.selected_units': evil_globals.selected_units dictionary which contains:
251                 [categoryname: #1 displayed unit, #2 displayed unit]
252                 """
253                 #Determine the contents of the selected category row
254                 selected, iter = self._categoryView.get_selection().get_selected()
255                 evil_globals.selected_category = self._categoryModel.get_value(iter, 0)
256
257                 selections = {
258                         'selected_category': evil_globals.selected_category,
259                         'selected_units': evil_globals.selected_units
260                 }
261                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
262                 pickle.dump(selections, open(selectionsDatPath, 'w'))
263
264                 #Get last size of app and save it
265                 window_settings = {
266                         'size': self._mainWindow.get_size()
267                 }
268                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
269                 pickle.dump(window_settings, open(windowDatPath, 'w'))
270
271                 gtk.mainquit
272                 sys.exit()
273
274         def _findEntry_changed(self, a):
275                 #Clear out find results since the user wants to look for something new
276                 evil_globals.find_result = [] #empty find result list
277                 evil_globals.find_count = 0 #default to find result number zero
278                 self._findLabel.set_text('') #clear result
279
280         def _on_find_key_press(self, a, b):
281                 #Check if the key pressed was an ASCII key
282                 if len(b.string)>0:
283                         #Check if the key pressed was the 'Enter' key
284                         if ord(b.string[0]) == 13:
285                                 #Execute the find units function
286                                 _on_user_find_units(1)
287
288         def _on_about_clicked(self, a):
289                 self._about_box.show()
290
291         def _on_about_hide(self, *args):
292                 self._about_box.hide()
293                 return gtk.TRUE
294
295         def messagebox_ok_clicked(self, a):
296                 messagebox.hide()
297
298         def _on_user_find_units(self, a):
299                 #check if 'new find' or 'last find' or 'next-find'
300
301                 #new-find = run the find algorithm which also selects the first found unit
302                 #         = evil_globals.find_count = 0 and evil_globals.find_result = []
303
304                 #last-find = restart from top again
305                 #          = evil_globals.find_count = len(evil_globals.find_result)
306
307                 #next-find = continue to next found location
308                 #           = evil_globals.find_count = 0 and len(evil_globals.find_result)>0
309
310                 #check for new-find
311                 if len(evil_globals.find_result) == 0:
312                         find_string = string.lower(string.strip(self._findEntry.get_text()))
313                         #Make sure that a valid find string has been requested
314                         if len(find_string)>0:
315                                 categories = unit_data.list_dic.keys()
316                                 categories.sort()
317                                 found_a_unit = 0 #reset the 'found-a-unit' flag
318                                 cat_no = 0
319                                 for category in categories:
320                                         units = unit_data.list_dic[category].keys()
321                                         units.sort()
322                                         del units[0] # do not display .base_unit description key
323                                         unit_no = 0
324                                         for unit in units:
325                                                 if string.find(string.lower(unit), find_string) >= 0:
326                                                         found_a_unit = 1 #indicate that a unit was found
327                                                         #print "'", find_string, "'", " found at category = ", category, " unit = ", unit
328                                                         evil_globals.find_result.append((category, unit, cat_no, unit_no))
329                                                 unit_no = unit_no+1
330                                         cat_no = cat_no+1
331
332                                 if found_a_unit == 1:
333                                         #select the first found unit
334                                         evil_globals.find_count = 0
335                                         #check if next find is in a new category (prevent category changes when unnecessary
336                                         if evil_globals.selected_category != evil_globals.find_result[evil_globals.find_count][0]:
337                                                 self._categoryView.set_cursor(evil_globals.find_result[0][2], self._categoryColumn, False)
338                                                 self._unitsView.set_cursor(evil_globals.find_result[0][3], self._unitNameColumn, True)
339                                                 if len(evil_globals.find_result)>1:
340                                                         self._findLabel.set_text(('Press Find for next unit. '+ str(len(evil_globals.find_result))+' result(s).'))
341                                                 else:
342                                                         self._findLabel.set_text('Text not found') #Display error
343                 else: #must be next-find or last-find
344                         #check for last-find
345                         if evil_globals.find_count == len(evil_globals.find_result)-1:
346                                 #select first result
347                                 evil_globals.find_count = 0
348                                 self._categoryView.set_cursor(evil_globals.find_result[evil_globals.find_count][2], self._categoryColumn, False)
349                                 self._unitsView.set_cursor(evil_globals.find_result[evil_globals.find_count][3], self._unitNameColumn, True)
350                         else: #must be next-find
351                                 evil_globals.find_count = evil_globals.find_count+1
352                                 #check if next find is in a new category (prevent category changes when unnecessary
353                                 if evil_globals.selected_category != evil_globals.find_result[evil_globals.find_count][0]:
354                                         self._categoryView.set_cursor(evil_globals.find_result[evil_globals.find_count][2], self._categoryColumn, False)
355                                 self._unitsView.set_cursor(evil_globals.find_result[evil_globals.find_count][3], self._unitNameColumn, True)
356
357         def _on_click_unit_column(self, col):
358                 """
359                 Sort the contents of the col when the user clicks on the title.
360                 """
361                 #Determine which column requires sorting
362                 if col is self._unitNameColumn:
363                         selectedUnitColumn = 0
364                         self._unitNameColumn.set_sort_indicator(True)
365                         self._unitValueColumn.set_sort_indicator(False)
366                         self._unitSymbolColumn.set_sort_indicator(False)
367                         self._unitNameColumn.set_sort_order(not evil_globals.unit_sort_direction)
368                 elif col is self._unitValueColumn:
369                         selectedUnitColumn = 1
370                         self._unitNameColumn.set_sort_indicator(False)
371                         self._unitValueColumn.set_sort_indicator(True)
372                         self._unitSymbolColumn.set_sort_indicator(False)
373                         self._unitValueColumn.set_sort_order(not evil_globals.value_sort_direction)
374                 elif col is self._unitSymbolColumn:
375                         selectedUnitColumn = 2
376                         self._unitNameColumn.set_sort_indicator(False)
377                         self._unitValueColumn.set_sort_indicator(False)
378                         self._unitSymbolColumn.set_sort_indicator(True)
379                         self._unitSymbolColumn.set_sort_order(not evil_globals.units_sort_direction)
380                 else:
381                         assert False, "Unknown column: %s" % (col.get_title(), )
382
383                 #declare a spot to hold the sorted list
384                 sorted_list = []
385
386                 #point to the first row
387                 iter = self._unitModel.get_iter_first()
388                 row = 0
389
390                 while iter:
391                         #grab all text from columns for sorting
392
393                         #get the text from each column
394                         unit_text = self._unitModel.get_value(iter, 0)
395                         units_text = self._unitModel.get_value(iter, 2)
396
397                         #do not bother sorting if the value column is empty
398                         if self._unitModel.get_value(iter, 1) == '' and selectedUnitColumn == 1:
399                                 return
400
401                         #special sorting exceptions for ascii values (instead of float values)
402                         if evil_globals.selected_category == "Computer Numbers":
403                                 value_text = self._unitModel.get_value(iter, 1)
404                         else:
405                                 if self._unitModel.get_value(iter, 1) == None or unit_model.get_value(iter, 1) == '':
406                                         value_text = ''
407                                 else:
408                                         value_text = float(self._unitModel.get_value(iter, 1))
409
410                         if selectedUnitColumn == 0:
411                                 sorted_list.append((unit_text, value_text, units_text))
412                         elif selectedUnitColumn == 1:
413                                 sorted_list.append((value_text, unit_text, units_text))
414                         else:
415                                 sorted_list.append((units_text, value_text, unit_text))
416
417                         #point to the next row in the self._unitModel
418                         iter = self._unitModel.iter_next(iter)
419                         row = row+1
420
421                 #check if no calculations have been made yet (don't bother sorting)
422                 if row == 0:
423                         return
424                 else:
425                         if selectedUnitColumn == 0:
426                                 if not evil_globals.unit_sort_direction:
427                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
428                                         evil_globals.unit_sort_direction = True
429                                 else:
430                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(y), string.lower(x)))
431                                         evil_globals.unit_sort_direction = False
432                         elif selectedUnitColumn == 1:
433                                 sorted_list.sort()
434                                 if not evil_globals.value_sort_direction:
435                                         evil_globals.value_sort_direction = True
436                                 else:
437                                         sorted_list.reverse()
438                                         evil_globals.value_sort_direction = False
439                         else:
440                                 if not evil_globals.units_sort_direction:
441                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
442                                         evil_globals.units_sort_direction = True
443                                 else:
444                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(y), string.lower(x)))
445                                         evil_globals.units_sort_direction = False
446
447                         #Clear out the previous list of units
448                         self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
449                         self._unitsView.set_model(self._unitModel)
450
451                         #colourize each row differently for easier reading
452                         self._unitsView.set_property('rules_hint', 1)
453
454                         #Clear out the description
455                         text_model = gtk.TextBuffer(None)
456                         self._unitDescription.set_buffer(text_model)
457
458                         if selectedUnitColumn == 0:
459                                 for unit, value, units in sorted_list:
460                                         iter = self._unitModel.append()
461                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
462                         elif selectedUnitColumn == 1:
463                                 for value, unit, units in sorted_list:
464                                         iter = self._unitModel.append()
465                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
466                         else:
467                                 for units, value, unit in sorted_list:
468                                         iter = self._unitModel.append()
469                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
470                 return
471
472         def _on_click_category(self, row):
473                 #Clear out the previous list of units
474                 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
475                 self._unitsView.set_model(self._unitModel)
476
477                 #Colourize each row alternately for easier reading
478                 self._unitsView.set_property('rules_hint', 1)
479
480                 #Clear out the description
481                 text_model = gtk.TextBuffer(None)
482                 self._unitDescription.set_buffer(text_model)
483
484                 #Determine the contents of the selected category row
485                 selected, iter = row.get_selection().get_selected()
486
487                 evil_globals.selected_category = self._categoryModel.get_value(iter, 0)
488
489                 evil_globals.unit_sort_direction = False
490                 evil_globals.value_sort_direction = False
491                 evil_globals.units_sort_direction = False
492                 self._unitNameColumn.set_sort_indicator(False)
493                 self._unitValueColumn.set_sort_indicator(False)
494                 self._unitSymbolColumn.set_sort_indicator(False)
495
496                 self._unitDataInCategory = unit_data.list_dic[selected.get_value(iter, 0)]
497                 keys = self._unitDataInCategory.keys()
498                 keys.sort()
499                 del keys[0] # do not display .base_unit description key
500
501                 #Fill up the units descriptions and clear the value cells
502                 for key in keys:
503                         iter = self._unitModel.append()
504                         self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
505
506                 self._unitName.set_text('')
507                 self._unitValue.set_text('')
508                 self._previousUnitName.set_text('')
509                 self._previousUnitValue.set_text('')
510                 self._unitSymbol.set_text('')
511                 self._previousUnitSymbol.set_text('')
512
513                 self.restore_units()
514
515         def restore_units(self):
516                 # Restore the previous historical settings of previously selected units in this newly selected category
517                 #Since category has just been clicked, the list will be sorted already.
518                 if evil_globals.selected_category in evil_globals.selected_units:
519                         if evil_globals.selected_units[evil_globals.selected_category][0]:
520                                 ''"debug ''"
521                                 #evil_globals.selected_units[evil_globals.selected_category] = [selected_unit, evil_globals.selected_units[evil_globals.selected_category][0]]
522
523                                 units = unit_data.list_dic[evil_globals.selected_category].keys()
524                                 units.sort()
525                                 del units[0] # do not display .base_unit description key
526
527                                 #Restore oldest selection first.
528                                 if evil_globals.selected_units[evil_globals.selected_category][1]:
529                                         unit_no = 0
530                                         for unit in units:
531                                                 if unit == evil_globals.selected_units[evil_globals.selected_category][1]:
532                                                         self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
533                                                 unit_no = unit_no+1
534
535                                 #Restore newest selection second.
536                                 unit_no = 0
537                                 for unit in units:
538                                         if unit == evil_globals.selected_units[evil_globals.selected_category][0]:
539                                                 self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
540                                         unit_no = unit_no+1
541
542                 # select the text so user can start typing right away
543                 self._unitValue.grab_focus()
544                 self._unitValue.select_region(0, -1)
545
546         def _on_button_released(self, row, a):
547                 self._on_click_unit(row)
548
549         def _on_click_unit(self, row):
550                 evil_globals.calcsuppress = 1 #suppress calculations
551
552                 #Determine the contents of the selected row.
553                 selected, iter = self._unitsView.get_selection().get_selected()
554
555                 selected_unit = selected.get_value(iter, 0)
556
557                 unit_spec = self._unitDataInCategory[selected_unit]
558
559                 #Clear out the description
560                 text_model = gtk.TextBuffer(None)
561                 self._unitDescription.set_buffer(text_model)
562
563                 enditer = text_model.get_end_iter()
564                 text_model.insert(enditer, unit_spec[2])
565
566                 if self._unitName.get_text() != selected_unit:
567                         self._previousUnitName.set_text(self._unitName.get_text())
568                         self._previousUnitValue.set_text(self._unitValue.get_text())
569                         if self._unitSymbol.get() == None:
570                                 self._previousUnitSymbol.set_text('')
571                         else:
572                                 self._previousUnitSymbol.set_text(self._unitSymbol.get())
573                 self._unitName.set_text(selected_unit)
574
575                 self._unitValue.set_text(selected.get_value(iter, 1))
576
577                 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
578                 if self._unitValue.get_text() == '':
579                         if evil_globals.selected_category == "Computer Numbers":
580                                 self._unitValue.set_text("0")
581                         else:
582                                 self._unitValue.set_text("0.0")
583
584                 #For historical purposes, record this unit as the most recent one in this category.
585                 # Also, if a previous unit exists, then shift that previous unit to oldest unit.
586                 if evil_globals.selected_category in evil_globals.selected_units:
587                         if evil_globals.selected_units[evil_globals.selected_category][0]:
588                                 evil_globals.selected_units[evil_globals.selected_category] = [selected_unit, evil_globals.selected_units[evil_globals.selected_category][0]]
589                 else:
590                         evil_globals.selected_units[evil_globals.selected_category] = [selected_unit, '']
591
592                 # select the text so user can start typing right away
593                 self._unitValue.grab_focus()
594                 self._unitValue.select_region(0, -1)
595
596                 evil_globals.calcsuppress = 0 #enable calculations
597
598         def _on_user_write_units(self, a):
599                 ''"Write the list of categories and units to stdout for documentation purposes.''"
600                 messagebox_model = gtk.TextBuffer(None)
601                 messageboxtext.set_buffer(messagebox_model)
602                 messagebox_model.insert_at_cursor(_(u'The units are being written to stdout. You can capture this printout by starting gonvert from the command line as follows: \n$ gonvert > file.txt'), -1)
603                 messagebox.show()
604                 while gtk.events_pending():
605                         gtk.mainiteration(False)
606                 category_keys = unit_data.list_dic.keys()
607                 category_keys.sort()
608                 total_categories = 0
609                 total_units = 0
610                 print 'gonvert-%s%s' % (
611                         constants.__version__,
612                         _(u' - Unit Conversion Utility  - Convertible units listing: ')
613                 )
614                 for category_key in category_keys:
615                         total_categories = total_categories + 1
616                         print category_key, ": "
617                         self._unitDataInCategory = unit_data.list_dic[category_key]
618                         unit_keys = self._unitDataInCategory.keys()
619                         unit_keys.sort()
620                         del unit_keys[0] # do not display .base_unit description key
621                         for unit_key in unit_keys:
622                                 total_units = total_units + 1
623                                 print "\t", unit_key
624                 print total_categories, ' categories'
625                 print total_units, ' units'
626                 messagebox_model = gtk.TextBuffer(None)
627                 messageboxtext.set_buffer(messagebox_model)
628                 messagebox_model.insert_at_cursor(_(u'The units list has been written to stdout. You can capture this printout by starting gonvert from the command line as follows: \n$ gonvert > file.txt'), -1)
629
630         def top(self, a):
631                 if evil_globals.calcsuppress == 1:
632                         #evil_globals.calcsuppress = 0
633                         return
634                 # determine if value to be calculated is empty
635                 if evil_globals.selected_category == "Computer Numbers":
636                         if self._unitValue.get_text() == '':
637                                 value = '0'
638                         else:
639                                 value = self._unitValue.get_text()
640                 else:
641                         if self._unitValue.get_text() == '':
642                                 value = 0.0
643                         else:
644                                 value = float(self._unitValue.get_text())
645
646                 if self._unitName.get_text() != '':
647                         func, arg = self._unitDataInCategory[self._unitName.get_text()][0] #retrieve the conversion function and value from the selected unit
648                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
649
650                         keys = self._unitDataInCategory.keys()
651                         keys.sort()
652                         del keys[0]
653                         row = 0
654
655                         #point to the first row
656                         iter = self._unitModel.get_iter_first()
657
658                         while iter:
659                                 #get the formula from the name at the row
660                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
661
662                                 #set the result in the value column
663                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
664
665                                 #point to the next row in the self._unitModel
666                                 iter = self._unitModel.iter_next(iter)
667
668                         # if the second row has a unit then update its value
669                         if self._previousUnitName.get_text() != '':
670                                 evil_globals.calcsuppress = 1
671                                 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
672                                 self._previousUnitValue.set_text(str(apply(func.from_base, (base, arg, ))))
673                                 evil_globals.calcsuppress = 0
674
675         def bottom(self, a):
676                 if evil_globals.calcsuppress == 1:
677                         #evil_globals.calcsuppress = 0
678                         return
679                 # determine if value to be calculated is empty
680                 if evil_globals.selected_category == "Computer Numbers":
681                         if self._previousUnitValue.get_text() == '':
682                                 value = '0'
683                         else:
684                                 value = self._previousUnitValue.get_text()
685                 else:
686                         if self._previousUnitValue.get_text() == '':
687                                 value = 0.0
688                         else:
689                                 value = float(self._previousUnitValue.get_text())
690
691                 if self._previousUnitName.get_text() != '':
692                         func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0] #retrieve the conversion function and value from the selected unit
693                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
694
695                         keys = self._unitDataInCategory.keys()
696                         keys.sort()
697                         del keys[0]
698                         row = 0
699
700                         #point to the first row
701                         iter = self._unitModel.get_iter_first()
702
703                         while iter:
704                                 #get the formula from the name at the row
705                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
706
707                                 #set the result in the value column
708                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
709
710                                 #point to the next row in the self._unitModel
711                                 iter = self._unitModel.iter_next(iter)
712
713                         # if the second row has a unit then update its value
714                         if self._unitName.get_text() != '':
715                                 evil_globals.calcsuppress = 1
716                                 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
717                                 self._unitValue.set_text(str(apply(func.from_base, (base, arg, ))))
718                                 evil_globals.calcsuppress = 0
719
720
721 def main():
722         logging.basicConfig(level = logging.DEBUG)
723         try:
724                 os.makedirs(constants._data_path_)
725         except OSError, e:
726                 if e.errno != 17:
727                         raise
728
729         gonvert = Gonvert()
730         gtk.main()
731
732
733 if __name__ == "__main__":
734         main()