e1321194644f04c95dafb077f4e38fe5d3fb6290
[gonvert] / src / gonvert_glade.py
1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
3
4 import os
5 import pickle
6 import string
7 import sys
8 import gettext
9 import logging
10
11 import gobject
12 import gtk
13 import gtk.glade
14 import gtk.gdk
15
16 import constants
17 import unit_data
18
19
20 _moduleLogger = logging.getLogger("gonvert_glade")
21
22 gettext.bindtextdomain('gonvert', '/usr/share/locale')
23 gettext.textdomain('gonvert')
24 _ = gettext.gettext
25
26
27 def change_menu_label(widgets, labelname, newtext):
28         item_label = widgets.get_widget(labelname).get_children()[0]
29         item_label.set_text(newtext)
30
31
32 class Gonvert(object):
33
34         _glade_files = [
35                 os.path.join(os.path.dirname(__file__), "gonvert.glade"),
36                 os.path.join(os.path.dirname(__file__), "../data/gonvert.glade"),
37                 os.path.join(os.path.dirname(__file__), "../lib/gonvert.glade"),
38                 '/usr/lib/gonvert/gonvert.glade',
39         ]
40
41         def __init__(self):
42                 self._unitDataInCategory = None
43                 self._calcsuppress = False
44                 self._unit_sort_direction = False
45                 self._value_sort_direction = False
46                 self._units_sort_direction = False
47
48                 self._find_result = [] # empty find result list
49                 self._find_count = 0 # default to find result number zero
50
51                 self._selected_category = '' # preset to no selected category
52                 self._selected_units = {} # empty dictionary for later use
53
54                 #check to see if glade file is in current directory (user must be
55                 # running from download untar directory)
56                 for gladePath in self._glade_files:
57                         if os.path.isfile(gladePath):
58                                 homepath = os.path.dirname(gladePath)
59                                 pixmapspath = "/".join((homepath, "pixmaps"))
60                                 widgets = gtk.glade.XML(gladePath)
61                                 break
62                 else:
63                         return
64
65                 self._mainWindow = widgets.get_widget('mainWindow')
66
67                 change_menu_label(widgets, 'fileMenuItem', _('File'))
68                 change_menu_label(widgets, 'exitMenuItem', _('Exit'))
69                 change_menu_label(widgets, 'toolsMenuItem', _('Tools'))
70                 change_menu_label(widgets, 'clearSelectionMenuItem', _('Clear selections'))
71                 change_menu_label(widgets, 'writeUnitsMenuItem', _('Write Units'))
72                 change_menu_label(widgets, 'helpMenuItem', _('Help'))
73                 change_menu_label(widgets, 'aboutMenuItem', _('About'))
74                 change_menu_label(widgets, 'findButton', _('Find'))
75
76                 self._shortlistcheck = widgets.get_widget('shortlistcheck')
77                 self._toggleShortList = widgets.get_widget('toggleShortList')
78
79                 self._categoryView = widgets.get_widget('categoryView')
80
81                 self._unitsView = widgets.get_widget('unitsView')
82                 self._unitsView_selection = self._unitsView.get_selection()
83
84                 self._unitName = widgets.get_widget('unitName')
85                 self._unitValue = widgets.get_widget('unitValue')
86                 self._previousUnitName = widgets.get_widget('previousUnitName')
87                 self._previousUnitValue = widgets.get_widget('previousUnitValue')
88                 messagebox = widgets.get_widget('msgbox')
89                 messageboxtext = widgets.get_widget('msgboxtext')
90
91                 self._unitSymbol = widgets.get_widget('unitSymbol')
92                 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
93
94                 self._unitDescription = widgets.get_widget('unitDescription')
95
96                 self._findEntry = widgets.get_widget('findEntry')
97                 self._findLabel = widgets.get_widget('findLabel')
98                 findButton = widgets.get_widget('findButton')
99
100                 #insert a self._categoryColumnumn into the units list even though the heading will not be seen
101                 renderer = gtk.CellRendererText()
102                 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
103                 self._unitNameColumn.set_property('resizable', 1)
104                 self._unitNameColumn.add_attribute(renderer, 'text', 0)
105                 self._unitNameColumn.set_clickable(True)
106                 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
107                 self._unitsView.append_column(self._unitNameColumn)
108
109                 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
110                 self._unitValueColumn.set_property('resizable', 1)
111                 self._unitValueColumn.add_attribute(renderer, 'text', 1)
112                 self._unitValueColumn.set_clickable(True)
113                 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
114                 self._unitsView.append_column(self._unitValueColumn)
115
116                 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
117                 self._unitSymbolColumn.set_property('resizable', 1)
118                 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
119                 self._unitSymbolColumn.set_clickable(True)
120                 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
121                 self._unitsView.append_column(self._unitSymbolColumn)
122
123                 #Insert a column into the category list even though the heading will not be seen
124                 renderer = gtk.CellRendererText()
125                 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
126                 self._categoryColumn.set_property('resizable', 1)
127                 self._categoryColumn.add_attribute(renderer, 'text', 0)
128                 self._categoryView.append_column(self._categoryColumn)
129
130                 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
131                 self._categoryView.set_model(self._categoryModel)
132                 #colourize each row differently for easier reading
133                 self._categoryView.set_property('rules_hint', 1)
134
135                 #Populate the catagories list
136                 keys = unit_data.list_dic.keys()
137                 keys.sort()
138                 for key in keys:
139                         iter = self._categoryModel.append()
140                         self._categoryModel.set(iter, 0, key)
141
142                 ToolTips = gtk.Tooltips()
143                 ToolTips.set_tip(findButton, _(u'Find unit (F6)'))
144
145                 #--------- connections to GUI ----------------
146                 dic = {
147                         "on_exit_menu_activate": self._on_user_exit,
148                         "on_main_window_destroy": self._on_user_exit,
149                         "on_categoryView_select_row": self._on_click_category,
150                         "on_unitsView__on_click_unit_column": self._on_click_unit_column,
151                         "on_unitValue_changed": self.top,
152                         "on_previousUnitValue_changed": self.bottom,
153                         "on_writeUnitsMenuItem_activate": self._on_user_write_units,
154                         "on_findButton_clicked": self._on_user_find_units,
155                         "on_findEntry_key_press_event": self._on_find_key_press,
156                         "on_findEntry_changed": self._findEntry_changed,
157                         "on_aboutMenuItem_activate": self._on_about_clicked,
158                         "on_messagebox_ok_clicked": self.messagebox_ok_clicked,
159                         "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
160                         "on_unitsView_cursor_changed": self._on_click_unit,
161                         "on_unitsView_button_released": self._on_button_released,
162                         "on_shortlistcheck_toggled": self._on_shortlist_changed,
163                         "on_toggleShortList_activate": self._on_edit_shortlist,
164                 }
165                 widgets.signal_autoconnect(dic)
166
167                 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
168                 iconPath = pixmapspath + '/gonvert.png'
169                 if os.path.exists(iconPath):
170                         self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
171                 else:
172                         _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
173
174                 #Restore window size from previously saved settings if it exists and is valid.
175                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
176                 if os.path.exists(windowDatPath):
177                         #Retrieving previous window settings from ~/.gonvert/window.dat
178                         saved_window = pickle.load(open(windowDatPath, "r"))
179                         #If the 'size' has been stored, then extract size from saved_window.
180                         if 'size' in saved_window:
181                                 a, b = saved_window['size']
182                                 self._mainWindow.resize(a, b)
183                         else:
184                                 #Maximize if no previous size was found
185                                 #self._mainWindow.maximize()
186                                 pass
187                 else:
188                         #Maximize if no previous window.dat file was found
189                         #self._mainWindow.maximize()
190                         pass
191
192                 #Restore selections from previously saved settings if it exists and is valid.
193                 historical_catergory_found = False
194                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
195                 if os.path.exists(selectionsDatPath):
196                         #Retrieving previous selections from ~/.gonvert/selections.dat
197                         selections = pickle.load(open(selectionsDatPath, 'r'))
198                         #Restoring previous selections.
199                         #
200                         #Make a list of categories to determine which one to select
201                         categories = unit_data.list_dic.keys()
202                         categories.sort()
203                         #
204                         #If the 'selected_unts' has been stored, then extract self._selected_units from selections.
205                         if 'selected_units' in selections:
206                                 self._selected_units = selections['selected_units']
207                         #Make sure that the 'self._selected_category' has been stored.
208                         if 'selected_category' in selections:
209                                 #Match an available category to the previously selected category.
210                                 for counter in range(len(categories)):
211                                         if selections['selected_category'] == categories[counter]:
212                                                 # Restore the previously selected category.
213                                                 self._categoryView.set_cursor(counter, self._categoryColumn, False)
214                                                 self._categoryView.grab_focus()
215                                 historical_catergory_found = True
216
217                 if not historical_catergory_found:
218                         print "Couldn't find saved category, using default."
219                         #If historical records were not kept then default to
220                         # put the focus on the first category
221                         self._categoryView.set_cursor(0, self._categoryColumn, False)
222                         self._categoryView.grab_focus()
223
224                 self.restore_units()
225
226         def _on_shortlist_changed(self, a):
227                 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
228
229         def _on_edit_shortlist(self, a):
230                 raise NotImplementedError("%s" % self._toggleShortList.get_active())
231
232         def _on_user_clear_selections(self, a):
233                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
234                 os.remove(selectionsDatPath)
235                 self._selected_units = {}
236
237         def _on_user_exit(self, a):
238                 """
239                 This routine saves the selections to a file, and
240                 should therefore only be called when exiting the program.
241
242                 Update selections dictionary which consists of the following keys:
243                 'self._selected_category': full name of selected category
244                 'self._selected_units': self._selected_units dictionary which contains:
245                 [categoryname: #1 displayed unit, #2 displayed unit]
246                 """
247                 #Determine the contents of the selected category row
248                 selected, iter = self._categoryView.get_selection().get_selected()
249                 self._selected_category = self._categoryModel.get_value(iter, 0)
250
251                 selections = {
252                         'selected_category': self._selected_category,
253                         'selected_units': self._selected_units
254                 }
255                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
256                 pickle.dump(selections, open(selectionsDatPath, 'w'))
257
258                 #Get last size of app and save it
259                 window_settings = {
260                         'size': self._mainWindow.get_size()
261                 }
262                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
263                 pickle.dump(window_settings, open(windowDatPath, 'w'))
264
265                 gtk.mainquit
266                 sys.exit()
267
268         def _findEntry_changed(self, a):
269                 #Clear out find results since the user wants to look for something new
270                 self._find_result = [] #empty find result list
271                 self._find_count = 0 #default to find result number zero
272                 self._findLabel.set_text('') #clear result
273
274         def _on_find_key_press(self, a, b):
275                 #Check if the key pressed was an ASCII key
276                 if len(b.string)>0:
277                         #Check if the key pressed was the 'Enter' key
278                         if ord(b.string[0]) == 13:
279                                 #Execute the find units function
280                                 self._on_user_find_units(1)
281
282         def _on_about_clicked(self, a):
283                 dlg = gtk.AboutDialog()
284                 dlg.set_name(constants.__pretty_app_name__)
285                 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
286                 dlg.set_copyright("Copyright 2009 - GPL")
287                 dlg.set_comments("")
288                 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
289                 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
290                 dlg.run()
291                 dlg.destroy()
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                 #         = self._find_count = 0 and self._find_result = []
301
302                 #last-find = restart from top again
303                 #          = self._find_count = len(self._find_result)
304
305                 #next-find = continue to next found location
306                 #           = self._find_count = 0 and len(self._find_result)>0
307
308                 #check for new-find
309                 if len(self._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                                                         self._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                                         self._find_count = 0
333                                         #check if next find is in a new category (prevent category changes when unnecessary
334                                         if self._selected_category != self._find_result[self._find_count][0]:
335                                                 self._categoryView.set_cursor(self._find_result[0][2], self._categoryColumn, False)
336                                                 self._unitsView.set_cursor(self._find_result[0][3], self._unitNameColumn, True)
337                                                 if len(self._find_result)>1:
338                                                         self._findLabel.set_text(('Press Find for next unit. '+ str(len(self._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 self._find_count == len(self._find_result)-1:
344                                 #select first result
345                                 self._find_count = 0
346                                 self._categoryView.set_cursor(self._find_result[self._find_count][2], self._categoryColumn, False)
347                                 self._unitsView.set_cursor(self._find_result[self._find_count][3], self._unitNameColumn, True)
348                         else: #must be next-find
349                                 self._find_count = self._find_count+1
350                                 #check if next find is in a new category (prevent category changes when unnecessary
351                                 if self._selected_category != self._find_result[self._find_count][0]:
352                                         self._categoryView.set_cursor(self._find_result[self._find_count][2], self._categoryColumn, False)
353                                 self._unitsView.set_cursor(self._find_result[self._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 self._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 self._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 self._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 self._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 self._unit_sort_direction:
425                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
426                                         self._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                                         self._unit_sort_direction = False
430                         elif selectedUnitColumn == 1:
431                                 sorted_list.sort()
432                                 if not self._value_sort_direction:
433                                         self._value_sort_direction = True
434                                 else:
435                                         sorted_list.reverse()
436                                         self._value_sort_direction = False
437                         else:
438                                 if not self._units_sort_direction:
439                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
440                                         self._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                                         self._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                 #Clear out the previous list of units
472                 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
473                 self._unitsView.set_model(self._unitModel)
474
475                 #Colourize each row alternately for easier reading
476                 self._unitsView.set_property('rules_hint', 1)
477
478                 #Clear out the description
479                 text_model = gtk.TextBuffer(None)
480                 self._unitDescription.set_buffer(text_model)
481
482                 #Determine the contents of the selected category row
483                 selected, iter = row.get_selection().get_selected()
484
485                 self._selected_category = self._categoryModel.get_value(iter, 0)
486
487                 self._unit_sort_direction = False
488                 self._value_sort_direction = False
489                 self._units_sort_direction = False
490                 self._unitNameColumn.set_sort_indicator(False)
491                 self._unitValueColumn.set_sort_indicator(False)
492                 self._unitSymbolColumn.set_sort_indicator(False)
493
494                 self._unitDataInCategory = unit_data.list_dic[selected.get_value(iter, 0)]
495                 keys = self._unitDataInCategory.keys()
496                 keys.sort()
497                 del keys[0] # do not display .base_unit description key
498
499                 #Fill up the units descriptions and clear the value cells
500                 for key in keys:
501                         iter = self._unitModel.append()
502                         self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
503
504                 self._unitName.set_text('')
505                 self._unitValue.set_text('')
506                 self._previousUnitName.set_text('')
507                 self._previousUnitValue.set_text('')
508                 self._unitSymbol.set_text('')
509                 self._previousUnitSymbol.set_text('')
510
511                 self.restore_units()
512
513         def restore_units(self):
514                 # Restore the previous historical settings of previously selected units in this newly selected category
515                 #Since category has just been clicked, the list will be sorted already.
516                 if self._selected_category in self._selected_units:
517                         if self._selected_units[self._selected_category][0]:
518                                 ''"debug ''"
519                                 #self._selected_units[self._selected_category] = [selected_unit, self._selected_units[self._selected_category][0]]
520
521                                 units = unit_data.list_dic[self._selected_category].keys()
522                                 units.sort()
523                                 del units[0] # do not display .base_unit description key
524
525                                 #Restore oldest selection first.
526                                 if self._selected_units[self._selected_category][1]:
527                                         unit_no = 0
528                                         for unit in units:
529                                                 if unit == self._selected_units[self._selected_category][1]:
530                                                         self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
531                                                 unit_no = unit_no+1
532
533                                 #Restore newest selection second.
534                                 unit_no = 0
535                                 for unit in units:
536                                         if unit == self._selected_units[self._selected_category][0]:
537                                                 self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
538                                         unit_no = unit_no+1
539
540                 # select the text so user can start typing right away
541                 self._unitValue.grab_focus()
542                 self._unitValue.select_region(0, -1)
543
544         def _on_button_released(self, row, a):
545                 self._on_click_unit(row)
546
547         def _on_click_unit(self, row):
548                 self._calcsuppress = True #suppress calculations
549
550                 #Determine the contents of the selected row.
551                 selected, iter = self._unitsView.get_selection().get_selected()
552
553                 selected_unit = selected.get_value(iter, 0)
554
555                 unit_spec = self._unitDataInCategory[selected_unit]
556
557                 #Clear out the description
558                 text_model = gtk.TextBuffer(None)
559                 self._unitDescription.set_buffer(text_model)
560
561                 enditer = text_model.get_end_iter()
562                 text_model.insert(enditer, unit_spec[2])
563
564                 if self._unitName.get_text() != selected_unit:
565                         self._previousUnitName.set_text(self._unitName.get_text())
566                         self._previousUnitValue.set_text(self._unitValue.get_text())
567                         if self._unitSymbol.get() == None:
568                                 self._previousUnitSymbol.set_text('')
569                         else:
570                                 self._previousUnitSymbol.set_text(self._unitSymbol.get())
571                 self._unitName.set_text(selected_unit)
572
573                 self._unitValue.set_text(selected.get_value(iter, 1))
574
575                 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
576                 if self._unitValue.get_text() == '':
577                         if self._selected_category == "Computer Numbers":
578                                 self._unitValue.set_text("0")
579                         else:
580                                 self._unitValue.set_text("0.0")
581
582                 #For historical purposes, record this unit as the most recent one in this category.
583                 # Also, if a previous unit exists, then shift that previous unit to oldest unit.
584                 if self._selected_category in self._selected_units:
585                         if self._selected_units[self._selected_category][0]:
586                                 self._selected_units[self._selected_category] = [selected_unit, self._selected_units[self._selected_category][0]]
587                 else:
588                         self._selected_units[self._selected_category] = [selected_unit, '']
589
590                 # select the text so user can start typing right away
591                 self._unitValue.grab_focus()
592                 self._unitValue.select_region(0, -1)
593
594                 self._calcsuppress = False #enable calculations
595
596         def _on_user_write_units(self, a):
597                 ''"Write the list of categories and units to stdout for documentation purposes.''"
598                 messagebox_model = gtk.TextBuffer(None)
599                 messageboxtext.set_buffer(messagebox_model)
600                 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)
601                 messagebox.show()
602                 while gtk.events_pending():
603                         gtk.mainiteration(False)
604                 category_keys = unit_data.list_dic.keys()
605                 category_keys.sort()
606                 total_categories = 0
607                 total_units = 0
608                 print 'gonvert-%s%s' % (
609                         constants.__version__,
610                         _(u' - Unit Conversion Utility  - Convertible units listing: ')
611                 )
612                 for category_key in category_keys:
613                         total_categories = total_categories + 1
614                         print category_key, ": "
615                         self._unitDataInCategory = unit_data.list_dic[category_key]
616                         unit_keys = self._unitDataInCategory.keys()
617                         unit_keys.sort()
618                         del unit_keys[0] # do not display .base_unit description key
619                         for unit_key in unit_keys:
620                                 total_units = total_units + 1
621                                 print "\t", unit_key
622                 print total_categories, ' categories'
623                 print total_units, ' units'
624                 messagebox_model = gtk.TextBuffer(None)
625                 messageboxtext.set_buffer(messagebox_model)
626                 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)
627
628         def top(self, a):
629                 if self._calcsuppress:
630                         #self._calcsuppress = False
631                         return
632                 # determine if value to be calculated is empty
633                 if self._selected_category == "Computer Numbers":
634                         if self._unitValue.get_text() == '':
635                                 value = '0'
636                         else:
637                                 value = self._unitValue.get_text()
638                 else:
639                         if self._unitValue.get_text() == '':
640                                 value = 0.0
641                         else:
642                                 value = float(self._unitValue.get_text())
643
644                 if self._unitName.get_text() != '':
645                         func, arg = self._unitDataInCategory[self._unitName.get_text()][0] #retrieve the conversion function and value from the selected unit
646                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
647
648                         keys = self._unitDataInCategory.keys()
649                         keys.sort()
650                         del keys[0]
651                         row = 0
652
653                         #point to the first row
654                         iter = self._unitModel.get_iter_first()
655
656                         while iter:
657                                 #get the formula from the name at the row
658                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
659
660                                 #set the result in the value column
661                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
662
663                                 #point to the next row in the self._unitModel
664                                 iter = self._unitModel.iter_next(iter)
665
666                         # if the second row has a unit then update its value
667                         if self._previousUnitName.get_text() != '':
668                                 self._calcsuppress = True
669                                 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
670                                 self._previousUnitValue.set_text(str(apply(func.from_base, (base, arg, ))))
671                                 self._calcsuppress = False
672
673         def bottom(self, a):
674                 if self._calcsuppress == True:
675                         #self._calcsuppress = False
676                         return
677                 # determine if value to be calculated is empty
678                 if self._selected_category == "Computer Numbers":
679                         if self._previousUnitValue.get_text() == '':
680                                 value = '0'
681                         else:
682                                 value = self._previousUnitValue.get_text()
683                 else:
684                         if self._previousUnitValue.get_text() == '':
685                                 value = 0.0
686                         else:
687                                 value = float(self._previousUnitValue.get_text())
688
689                 if self._previousUnitName.get_text() != '':
690                         func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0] #retrieve the conversion function and value from the selected unit
691                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
692
693                         keys = self._unitDataInCategory.keys()
694                         keys.sort()
695                         del keys[0]
696                         row = 0
697
698                         #point to the first row
699                         iter = self._unitModel.get_iter_first()
700
701                         while iter:
702                                 #get the formula from the name at the row
703                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
704
705                                 #set the result in the value column
706                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
707
708                                 #point to the next row in the self._unitModel
709                                 iter = self._unitModel.iter_next(iter)
710
711                         # if the second row has a unit then update its value
712                         if self._unitName.get_text() != '':
713                                 self._calcsuppress = True
714                                 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
715                                 self._unitValue.set_text(str(apply(func.from_base, (base, arg, ))))
716                                 self._calcsuppress = False
717
718
719 def main():
720         logging.basicConfig(level = logging.DEBUG)
721         try:
722                 os.makedirs(constants._data_path_)
723         except OSError, e:
724                 if e.errno != 17:
725                         raise
726
727         gonvert = Gonvert()
728         gtk.main()
729
730
731 if __name__ == "__main__":
732         main()