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