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