bbf9d9e97e0e0bae0044a8c1ac05055563559a24
[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_unitValue_changed": self._on_unit_value_changed,
148                         "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
149                         "on_writeUnitsMenuItem_activate": self._on_user_write_units,
150                         "on_findButton_clicked": self._on_find_activate,
151                         "on_findEntry_activated": self._on_find_activate,
152                         "on_findEntry_changed": self._on_findEntry_changed,
153                         "on_aboutMenuItem_activate": self._on_about_clicked,
154                         "on_messagebox_ok_clicked": self.messagebox_ok_clicked,
155                         "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
156                         "on_unitsView_cursor_changed": self._on_click_unit,
157                         "on_shortlistcheck_toggled": self._on_shortlist_changed,
158                         "on_toggleShortList_activate": self._on_edit_shortlist,
159                 }
160                 widgets.signal_autoconnect(dic)
161
162                 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
163                 iconPath = pixmapspath + '/gonvert.png'
164                 if os.path.exists(iconPath):
165                         self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
166                 else:
167                         _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
168
169                 self._load_settings()
170
171         def _load_settings(self):
172                 #Restore window size from previously saved settings if it exists and is valid.
173                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
174                 if os.path.exists(windowDatPath):
175                         #Retrieving previous window settings from ~/.gonvert/window.dat
176                         saved_window = pickle.load(open(windowDatPath, "r"))
177                         #If the 'size' has been stored, then extract size from saved_window.
178                         if 'size' in saved_window:
179                                 a, b = saved_window['size']
180                                 self._mainWindow.resize(a, b)
181                         else:
182                                 #Maximize if no previous size was found
183                                 #self._mainWindow.maximize()
184                                 pass
185                 else:
186                         #Maximize if no previous window.dat file was found
187                         #self._mainWindow.maximize()
188                         pass
189
190                 #Restore selections from previously saved settings if it exists and is valid.
191                 historical_catergory_found = False
192                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
193                 if os.path.exists(selectionsDatPath):
194                         #Retrieving previous selections from ~/.gonvert/selections.dat
195                         selections = pickle.load(open(selectionsDatPath, 'r'))
196                         #Restoring previous selections.
197                         #If the 'selected_unts' has been stored, then extract self._selected_units from selections.
198                         if 'selected_units' in selections:
199                                 self._selected_units = selections['selected_units']
200                         #Make sure that the 'self._selected_category' has been stored.
201                         if 'selected_category' in selections:
202                                 #Match an available category to the previously selected category.
203                                 for counter in range(len(unit_data.UNIT_CATEGORIES)):
204                                         if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
205                                                 # Restore the previously selected category.
206                                                 self._categoryView.set_cursor(counter, self._categoryColumn, False)
207                                                 self._categoryView.grab_focus()
208                                 historical_catergory_found = True
209
210                 if not historical_catergory_found:
211                         print "Couldn't find saved category, using default."
212                         #If historical records were not kept then default to
213                         # put the focus on the first category
214                         self._categoryView.set_cursor(0, self._categoryColumn, False)
215                         self._categoryView.grab_focus()
216
217                 self.restore_units()
218
219         def _save_settings(self):
220                 """
221                 This routine saves the selections to a file, and
222                 should therefore only be called when exiting the program.
223
224                 Update selections dictionary which consists of the following keys:
225                 'self._selected_category': full name of selected category
226                 'self._selected_units': self._selected_units dictionary which contains:
227                 [categoryname: #1 displayed unit, #2 displayed unit]
228                 """
229                 #Determine the contents of the selected category row
230                 selected, iter = self._categoryView.get_selection().get_selected()
231                 self._selected_category = self._categoryModel.get_value(iter, 0)
232
233                 selections = {
234                         'selected_category': self._selected_category,
235                         'selected_units': self._selected_units
236                 }
237                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
238                 pickle.dump(selections, open(selectionsDatPath, 'w'))
239
240                 #Get last size of app and save it
241                 window_settings = {
242                         'size': self._mainWindow.get_size()
243                 }
244                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
245                 pickle.dump(window_settings, open(windowDatPath, 'w'))
246
247         def _clear_find(self):
248                 # switch to "new find" state
249                 self._find_result = []
250                 self._find_count = 0
251
252                 # Clear our user message
253                 self._findLabel.set_text('')
254
255         def _find_first(self):
256                 assert len(self._find_result) == 0
257                 assert self._find_count == 0
258                 findString = string.lower(string.strip(self._findEntry.get_text()))
259                 if not findString:
260                         return
261
262                 # Gather info on all the matching units from all categories
263                 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
264                         units = unit_data.get_units(category)
265                         for unitIndex, unit in enumerate(units):
266                                 loweredUnit = unit.lower()
267                                 if loweredUnit in findString or findString in loweredUnit:
268                                         self._find_result.append((category, unit, catIndex, unitIndex))
269
270                 if not self._find_result:
271                         return
272
273                 self._select_found_unit()
274
275         def _find_wrap_around(self):
276                 assert 0 < len(self._find_result)
277                 assert self._find_count + 1 == len(self._find_result)
278                 #select first result
279                 self._find_count = 0
280                 self._select_found_unit()
281
282         def _find_next(self):
283                 assert 0 < len(self._find_result)
284                 assert self._find_count + 1 < len(self._find_result)
285                 self._find_count += 1
286                 self._select_found_unit()
287
288         def _select_found_unit(self):
289                 assert 0 < len(self._find_result)
290
291                 #check if next find is in a new category (prevent category changes when unnecessary
292                 if self._selected_category != self._find_result[self._find_count][0]:
293                         self._categoryView.set_cursor(
294                                 self._find_result[self._find_count][2], self._categoryColumn, False
295                         )
296
297                 self._unitsView.set_cursor(
298                         self._find_result[self._find_count][3], self._unitNameColumn, True
299                 )
300
301         def _on_findEntry_changed(self, *args):
302                 """
303                 Clear out find results since the user wants to look for something new
304                 """
305                 try:
306                         self._clear_find()
307                 except Exception:
308                         _moduleLogger.exception()
309
310         def _on_shortlist_changed(self, *args):
311                 try:
312                         raise NotImplementedError("%s" % self._shortlistcheck.get_active())
313                 except Exception:
314                         _moduleLogger.exception()
315
316         def _on_edit_shortlist(self, *args):
317                 try:
318                         raise NotImplementedError("%s" % self._toggleShortList.get_active())
319                 except Exception:
320                         _moduleLogger.exception()
321
322         def _on_user_clear_selections(self, *args):
323                 try:
324                         selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
325                         os.remove(selectionsDatPath)
326                         self._selected_units = {}
327                 except Exception:
328                         _moduleLogger.exception()
329
330         def _on_find_activate(self, a):
331                 """
332                 check if 'new find' or 'last find' or 'next-find'
333
334                 new-find = run the find algorithm which also selects the first found unit
335                          = self._find_count = 0 and self._find_result = []
336
337                 last-find = restart from top again
338                           = self._find_count = len(self._find_result)
339
340                 next-find = continue to next found location
341                            = self._find_count = 0 and len(self._find_result)>0
342                 """
343                 try:
344                         if len(self._find_result) == 0:
345                                 self._find_first()
346                         else:
347                                 if self._find_count == len(self._find_result)-1:
348                                         self._find_wrap_around()
349                                 else:
350                                         self._find_next()
351
352                         if not self._find_result:
353                                 self._findLabel.set_text('Text not found')
354                         else:
355                                 resultsLeft = len(self._find_result) - self._find_count - 1
356                                 self._findLabel.set_text(
357                                         '%s result(s) left' % (resultsLeft, )
358                                 )
359                 except Exception:
360                         _moduleLogger.exception()
361
362         def _on_click_unit_column(self, col):
363                 """
364                 Sort the contents of the col when the user clicks on the title.
365                 """
366                 #Determine which column requires sorting
367                 self._unitNameColumn.set_sort_indicator(False)
368                 self._unitValueColumn.set_sort_indicator(False)
369                 self._unitSymbolColumn.set_sort_indicator(False)
370                 for selectedUnitColumn, (maybeCol, sortDirection) in enumerate((
371                         (self._unitNameColumn, self._unit_sort_direction),
372                         (self._unitValueColumn, self._value_sort_direction),
373                         (self._unitSymbolColumn, self._units_sort_direction),
374                 )):
375                         if col is maybeCol:
376                                 col.set_sort_indicator(True)
377                                 col.set_sort_order(not sortDirection)
378                                 break
379                 else:
380                         assert False, "Unknown column: %s" % (col.get_title(), )
381
382                 #declare a spot to hold the sorted list
383                 sorted_list = []
384
385                 #point to the first row
386                 iter = self._unitModel.get_iter_first()
387                 row = 0
388
389                 while iter:
390                         #grab all text from columns for sorting
391
392                         #get the text from each column
393                         unit_text = self._unitModel.get_value(iter, 0)
394                         units_text = self._unitModel.get_value(iter, 2)
395
396                         #do not bother sorting if the value column is empty
397                         if self._unitModel.get_value(iter, 1) == '' and selectedUnitColumn == 1:
398                                 return
399
400                         #special sorting exceptions for ascii values (instead of float values)
401                         if self._selected_category == "Computer Numbers":
402                                 value_text = self._unitModel.get_value(iter, 1)
403                         else:
404                                 if self._unitModel.get_value(iter, 1) == None or self._unitModel.get_value(iter, 1) == '':
405                                         value_text = ''
406                                 else:
407                                         value_text = float(self._unitModel.get_value(iter, 1))
408
409                         if selectedUnitColumn == 0:
410                                 sorted_list.append((unit_text, value_text, units_text))
411                         elif selectedUnitColumn == 1:
412                                 sorted_list.append((value_text, unit_text, units_text))
413                         else:
414                                 sorted_list.append((units_text, value_text, unit_text))
415
416                         #point to the next row in the self._unitModel
417                         iter = self._unitModel.iter_next(iter)
418                         row = row+1
419
420                 #check if no calculations have been made yet (don't bother sorting)
421                 if row == 0:
422                         return
423                 else:
424                         if selectedUnitColumn == 0:
425                                 if not self._unit_sort_direction:
426                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
427                                         self._unit_sort_direction = True
428                                 else:
429                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(y), string.lower(x)))
430                                         self._unit_sort_direction = False
431                         elif selectedUnitColumn == 1:
432                                 sorted_list.sort()
433                                 if not self._value_sort_direction:
434                                         self._value_sort_direction = True
435                                 else:
436                                         sorted_list.reverse()
437                                         self._value_sort_direction = False
438                         else:
439                                 if not self._units_sort_direction:
440                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(x), string.lower(y)))
441                                         self._units_sort_direction = True
442                                 else:
443                                         sorted_list.sort(lambda (x, xx, xxx), (y, yy, yyy): cmp(string.lower(y), string.lower(x)))
444                                         self._units_sort_direction = False
445
446                         #Clear out the previous list of units
447                         self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
448                         self._unitsView.set_model(self._unitModel)
449
450                         #colourize each row differently for easier reading
451                         self._unitsView.set_property('rules_hint', 1)
452
453                         #Clear out the description
454                         text_model = gtk.TextBuffer(None)
455                         self._unitDescription.set_buffer(text_model)
456
457                         if selectedUnitColumn == 0:
458                                 for unit, value, units in sorted_list:
459                                         iter = self._unitModel.append()
460                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
461                         elif selectedUnitColumn == 1:
462                                 for value, unit, units in sorted_list:
463                                         iter = self._unitModel.append()
464                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
465                         else:
466                                 for units, value, unit in sorted_list:
467                                         iter = self._unitModel.append()
468                                         self._unitModel.set(iter, 0, unit, 1, str(value), 2, units)
469                 return
470
471         def _on_click_category(self, row):
472                 #Clear out the previous list of units
473                 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
474                 self._unitsView.set_model(self._unitModel)
475
476                 #Colourize each row alternately for easier reading
477                 self._unitsView.set_property('rules_hint', 1)
478
479                 #Clear out the description
480                 text_model = gtk.TextBuffer(None)
481                 self._unitDescription.set_buffer(text_model)
482
483                 #Determine the contents of the selected category row
484                 selected, iter = row.get_selection().get_selected()
485
486                 self._selected_category = self._categoryModel.get_value(iter, 0)
487
488                 self._unit_sort_direction = False
489                 self._value_sort_direction = False
490                 self._units_sort_direction = False
491                 self._unitNameColumn.set_sort_indicator(False)
492                 self._unitValueColumn.set_sort_indicator(False)
493                 self._unitSymbolColumn.set_sort_indicator(False)
494
495                 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[selected.get_value(iter, 0)]
496                 keys = self._unitDataInCategory.keys()
497                 keys.sort()
498                 del keys[0] # do not display .base_unit description key
499
500                 #Fill up the units descriptions and clear the value cells
501                 for key in keys:
502                         iter = self._unitModel.append()
503                         self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
504
505                 self._unitName.set_text('')
506                 self._unitValue.set_text('')
507                 self._previousUnitName.set_text('')
508                 self._previousUnitValue.set_text('')
509                 self._unitSymbol.set_text('')
510                 self._previousUnitSymbol.set_text('')
511
512                 self.restore_units()
513
514         def restore_units(self):
515                 # Restore the previous historical settings of previously selected units in this newly selected category
516                 #Since category has just been clicked, the list will be sorted already.
517                 if self._selected_category in self._selected_units:
518                         if self._selected_units[self._selected_category][0]:
519                                 #self._selected_units[self._selected_category] = [selected_unit, self._selected_units[self._selected_category][0]]
520
521                                 units = unit_data.UNIT_DESCRIPTIONS[self._selected_category].keys()
522                                 units.sort()
523                                 del units[0] # do not display .base_unit description key
524
525                                 #Restore oldest selection first.
526                                 if self._selected_units[self._selected_category][1]:
527                                         unit_no = 0
528                                         for unit in units:
529                                                 if unit == self._selected_units[self._selected_category][1]:
530                                                         self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
531                                                 unit_no = unit_no+1
532
533                                 #Restore newest selection second.
534                                 unit_no = 0
535                                 for unit in units:
536                                         if unit == self._selected_units[self._selected_category][0]:
537                                                 self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
538                                         unit_no = unit_no+1
539
540                 # select the text so user can start typing right away
541                 self._unitValue.grab_focus()
542                 self._unitValue.select_region(0, -1)
543
544         def _on_click_unit(self, row):
545                 self._calcsuppress = True #suppress calculations
546
547                 #Determine the contents of the selected row.
548                 selected, iter = self._unitsView.get_selection().get_selected()
549
550                 selected_unit = selected.get_value(iter, 0)
551
552                 unit_spec = self._unitDataInCategory[selected_unit]
553
554                 #Clear out the description
555                 text_model = gtk.TextBuffer(None)
556                 self._unitDescription.set_buffer(text_model)
557
558                 enditer = text_model.get_end_iter()
559                 text_model.insert(enditer, unit_spec[2])
560
561                 if self._unitName.get_text() != selected_unit:
562                         self._previousUnitName.set_text(self._unitName.get_text())
563                         self._previousUnitValue.set_text(self._unitValue.get_text())
564                         if self._unitSymbol.get() == None:
565                                 self._previousUnitSymbol.set_text('')
566                         else:
567                                 self._previousUnitSymbol.set_text(self._unitSymbol.get())
568                 self._unitName.set_text(selected_unit)
569
570                 self._unitValue.set_text(selected.get_value(iter, 1))
571
572                 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
573                 if self._unitValue.get_text() == '':
574                         if self._selected_category == "Computer Numbers":
575                                 self._unitValue.set_text("0")
576                         else:
577                                 self._unitValue.set_text("0.0")
578
579                 #For historical purposes, record this unit as the most recent one in this category.
580                 # Also, if a previous unit exists, then shift that previous unit to oldest unit.
581                 if self._selected_category in self._selected_units:
582                         if self._selected_units[self._selected_category][0]:
583                                 self._selected_units[self._selected_category] = [selected_unit, self._selected_units[self._selected_category][0]]
584                 else:
585                         self._selected_units[self._selected_category] = [selected_unit, '']
586
587                 # select the text so user can start typing right away
588                 self._unitValue.grab_focus()
589                 self._unitValue.select_region(0, -1)
590
591                 self._calcsuppress = False #enable calculations
592
593         def messagebox_ok_clicked(self, a):
594                 messagebox.hide()
595
596         def _on_user_write_units(self, a):
597                 ''"Write the list of categories and units to stdout for documentation purposes.''"
598                 messagebox_model = gtk.TextBuffer(None)
599                 messageboxtext.set_buffer(messagebox_model)
600                 messagebox_model.insert_at_cursor(_(u'The units are being written to stdout. You can capture this printout by starting gonvert from the command line as follows: \n$ gonvert > file.txt'), -1)
601                 messagebox.show()
602                 while gtk.events_pending():
603                         gtk.mainiteration(False)
604
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 unit_data.UNIT_CATEGORIES:
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         def _on_about_clicked(self, a):
715                 dlg = gtk.AboutDialog()
716                 dlg.set_name(constants.__pretty_app_name__)
717                 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
718                 dlg.set_copyright("Copyright 2009 - GPL")
719                 dlg.set_comments("")
720                 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
721                 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
722                 dlg.run()
723                 dlg.destroy()
724
725         def _on_user_exit(self, *args):
726                 try:
727                         self._save_settings()
728                 except Exception:
729                         _moduleLogger.exception()
730                 finally:
731                         gtk.main_quit()
732
733
734 def main():
735         logging.basicConfig(level = logging.DEBUG)
736         try:
737                 os.makedirs(constants._data_path_)
738         except OSError, e:
739                 if e.errno != 17:
740                         raise
741
742         gonvert = Gonvert()
743         gtk.main()
744
745
746 if __name__ == "__main__":
747         main()