2d13136324c41a6b369ca0f24282f6e6af4d1eda
[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                 for key in unit_data.UNIT_CATEGORIES:
139                         iter = self._categoryModel.append()
140                         self._categoryModel.set(iter, 0, key)
141
142                 #--------- connections to GUI ----------------
143                 dic = {
144                         "on_exit_menu_activate": self._on_user_exit,
145                         "on_main_window_destroy": self._on_user_exit,
146                         "on_categoryView_select_row": self._on_click_category,
147                         "on_unitsView__on_click_unit_column": self._on_click_unit_column,
148                         "on_unitValue_changed": self._on_unit_value_changed,
149                         "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
150                         "on_writeUnitsMenuItem_activate": self._on_user_write_units,
151                         "on_findButton_clicked": self._on_find_activate,
152                         "on_findEntry_activated": self._on_find_activate,
153                         "on_findEntry_changed": self._on_findEntry_changed,
154                         "on_aboutMenuItem_activate": self._on_about_clicked,
155                         "on_messagebox_ok_clicked": self.messagebox_ok_clicked,
156                         "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
157                         "on_unitsView_cursor_changed": self._on_click_unit,
158                         "on_unitsView_button_released": self._on_button_released,
159                         "on_shortlistcheck_toggled": self._on_shortlist_changed,
160                         "on_toggleShortList_activate": self._on_edit_shortlist,
161                 }
162                 widgets.signal_autoconnect(dic)
163
164                 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
165                 iconPath = pixmapspath + '/gonvert.png'
166                 if os.path.exists(iconPath):
167                         self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
168                 else:
169                         _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
170
171                 self._load_settings()
172
173         def _load_settings(self):
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                         #If the 'selected_unts' has been stored, then extract self._selected_units from selections.
200                         if 'selected_units' in selections:
201                                 self._selected_units = selections['selected_units']
202                         #Make sure that the 'self._selected_category' has been stored.
203                         if 'selected_category' in selections:
204                                 #Match an available category to the previously selected category.
205                                 for counter in range(len(unit_data.UNIT_CATEGORIES)):
206                                         if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
207                                                 # Restore the previously selected category.
208                                                 self._categoryView.set_cursor(counter, self._categoryColumn, False)
209                                                 self._categoryView.grab_focus()
210                                 historical_catergory_found = True
211
212                 if not historical_catergory_found:
213                         print "Couldn't find saved category, using default."
214                         #If historical records were not kept then default to
215                         # put the focus on the first category
216                         self._categoryView.set_cursor(0, self._categoryColumn, False)
217                         self._categoryView.grab_focus()
218
219                 self.restore_units()
220
221         def _save_settings(self):
222                 """
223                 This routine saves the selections to a file, and
224                 should therefore only be called when exiting the program.
225
226                 Update selections dictionary which consists of the following keys:
227                 'self._selected_category': full name of selected category
228                 'self._selected_units': self._selected_units dictionary which contains:
229                 [categoryname: #1 displayed unit, #2 displayed unit]
230                 """
231                 #Determine the contents of the selected category row
232                 selected, iter = self._categoryView.get_selection().get_selected()
233                 self._selected_category = self._categoryModel.get_value(iter, 0)
234
235                 selections = {
236                         'selected_category': self._selected_category,
237                         'selected_units': self._selected_units
238                 }
239                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
240                 pickle.dump(selections, open(selectionsDatPath, 'w'))
241
242                 #Get last size of app and save it
243                 window_settings = {
244                         'size': self._mainWindow.get_size()
245                 }
246                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
247                 pickle.dump(window_settings, open(windowDatPath, 'w'))
248
249         def _clear_find(self):
250                 # switch to "new find" state
251                 self._find_result = []
252                 self._find_count = 0
253
254                 # Clear our user message
255                 self._findLabel.set_text('')
256
257         def _find_first(self):
258                 assert len(self._find_result) == 0
259                 assert self._find_count == 0
260                 findString = string.lower(string.strip(self._findEntry.get_text()))
261                 if not findString:
262                         return
263
264                 # Gather info on all the matching units from all categories
265                 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
266                         units = unit_data.get_units(category)
267                         for unitIndex, unit in enumerate(units):
268                                 loweredUnit = unit.lower()
269                                 if loweredUnit in findString or findString in loweredUnit:
270                                         self._find_result.append((category, unit, catIndex, unitIndex))
271
272                 if not self._find_result:
273                         return
274
275                 self._select_found_unit()
276
277         def _find_wrap_around(self):
278                 assert 0 < len(self._find_result)
279                 assert self._find_count + 1 == len(self._find_result)
280                 #select first result
281                 self._find_count = 0
282                 self._select_found_unit()
283
284         def _find_next(self):
285                 assert 0 < len(self._find_result)
286                 assert self._find_count + 1 < len(self._find_result)
287                 self._find_count += 1
288                 self._select_found_unit()
289
290         def _select_found_unit(self):
291                 assert 0 < len(self._find_result)
292
293                 #check if next find is in a new category (prevent category changes when unnecessary
294                 if self._selected_category != self._find_result[self._find_count][0]:
295                         self._categoryView.set_cursor(
296                                 self._find_result[self._find_count][2], self._categoryColumn, False
297                         )
298
299                 self._unitsView.set_cursor(
300                         self._find_result[self._find_count][3], self._unitNameColumn, True
301                 )
302
303         def _on_findEntry_changed(self, *args):
304                 """
305                 Clear out find results since the user wants to look for something new
306                 """
307                 try:
308                         self._clear_find()
309                 except Exception:
310                         _moduleLogger.exception()
311
312         def _on_shortlist_changed(self, *args):
313                 try:
314                         raise NotImplementedError("%s" % self._shortlistcheck.get_active())
315                 except Exception:
316                         _moduleLogger.exception()
317
318         def _on_edit_shortlist(self, *args):
319                 try:
320                         raise NotImplementedError("%s" % self._toggleShortList.get_active())
321                 except Exception:
322                         _moduleLogger.exception()
323
324         def _on_user_clear_selections(self, *args):
325                 try:
326                         selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
327                         os.remove(selectionsDatPath)
328                         self._selected_units = {}
329                 except Exception:
330                         _moduleLogger.exception()
331
332         def _on_find_activate(self, a):
333                 """
334                 check if 'new find' or 'last find' or 'next-find'
335
336                 new-find = run the find algorithm which also selects the first found unit
337                          = self._find_count = 0 and self._find_result = []
338
339                 last-find = restart from top again
340                           = self._find_count = len(self._find_result)
341
342                 next-find = continue to next found location
343                            = self._find_count = 0 and len(self._find_result)>0
344                 """
345                 try:
346                         if len(self._find_result) == 0:
347                                 self._find_first()
348                         else:
349                                 if self._find_count == len(self._find_result)-1:
350                                         self._find_wrap_around()
351                                 else:
352                                         self._find_next()
353
354                         if not self._find_result:
355                                 self._findLabel.set_text('Text not found')
356                         else:
357                                 resultsLeft = len(self._find_result) - self._find_count - 1
358                                 self._findLabel.set_text(
359                                         '%s result(s) left' % (resultsLeft, )
360                                 )
361                 except Exception:
362                         _moduleLogger.exception()
363
364         def _on_click_unit_column(self, col):
365                 """
366                 Sort the contents of the col when the user clicks on the title.
367                 """
368                 #Determine which column requires sorting
369                 if col is self._unitNameColumn:
370                         selectedUnitColumn = 0
371                         self._unitNameColumn.set_sort_indicator(True)
372                         self._unitValueColumn.set_sort_indicator(False)
373                         self._unitSymbolColumn.set_sort_indicator(False)
374                         self._unitNameColumn.set_sort_order(not self._unit_sort_direction)
375                 elif col is self._unitValueColumn:
376                         selectedUnitColumn = 1
377                         self._unitNameColumn.set_sort_indicator(False)
378                         self._unitValueColumn.set_sort_indicator(True)
379                         self._unitSymbolColumn.set_sort_indicator(False)
380                         self._unitValueColumn.set_sort_order(not self._value_sort_direction)
381                 elif col is self._unitSymbolColumn:
382                         selectedUnitColumn = 2
383                         self._unitNameColumn.set_sort_indicator(False)
384                         self._unitValueColumn.set_sort_indicator(False)
385                         self._unitSymbolColumn.set_sort_indicator(True)
386                         self._unitSymbolColumn.set_sort_order(not self._units_sort_direction)
387                 else:
388                         assert False, "Unknown column: %s" % (col.get_title(), )
389
390                 #declare a spot to hold the sorted list
391                 sorted_list = []
392
393                 #point to the first row
394                 iter = self._unitModel.get_iter_first()
395                 row = 0
396
397                 while iter:
398                         #grab all text from columns for sorting
399
400                         #get the text from each column
401                         unit_text = self._unitModel.get_value(iter, 0)
402                         units_text = self._unitModel.get_value(iter, 2)
403
404                         #do not bother sorting if the value column is empty
405                         if self._unitModel.get_value(iter, 1) == '' and selectedUnitColumn == 1:
406                                 return
407
408                         #special sorting exceptions for ascii values (instead of float values)
409                         if self._selected_category == "Computer Numbers":
410                                 value_text = self._unitModel.get_value(iter, 1)
411                         else:
412                                 if self._unitModel.get_value(iter, 1) == None or self._unitModel.get_value(iter, 1) == '':
413                                         value_text = ''
414                                 else:
415                                         value_text = float(self._unitModel.get_value(iter, 1))
416
417                         if selectedUnitColumn == 0:
418                                 sorted_list.append((unit_text, value_text, units_text))
419                         elif selectedUnitColumn == 1:
420                                 sorted_list.append((value_text, unit_text, units_text))
421                         else:
422                                 sorted_list.append((units_text, value_text, unit_text))
423
424                         #point to the next row in the self._unitModel
425                         iter = self._unitModel.iter_next(iter)
426                         row = row+1
427
428                 #check if no calculations have been made yet (don't bother sorting)
429                 if row == 0:
430                         return
431                 else:
432                         if selectedUnitColumn == 0:
433                                 if not self._unit_sort_direction:
434                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
435                                         self._unit_sort_direction = True
436                                 else:
437                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(y), string.lower(x)))
438                                         self._unit_sort_direction = False
439                         elif selectedUnitColumn == 1:
440                                 sorted_list.sort()
441                                 if not self._value_sort_direction:
442                                         self._value_sort_direction = True
443                                 else:
444                                         sorted_list.reverse()
445                                         self._value_sort_direction = False
446                         else:
447                                 if not self._units_sort_direction:
448                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
449                                         self._units_sort_direction = True
450                                 else:
451                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(y), string.lower(x)))
452                                         self._units_sort_direction = False
453
454                         #Clear out the previous list of units
455                         self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
456                         self._unitsView.set_model(self._unitModel)
457
458                         #colourize each row differently for easier reading
459                         self._unitsView.set_property('rules_hint', 1)
460
461                         #Clear out the description
462                         text_model = gtk.TextBuffer(None)
463                         self._unitDescription.set_buffer(text_model)
464
465                         if selectedUnitColumn == 0:
466                                 for unit, value, units in sorted_list:
467                                         iter = self._unitModel.append()
468                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
469                         elif selectedUnitColumn == 1:
470                                 for value, unit, units in sorted_list:
471                                         iter = self._unitModel.append()
472                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
473                         else:
474                                 for units, value, unit in sorted_list:
475                                         iter = self._unitModel.append()
476                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
477                 return
478
479         def _on_click_category(self, row):
480                 #Clear out the previous list of units
481                 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
482                 self._unitsView.set_model(self._unitModel)
483
484                 #Colourize each row alternately for easier reading
485                 self._unitsView.set_property('rules_hint', 1)
486
487                 #Clear out the description
488                 text_model = gtk.TextBuffer(None)
489                 self._unitDescription.set_buffer(text_model)
490
491                 #Determine the contents of the selected category row
492                 selected, iter = row.get_selection().get_selected()
493
494                 self._selected_category = self._categoryModel.get_value(iter, 0)
495
496                 self._unit_sort_direction = False
497                 self._value_sort_direction = False
498                 self._units_sort_direction = False
499                 self._unitNameColumn.set_sort_indicator(False)
500                 self._unitValueColumn.set_sort_indicator(False)
501                 self._unitSymbolColumn.set_sort_indicator(False)
502
503                 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[selected.get_value(iter, 0)]
504                 keys = self._unitDataInCategory.keys()
505                 keys.sort()
506                 del keys[0] # do not display .base_unit description key
507
508                 #Fill up the units descriptions and clear the value cells
509                 for key in keys:
510                         iter = self._unitModel.append()
511                         self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
512
513                 self._unitName.set_text('')
514                 self._unitValue.set_text('')
515                 self._previousUnitName.set_text('')
516                 self._previousUnitValue.set_text('')
517                 self._unitSymbol.set_text('')
518                 self._previousUnitSymbol.set_text('')
519
520                 self.restore_units()
521
522         def restore_units(self):
523                 # Restore the previous historical settings of previously selected units in this newly selected category
524                 #Since category has just been clicked, the list will be sorted already.
525                 if self._selected_category in self._selected_units:
526                         if self._selected_units[self._selected_category][0]:
527                                 #self._selected_units[self._selected_category] = [selected_unit, self._selected_units[self._selected_category][0]]
528
529                                 units = unit_data.UNIT_DESCRIPTIONS[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 messagebox_ok_clicked(self, a):
605                 messagebox.hide()
606
607         def _on_user_write_units(self, a):
608                 ''"Write the list of categories and units to stdout for documentation purposes.''"
609                 messagebox_model = gtk.TextBuffer(None)
610                 messageboxtext.set_buffer(messagebox_model)
611                 messagebox_model.insert_at_cursor(_(u'The units are being written to stdout. You can capture this printout by starting gonvert from the command line as follows: \n$ gonvert > file.txt'), -1)
612                 messagebox.show()
613                 while gtk.events_pending():
614                         gtk.mainiteration(False)
615
616                 total_categories = 0
617                 total_units = 0
618                 print 'gonvert-%s%s' % (
619                         constants.__version__,
620                         _(u' - Unit Conversion Utility  - Convertible units listing: ')
621                 )
622                 for category_key in unit_data.UNIT_CATEGORIES:
623                         total_categories = total_categories + 1
624                         print category_key, ": "
625                         self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[category_key]
626                         unit_keys = self._unitDataInCategory.keys()
627                         unit_keys.sort()
628                         del unit_keys[0] # do not display .base_unit description key
629                         for unit_key in unit_keys:
630                                 total_units = total_units + 1
631                                 print "\t", unit_key
632                 print total_categories, ' categories'
633                 print total_units, ' units'
634
635         def _on_unit_value_changed(self, a):
636                 if self._calcsuppress:
637                         #self._calcsuppress = False
638                         return
639                 # determine if value to be calculated is empty
640                 if self._selected_category == "Computer Numbers":
641                         if self._unitValue.get_text() == '':
642                                 value = '0'
643                         else:
644                                 value = self._unitValue.get_text()
645                 else:
646                         if self._unitValue.get_text() == '':
647                                 value = 0.0
648                         else:
649                                 value = float(self._unitValue.get_text())
650
651                 if self._unitName.get_text() != '':
652                         func, arg = self._unitDataInCategory[self._unitName.get_text()][0] #retrieve the conversion function and value from the selected unit
653                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
654
655                         keys = self._unitDataInCategory.keys()
656                         keys.sort()
657                         del keys[0]
658                         row = 0
659
660                         #point to the first row
661                         iter = self._unitModel.get_iter_first()
662
663                         while iter:
664                                 #get the formula from the name at the row
665                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
666
667                                 #set the result in the value column
668                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
669
670                                 #point to the next row in the self._unitModel
671                                 iter = self._unitModel.iter_next(iter)
672
673                         # if the second row has a unit then update its value
674                         if self._previousUnitName.get_text() != '':
675                                 self._calcsuppress = True
676                                 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
677                                 self._previousUnitValue.set_text(str(apply(func.from_base, (base, arg, ))))
678                                 self._calcsuppress = False
679
680         def _on_previous_unit_value_changed(self, a):
681                 if self._calcsuppress == True:
682                         #self._calcsuppress = False
683                         return
684                 # determine if value to be calculated is empty
685                 if self._selected_category == "Computer Numbers":
686                         if self._previousUnitValue.get_text() == '':
687                                 value = '0'
688                         else:
689                                 value = self._previousUnitValue.get_text()
690                 else:
691                         if self._previousUnitValue.get_text() == '':
692                                 value = 0.0
693                         else:
694                                 value = float(self._previousUnitValue.get_text())
695
696                 if self._previousUnitName.get_text() != '':
697                         func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0] #retrieve the conversion function and value from the selected unit
698                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
699
700                         keys = self._unitDataInCategory.keys()
701                         keys.sort()
702                         del keys[0]
703                         row = 0
704
705                         #point to the first row
706                         iter = self._unitModel.get_iter_first()
707
708                         while iter:
709                                 #get the formula from the name at the row
710                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
711
712                                 #set the result in the value column
713                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
714
715                                 #point to the next row in the self._unitModel
716                                 iter = self._unitModel.iter_next(iter)
717
718                         # if the second row has a unit then update its value
719                         if self._unitName.get_text() != '':
720                                 self._calcsuppress = True
721                                 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
722                                 self._unitValue.set_text(str(apply(func.from_base, (base, arg, ))))
723                                 self._calcsuppress = False
724
725         def _on_about_clicked(self, a):
726                 dlg = gtk.AboutDialog()
727                 dlg.set_name(constants.__pretty_app_name__)
728                 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
729                 dlg.set_copyright("Copyright 2009 - GPL")
730                 dlg.set_comments("")
731                 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
732                 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
733                 dlg.run()
734                 dlg.destroy()
735
736         def _on_user_exit(self, *args):
737                 try:
738                         self._save_settings()
739                 except Exception:
740                         _moduleLogger.exception()
741                 finally:
742                         gtk.main_quit()
743
744
745 def main():
746         logging.basicConfig(level = logging.DEBUG)
747         try:
748                 os.makedirs(constants._data_path_)
749         except OSError, e:
750                 if e.errno != 17:
751                         raise
752
753         gonvert = Gonvert()
754         gtk.main()
755
756
757 if __name__ == "__main__":
758         main()