7e21014d3e23f827292f2ca046f13f8ecdd97fe7
[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 gettext
8 import logging
9
10 import gobject
11 import gtk
12 import gtk.glade
13 import gtk.gdk
14
15 import constants
16 import unit_data
17
18
19 _moduleLogger = logging.getLogger("gonvert_glade")
20
21 gettext.bindtextdomain('gonvert', '/usr/share/locale')
22 gettext.textdomain('gonvert')
23 _ = gettext.gettext
24
25
26 def change_menu_label(widgets, labelname, newtext):
27         item_label = widgets.get_widget(labelname).get_children()[0]
28         item_label.set_text(newtext)
29
30
31 class Gonvert(object):
32
33         _glade_files = [
34                 os.path.join(os.path.dirname(__file__), "gonvert.glade"),
35                 os.path.join(os.path.dirname(__file__), "../data/gonvert.glade"),
36                 os.path.join(os.path.dirname(__file__), "../lib/gonvert.glade"),
37                 '/usr/lib/gonvert/gonvert.glade',
38         ]
39
40         def __init__(self):
41                 self._unitDataInCategory = None
42                 self._calcsuppress = False
43                 self._unit_sort_direction = False
44                 self._value_sort_direction = False
45                 self._units_sort_direction = False
46                 self._isFullScreen = False
47
48                 self._find_result = [] # empty find result list
49                 self._findIndex = 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.set_property('rules_hint', 1)
83                 self._unitsView_selection = self._unitsView.get_selection()
84
85                 self._unitName = widgets.get_widget('unitName')
86                 self._unitValue = widgets.get_widget('unitValue')
87                 self._previousUnitName = widgets.get_widget('previousUnitName')
88                 self._previousUnitValue = widgets.get_widget('previousUnitValue')
89                 messagebox = widgets.get_widget('msgbox')
90                 messageboxtext = widgets.get_widget('msgboxtext')
91
92                 self._unitSymbol = widgets.get_widget('unitSymbol')
93                 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
94
95                 self._unitDescription = widgets.get_widget('unitDescription')
96
97                 self._searchLayout = widgets.get_widget('searchLayout')
98                 self._searchLayout.hide()
99                 self._findEntry = widgets.get_widget('findEntry')
100                 self._findLabel = widgets.get_widget('findLabel')
101                 findButton = widgets.get_widget('findButton')
102                 ToolTips = gtk.Tooltips()
103                 ToolTips.set_tip(findButton, _(u'Find unit (F6)'))
104
105                 #insert a self._categoryColumnumn into the units list even though the heading will not be seen
106                 renderer = gtk.CellRendererText()
107                 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
108                 self._unitNameColumn.set_property('resizable', 1)
109                 self._unitNameColumn.add_attribute(renderer, 'text', 0)
110                 self._unitNameColumn.set_clickable(True)
111                 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
112                 self._unitsView.append_column(self._unitNameColumn)
113
114                 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
115                 self._unitValueColumn.set_property('resizable', 1)
116                 self._unitValueColumn.add_attribute(renderer, 'text', 1)
117                 self._unitValueColumn.set_clickable(True)
118                 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
119                 self._unitsView.append_column(self._unitValueColumn)
120
121                 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
122                 self._unitSymbolColumn.set_property('resizable', 1)
123                 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
124                 self._unitSymbolColumn.set_clickable(True)
125                 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
126                 self._unitsView.append_column(self._unitSymbolColumn)
127
128                 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
129                 self._sortedUnitModel = gtk.TreeModelSort(self._unitModel)
130                 columns = self._get_column_sort_stuff()
131                 for columnIndex, (column, sortDirection, col_cmp) in enumerate(columns):
132                         self._sortedUnitModel.set_sort_func(columnIndex, col_cmp)
133                 self._unitsView.set_model(self._sortedUnitModel)
134
135                 #Insert a column into the category list even though the heading will not be seen
136                 renderer = gtk.CellRendererText()
137                 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
138                 self._categoryColumn.set_property('resizable', 1)
139                 self._categoryColumn.add_attribute(renderer, 'text', 0)
140                 self._categoryView.append_column(self._categoryColumn)
141
142                 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
143                 self._categoryView.set_model(self._categoryModel)
144                 #colourize each row differently for easier reading
145                 self._categoryView.set_property('rules_hint', 1)
146
147                 #Populate the catagories list
148                 for key in unit_data.UNIT_CATEGORIES:
149                         iter = self._categoryModel.append()
150                         self._categoryModel.set(iter, 0, key)
151
152                 #--------- connections to GUI ----------------
153                 dic = {
154                         "on_exit_menu_activate": self._on_user_exit,
155                         "on_main_window_destroy": self._on_user_exit,
156                         "on_categoryView_select_row": self._on_click_category,
157                         "on_unitValue_changed": self._on_unit_value_changed,
158                         "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
159                         "on_writeUnitsMenuItem_activate": self._on_user_write_units,
160                         "on_findButton_clicked": self._on_find_activate,
161                         "on_findEntry_activated": self._on_find_activate,
162                         "on_findEntry_changed": self._on_findEntry_changed,
163                         "on_aboutMenuItem_activate": self._on_about_clicked,
164                         "on_messagebox_ok_clicked": self.messagebox_ok_clicked,
165                         "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
166                         "on_unitsView_cursor_changed": self._on_click_unit,
167                         "on_shortlistcheck_toggled": self._on_shortlist_changed,
168                         "on_toggleShortList_activate": self._on_edit_shortlist,
169                 }
170                 widgets.signal_autoconnect(dic)
171                 self._mainWindow.connect("key-press-event", self._on_key_press)
172                 self._mainWindow.connect("window-state-event", self._on_window_state_change)
173
174                 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
175                 iconPath = pixmapspath + '/gonvert.png'
176                 if os.path.exists(iconPath):
177                         self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
178                 else:
179                         _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
180
181                 self._load_settings()
182
183         def _load_settings(self):
184                 #Restore window size from previously saved settings if it exists and is valid.
185                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
186                 if os.path.exists(windowDatPath):
187                         #Retrieving previous window settings from ~/.gonvert/window.dat
188                         saved_window = pickle.load(open(windowDatPath, "r"))
189                         #If the 'size' has been stored, then extract size from saved_window.
190                         if 'size' in saved_window:
191                                 a, b = saved_window['size']
192                                 self._mainWindow.resize(a, b)
193                         else:
194                                 #Maximize if no previous size was found
195                                 #self._mainWindow.maximize()
196                                 pass
197                 else:
198                         #Maximize if no previous window.dat file was found
199                         #self._mainWindow.maximize()
200                         pass
201
202                 #Restore selections from previously saved settings if it exists and is valid.
203                 historical_catergory_found = False
204                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
205                 if os.path.exists(selectionsDatPath):
206                         #Retrieving previous selections from ~/.gonvert/selections.dat
207                         selections = pickle.load(open(selectionsDatPath, 'r'))
208                         #Restoring previous selections.
209                         #If the 'selected_unts' has been stored, then extract self._selected_units from selections.
210                         if 'selected_units' in selections:
211                                 self._selected_units = selections['selected_units']
212                         #Make sure that the 'self._selected_category' has been stored.
213                         if 'selected_category' in selections:
214                                 #Match an available category to the previously selected category.
215                                 for counter in range(len(unit_data.UNIT_CATEGORIES)):
216                                         if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
217                                                 # Restore the previously selected category.
218                                                 self._categoryView.set_cursor(counter, self._categoryColumn, False)
219                                                 self._categoryView.grab_focus()
220                                 historical_catergory_found = True
221
222                 if not historical_catergory_found:
223                         print "Couldn't find saved category, using default."
224                         #If historical records were not kept then default to
225                         # put the focus on the first category
226                         self._categoryView.set_cursor(0, self._categoryColumn, False)
227                         self._categoryView.grab_focus()
228
229                 self.restore_units()
230
231         def _save_settings(self):
232                 """
233                 This routine saves the selections to a file, and
234                 should therefore only be called when exiting the program.
235
236                 Update selections dictionary which consists of the following keys:
237                 'self._selected_category': full name of selected category
238                 'self._selected_units': self._selected_units dictionary which contains:
239                 [categoryname: #1 displayed unit, #2 displayed unit]
240                 """
241                 #Determine the contents of the selected category row
242                 selected, iter = self._categoryView.get_selection().get_selected()
243                 self._selected_category = self._categoryModel.get_value(iter, 0)
244
245                 selections = {
246                         'selected_category': self._selected_category,
247                         'selected_units': self._selected_units
248                 }
249                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
250                 pickle.dump(selections, open(selectionsDatPath, 'w'))
251
252                 #Get last size of app and save it
253                 window_settings = {
254                         'size': self._mainWindow.get_size()
255                 }
256                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
257                 pickle.dump(window_settings, open(windowDatPath, 'w'))
258
259         def _clear_find(self):
260                 # switch to "new find" state
261                 self._find_result = []
262                 self._findIndex = 0
263
264                 # Clear our user message
265                 self._findLabel.set_text('')
266
267         def _find_first(self):
268                 assert len(self._find_result) == 0
269                 assert self._findIndex == 0
270                 findString = string.lower(string.strip(self._findEntry.get_text()))
271                 if not findString:
272                         return
273
274                 # Gather info on all the matching units from all categories
275                 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
276                         units = unit_data.get_units(category)
277                         for unitIndex, unit in enumerate(units):
278                                 loweredUnit = unit.lower()
279                                 if loweredUnit in findString or findString in loweredUnit:
280                                         self._find_result.append((category, unit, catIndex, unitIndex))
281
282         def _update_find_selection(self):
283                 assert 0 < len(self._find_result)
284
285                 #check if next find is in a new category (prevent category changes when unnecessary
286                 if self._selected_category != self._find_result[self._findIndex][0]:
287                         self._categoryView.set_cursor(
288                                 self._find_result[self._findIndex][2], self._categoryColumn, False
289                         )
290
291                 self._unitsView.set_cursor(
292                         self._find_result[self._findIndex][3], self._unitNameColumn, True
293                 )
294
295         def _find_next(self):
296                 """
297                 check if 'new find' or 'last find' or 'next-find'
298
299                 new-find = run the find algorithm which also selects the first found unit
300                          = self._findIndex = 0 and self._find_result = []
301
302                 last-find = restart from top again
303                           = self._findIndex = len(self._find_result)
304
305                 next-find = continue to next found location
306                            = self._findIndex = 0 and len(self._find_result)>0
307                 """
308                 if len(self._find_result) == 0:
309                         self._find_first()
310                 else:
311                         if self._findIndex == len(self._find_result)-1:
312                                 self._findIndex = 0
313                         else:
314                                 self._findIndex += 1
315
316                 if not self._find_result:
317                         self._findLabel.set_text('Text not found')
318                 else:
319                         self._update_find_selection()
320                         resultsLeft = len(self._find_result) - self._findIndex - 1
321                         self._findLabel.set_text(
322                                 '%s result(s) left' % (resultsLeft, )
323                         )
324
325         def _find_previous(self):
326                 """
327                 check if 'new find' or 'last find' or 'next-find'
328
329                 new-find = run the find algorithm which also selects the first found unit
330                          = self._findIndex = 0 and self._find_result = []
331
332                 last-find = restart from top again
333                           = self._findIndex = len(self._find_result)
334
335                 next-find = continue to next found location
336                            = self._findIndex = 0 and len(self._find_result)>0
337                 """
338                 if len(self._find_result) == 0:
339                         self._find_first()
340                 else:
341                         if self._findIndex == 0:
342                                 self._findIndex = len(self._find_result)-1
343                         else:
344                                 self._findIndex -= 1
345
346                 if not self._find_result:
347                         self._findLabel.set_text('Text not found')
348                 else:
349                         self._update_find_selection()
350                         resultsLeft = len(self._find_result) - self._findIndex - 1
351                         self._findLabel.set_text(
352                                 '%s result(s) left' % (resultsLeft, )
353                         )
354
355         def _toggle_find(self):
356                 if self._searchLayout.get_property("visible"):
357                         self._searchLayout.hide()
358                 else:
359                         self._searchLayout.show()
360
361         def _on_shortlist_changed(self, *args):
362                 try:
363                         raise NotImplementedError("%s" % self._shortlistcheck.get_active())
364                 except Exception:
365                         _moduleLogger.exception("")
366
367         def _on_edit_shortlist(self, *args):
368                 try:
369                         raise NotImplementedError("%s" % self._toggleShortList.get_active())
370                 except Exception:
371                         _moduleLogger.exception("")
372
373         def _on_user_clear_selections(self, *args):
374                 try:
375                         selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
376                         os.remove(selectionsDatPath)
377                         self._selected_units = {}
378                 except Exception:
379                         _moduleLogger.exception("")
380
381         def _on_key_press(self, widget, event, *args):
382                 """
383                 @note Hildon specific
384                 """
385                 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
386                 try:
387                         if (
388                                 event.keyval == gtk.keysyms.F6 or
389                                 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
390                         ):
391                                 if self._isFullScreen:
392                                         self._mainWindow.unfullscreen()
393                                 else:
394                                         self._mainWindow.fullscreen()
395                         elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
396                                 self._toggle_find()
397                         elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
398                                 self._find_previous()
399                         elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
400                                 self._find_next()
401                 except Exception, e:
402                         _moduleLogger.exception("")
403
404         def _on_window_state_change(self, widget, event, *args):
405                 """
406                 @note Hildon specific
407                 """
408                 try:
409                         if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
410                                 self._isFullScreen = True
411                         else:
412                                 self._isFullScreen = False
413                 except Exception, e:
414                         _moduleLogger.exception("")
415
416         def _on_findEntry_changed(self, *args):
417                 """
418                 Clear out find results since the user wants to look for something new
419                 """
420                 try:
421                         self._clear_find()
422                 except Exception:
423                         _moduleLogger.exception("")
424
425         def _on_find_activate(self, a):
426                 try:
427                         self._find_next()
428                 except Exception:
429                         _moduleLogger.exception("")
430
431         def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
432                 leftUnitText = self._unitModel.get_value(leftItr, 0)
433                 rightUnitText = self._unitModel.get_value(rightItr, 0)
434                 return cmp(leftUnitText, rightUnitText)
435
436         def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
437                 leftSymbolText = self._unitModel.get_value(leftItr, 2)
438                 rightSymbolText = self._unitModel.get_value(rightItr, 2)
439                 return cmp(leftSymbolText, rightSymbolText)
440
441         def _value_model_cmp(self, sortedModel, leftItr, rightItr):
442                 #special sorting exceptions for ascii values (instead of float values)
443                 if self._selected_category == "Computer Numbers":
444                         leftValue = self._unitModel.get_value(leftItr, 1)
445                         rightValue = self._unitModel.get_value(rightItr, 1)
446                 else:
447                         leftValueText = self._unitModel.get_value(leftItr, 1)
448                         leftValue = float(leftValueText) if leftValueText else 0.0
449
450                         rightValueText = self._unitModel.get_value(rightItr, 1)
451                         rightValue = float(rightValueText) if rightValueText else 0.0
452                 return cmp(leftValue, rightValue)
453
454         def _get_column_sort_stuff(self):
455                 columns = (
456                         (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
457                         (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
458                         (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
459                 )
460                 return columns
461
462         def _on_click_unit_column(self, col):
463                 """
464                 Sort the contents of the col when the user clicks on the title.
465                 """
466                 try:
467                         #Determine which column requires sorting
468                         columns = self._get_column_sort_stuff()
469                         for column, directionName, col_cmp in columns:
470                                 column.set_sort_indicator(False)
471                         for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
472                                 if col is maybeCol:
473                                         direction = getattr(self, directionName)
474                                         gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
475
476                                         # cause a sort
477                                         self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
478
479                                         # set the visual for sorting
480                                         col.set_sort_indicator(True)
481                                         col.set_sort_order(not direction)
482
483                                         setattr(self, directionName, not direction)
484                                         break
485                         else:
486                                 assert False, "Unknown column: %s" % (col.get_title(), )
487                 except Exception:
488                         _moduleLogger.exception("")
489
490         def _on_click_category(self, *args):
491                 #Clear out the description
492                 self._unitDescription.get_buffer().set_text("")
493
494                 #Determine the contents of the selected category row
495                 selected, iter = self._categoryView.get_selection().get_selected()
496                 self._selected_category = self._categoryModel.get_value(iter, 0)
497
498                 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selected_category]
499
500                 #Fill up the units descriptions and clear the value cells
501                 self._unitModel.clear()
502                 for key in unit_data.get_units(self._selected_category):
503                         iter = self._unitModel.append()
504                         self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
505                 self._sortedUnitModel.sort_column_changed()
506
507                 self._unitName.set_text('')
508                 self._unitValue.set_text('')
509                 self._previousUnitName.set_text('')
510                 self._previousUnitValue.set_text('')
511                 self._unitSymbol.set_text('')
512                 self._previousUnitSymbol.set_text('')
513
514                 self.restore_units()
515
516         def restore_units(self):
517                 # Restore the previous historical settings of previously selected units in this newly selected category
518                 #Since category has just been clicked, the list will be sorted already.
519                 if self._selected_category in self._selected_units:
520                         if self._selected_units[self._selected_category][0]:
521                                 #self._selected_units[self._selected_category] = [selected_unit, self._selected_units[self._selected_category][0]]
522
523                                 units = unit_data.UNIT_DESCRIPTIONS[self._selected_category].keys()
524                                 units.sort()
525                                 del units[0] # do not display .base_unit description key
526
527                                 #Restore oldest selection first.
528                                 if self._selected_units[self._selected_category][1]:
529                                         unit_no = 0
530                                         for unit in units:
531                                                 if unit == self._selected_units[self._selected_category][1]:
532                                                         self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
533                                                 unit_no = unit_no+1
534
535                                 #Restore newest selection second.
536                                 unit_no = 0
537                                 for unit in units:
538                                         if unit == self._selected_units[self._selected_category][0]:
539                                                 self._unitsView.set_cursor(unit_no, self._unitNameColumn, True)
540                                         unit_no = unit_no+1
541
542                 # select the text so user can start typing right away
543                 self._unitValue.grab_focus()
544                 self._unitValue.select_region(0, -1)
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 messagebox_ok_clicked(self, a):
596                 messagebox.hide()
597
598         def _on_user_write_units(self, a):
599                 ''"Write the list of categories and units to stdout for documentation purposes.''"
600                 messagebox_model = gtk.TextBuffer(None)
601                 messageboxtext.set_buffer(messagebox_model)
602                 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)
603                 messagebox.show()
604                 while gtk.events_pending():
605                         gtk.mainiteration(False)
606
607                 total_categories = 0
608                 total_units = 0
609                 print 'gonvert-%s%s' % (
610                         constants.__version__,
611                         _(u' - Unit Conversion Utility  - Convertible units listing: ')
612                 )
613                 for category_key in unit_data.UNIT_CATEGORIES:
614                         total_categories = total_categories + 1
615                         print category_key, ": "
616                         self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[category_key]
617                         unit_keys = self._unitDataInCategory.keys()
618                         unit_keys.sort()
619                         del unit_keys[0] # do not display .base_unit description key
620                         for unit_key in unit_keys:
621                                 total_units = total_units + 1
622                                 print "\t", unit_key
623                 print total_categories, ' categories'
624                 print total_units, ' units'
625
626         def _on_unit_value_changed(self, a):
627                 if self._calcsuppress:
628                         #self._calcsuppress = False
629                         return
630                 # determine if value to be calculated is empty
631                 if self._selected_category == "Computer Numbers":
632                         if self._unitValue.get_text() == '':
633                                 value = '0'
634                         else:
635                                 value = self._unitValue.get_text()
636                 else:
637                         if self._unitValue.get_text() == '':
638                                 value = 0.0
639                         else:
640                                 value = float(self._unitValue.get_text())
641
642                 if self._unitName.get_text() != '':
643                         func, arg = self._unitDataInCategory[self._unitName.get_text()][0] #retrieve the conversion function and value from the selected unit
644                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
645
646                         keys = self._unitDataInCategory.keys()
647                         keys.sort()
648                         del keys[0]
649                         row = 0
650
651                         #point to the first row
652                         iter = self._unitModel.get_iter_first()
653
654                         while iter:
655                                 #get the formula from the name at the row
656                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
657
658                                 #set the result in the value column
659                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
660
661                                 #point to the next row in the self._unitModel
662                                 iter = self._unitModel.iter_next(iter)
663
664                         # if the second row has a unit then update its value
665                         if self._previousUnitName.get_text() != '':
666                                 self._calcsuppress = True
667                                 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
668                                 self._previousUnitValue.set_text(str(apply(func.from_base, (base, arg, ))))
669                                 self._calcsuppress = False
670
671         def _on_previous_unit_value_changed(self, a):
672                 if self._calcsuppress == True:
673                         #self._calcsuppress = False
674                         return
675                 # determine if value to be calculated is empty
676                 if self._selected_category == "Computer Numbers":
677                         if self._previousUnitValue.get_text() == '':
678                                 value = '0'
679                         else:
680                                 value = self._previousUnitValue.get_text()
681                 else:
682                         if self._previousUnitValue.get_text() == '':
683                                 value = 0.0
684                         else:
685                                 value = float(self._previousUnitValue.get_text())
686
687                 if self._previousUnitName.get_text() != '':
688                         func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0] #retrieve the conversion function and value from the selected unit
689                         base = apply(func.to_base, (value, arg, )) #determine the base unit value
690
691                         keys = self._unitDataInCategory.keys()
692                         keys.sort()
693                         del keys[0]
694                         row = 0
695
696                         #point to the first row
697                         iter = self._unitModel.get_iter_first()
698
699                         while iter:
700                                 #get the formula from the name at the row
701                                 func, arg = self._unitDataInCategory[self._unitModel.get_value(iter, 0)][0]
702
703                                 #set the result in the value column
704                                 self._unitModel.set(iter, 1, str(apply(func.from_base, (base, arg, ))))
705
706                                 #point to the next row in the self._unitModel
707                                 iter = self._unitModel.iter_next(iter)
708
709                         # if the second row has a unit then update its value
710                         if self._unitName.get_text() != '':
711                                 self._calcsuppress = True
712                                 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
713                                 self._unitValue.set_text(str(apply(func.from_base, (base, arg, ))))
714                                 self._calcsuppress = False
715
716         def _on_about_clicked(self, a):
717                 dlg = gtk.AboutDialog()
718                 dlg.set_name(constants.__pretty_app_name__)
719                 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
720                 dlg.set_copyright("Copyright 2009 - GPL")
721                 dlg.set_comments("")
722                 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
723                 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
724                 dlg.run()
725                 dlg.destroy()
726
727         def _on_user_exit(self, *args):
728                 try:
729                         self._save_settings()
730                 except Exception:
731                         _moduleLogger.exception("")
732                 finally:
733                         gtk.main_quit()
734
735
736 def main():
737         logging.basicConfig(level = logging.DEBUG)
738         try:
739                 os.makedirs(constants._data_path_)
740         except OSError, e:
741                 if e.errno != 17:
742                         raise
743
744         gonvert = Gonvert()
745         gtk.main()
746
747
748 if __name__ == "__main__":
749         main()