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