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