19 _moduleLogger = logging.getLogger("gonvert_glade")
21 gettext.bindtextdomain('gonvert', '/usr/share/locale')
22 gettext.textdomain('gonvert')
26 def change_menu_label(widgets, labelname, newtext):
27 item_label = widgets.get_widget(labelname).get_children()[0]
28 item_label.set_text(newtext)
31 class Gonvert(object):
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',
41 self._unitDataInCategory = None
42 self._unit_sort_direction = False
43 self._value_sort_direction = False
44 self._units_sort_direction = False
45 self._isFullScreen = False
47 self._find_result = [] # empty find result list
48 self._findIndex = 0 # default to find result number zero
50 self._selectedCategory = '' # preset to no selected category
51 self._defaultUnitForCategory = {} # empty dictionary for later use
53 #check to see if glade file is in current directory (user must be
54 # running from download untar directory)
55 for gladePath in self._glade_files:
56 if os.path.isfile(gladePath):
57 homepath = os.path.dirname(gladePath)
58 pixmapspath = "/".join((homepath, "pixmaps"))
59 widgets = gtk.glade.XML(gladePath)
62 _moduleLogger.error("UI Descriptor not found!")
66 self._mainWindow = widgets.get_widget('mainWindow')
68 change_menu_label(widgets, 'fileMenuItem', _('File'))
69 change_menu_label(widgets, 'exitMenuItem', _('Exit'))
70 change_menu_label(widgets, 'toolsMenuItem', _('Tools'))
71 change_menu_label(widgets, 'clearSelectionMenuItem', _('Clear selections'))
72 change_menu_label(widgets, 'writeUnitsMenuItem', _('Write Units'))
73 change_menu_label(widgets, 'helpMenuItem', _('Help'))
74 change_menu_label(widgets, 'aboutMenuItem', _('About'))
75 change_menu_label(widgets, 'findButton', _('Find'))
77 self._shortlistcheck = widgets.get_widget('shortlistcheck')
78 self._toggleShortList = widgets.get_widget('toggleShortList')
80 self._categoryView = widgets.get_widget('categoryView')
82 self._unitsView = widgets.get_widget('unitsView')
83 self._unitsView.set_property('rules_hint', 1)
84 self._unitsView_selection = self._unitsView.get_selection()
86 self._unitName = widgets.get_widget('unitName')
87 self._unitValue = widgets.get_widget('unitValue')
88 self._previousUnitName = widgets.get_widget('previousUnitName')
89 self._previousUnitValue = widgets.get_widget('previousUnitValue')
90 messagebox = widgets.get_widget('msgbox')
91 messageboxtext = widgets.get_widget('msgboxtext')
93 self._unitSymbol = widgets.get_widget('unitSymbol')
94 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
96 self._unitDescription = widgets.get_widget('unitDescription')
98 self._searchLayout = widgets.get_widget('searchLayout')
99 self._searchLayout.hide()
100 self._findEntry = widgets.get_widget('findEntry')
101 self._findLabel = widgets.get_widget('findLabel')
102 self._findButton = widgets.get_widget('findButton')
103 ToolTips = gtk.Tooltips()
104 ToolTips.set_tip(self._findButton, _(u'Find unit (F6)'))
106 #insert a self._categoryColumnumn into the units list even though the heading will not be seen
107 renderer = gtk.CellRendererText()
108 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
109 self._unitNameColumn.set_property('resizable', 1)
110 self._unitNameColumn.add_attribute(renderer, 'text', 0)
111 self._unitNameColumn.set_clickable(True)
112 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
113 self._unitsView.append_column(self._unitNameColumn)
115 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
116 self._unitValueColumn.set_property('resizable', 1)
117 self._unitValueColumn.add_attribute(renderer, 'text', 1)
118 self._unitValueColumn.set_clickable(True)
119 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
120 self._unitsView.append_column(self._unitValueColumn)
122 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
123 self._unitSymbolColumn.set_property('resizable', 1)
124 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
125 self._unitSymbolColumn.set_clickable(True)
126 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
127 self._unitsView.append_column(self._unitSymbolColumn)
129 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
130 self._sortedUnitModel = gtk.TreeModelSort(self._unitModel)
131 columns = self._get_column_sort_stuff()
132 for columnIndex, (column, sortDirection, col_cmp) in enumerate(columns):
133 self._sortedUnitModel.set_sort_func(columnIndex, col_cmp)
134 self._unitsView.set_model(self._sortedUnitModel)
136 #Insert a column into the category list even though the heading will not be seen
137 renderer = gtk.CellRendererText()
138 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
139 self._categoryColumn.set_property('resizable', 1)
140 self._categoryColumn.add_attribute(renderer, 'text', 0)
141 self._categoryView.append_column(self._categoryColumn)
143 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
144 self._categoryView.set_model(self._categoryModel)
145 #colourize each row differently for easier reading
146 self._categoryView.set_property('rules_hint', 1)
148 #Populate the catagories list
149 for key in unit_data.UNIT_CATEGORIES:
150 iter = self._categoryModel.append()
151 self._categoryModel.set(iter, 0, key)
153 #--------- connections to GUI ----------------
155 "on_exit_menu_activate": self._on_user_exit,
156 "on_main_window_destroy": self._on_user_exit,
157 "on_categoryView_select_row": self._on_click_category,
158 "on_unitValue_changed": self._on_unit_value_changed,
159 "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
160 "on_writeUnitsMenuItem_activate": self._on_user_write_units,
161 "on_findButton_clicked": self._on_find_activate,
162 "on_findEntry_activated": self._on_find_activate,
163 "on_findEntry_changed": self._on_findEntry_changed,
164 "on_aboutMenuItem_activate": self._on_about_clicked,
165 "on_messagebox_ok_clicked": self.messagebox_ok_clicked,
166 "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
167 "on_unitsView_cursor_changed": self._on_click_unit,
168 "on_shortlistcheck_toggled": self._on_shortlist_changed,
169 "on_toggleShortList_activate": self._on_edit_shortlist,
171 widgets.signal_autoconnect(dic)
172 self._mainWindow.connect("key-press-event", self._on_key_press)
173 self._mainWindow.connect("window-state-event", self._on_window_state_change)
175 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
176 iconPath = pixmapspath + '/gonvert.png'
177 if os.path.exists(iconPath):
178 self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
180 _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
182 self._load_settings()
184 def _load_settings(self):
185 #Restore window size from previously saved settings if it exists and is valid.
186 windowDatPath = "/".join((constants._data_path_, "window.dat"))
187 if os.path.exists(windowDatPath):
188 #Retrieving previous window settings from ~/.gonvert/window.dat
189 saved_window = pickle.load(open(windowDatPath, "r"))
190 #If the 'size' has been stored, then extract size from saved_window.
191 if 'size' in saved_window:
192 a, b = saved_window['size']
193 self._mainWindow.resize(a, b)
195 #Maximize if no previous size was found
196 #self._mainWindow.maximize()
199 #Maximize if no previous window.dat file was found
200 #self._mainWindow.maximize()
203 #Restore selections from previously saved settings if it exists and is valid.
204 historical_catergory_found = False
205 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
206 if os.path.exists(selectionsDatPath):
207 #Retrieving previous selections from ~/.gonvert/selections.dat
208 selections = pickle.load(open(selectionsDatPath, 'r'))
209 #Restoring previous selections.
210 #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
211 if 'selected_units' in selections:
212 self._defaultUnitForCategory = selections['selected_units']
213 #Make sure that the 'self._selectedCategory' has been stored.
214 if 'selected_category' in selections:
215 #Match an available category to the previously selected category.
216 for counter in range(len(unit_data.UNIT_CATEGORIES)):
217 if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
218 # Restore the previously selected category.
219 self._categoryView.set_cursor(counter, self._categoryColumn, False)
220 self._categoryView.grab_focus()
221 historical_catergory_found = True
223 if not historical_catergory_found:
224 print "Couldn't find saved category, using default."
225 #If historical records were not kept then default to
226 # put the focus on the first category
227 self._categoryView.set_cursor(0, self._categoryColumn, False)
228 self._categoryView.grab_focus()
230 self._select_default_unit()
232 def _save_settings(self):
234 This routine saves the selections to a file, and
235 should therefore only be called when exiting the program.
237 Update selections dictionary which consists of the following keys:
238 'self._selectedCategory': full name of selected category
239 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
240 [categoryname: #1 displayed unit, #2 displayed unit]
242 #Determine the contents of the selected category row
243 selected, iter = self._categoryView.get_selection().get_selected()
244 self._selectedCategory = self._categoryModel.get_value(iter, 0)
247 'selected_category': self._selectedCategory,
248 'selected_units': self._defaultUnitForCategory
250 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
251 pickle.dump(selections, open(selectionsDatPath, 'w'))
253 #Get last size of app and save it
255 'size': self._mainWindow.get_size()
257 windowDatPath = "/".join((constants._data_path_, "window.dat"))
258 pickle.dump(window_settings, open(windowDatPath, 'w'))
260 def _clear_find(self):
261 # switch to "new find" state
262 self._find_result = []
265 # Clear our user message
266 self._findLabel.set_text('')
268 def _find_first(self):
269 assert len(self._find_result) == 0
270 assert self._findIndex == 0
271 findString = string.lower(string.strip(self._findEntry.get_text()))
275 # Gather info on all the matching units from all categories
276 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
277 units = unit_data.get_units(category)
278 for unitIndex, unit in enumerate(units):
279 loweredUnit = unit.lower()
280 if loweredUnit in findString or findString in loweredUnit:
281 self._find_result.append((category, unit, catIndex, unitIndex))
283 def _update_find_selection(self):
284 assert 0 < len(self._find_result)
286 #check if next find is in a new category (prevent category changes when unnecessary
287 if self._selectedCategory != self._find_result[self._findIndex][0]:
288 self._categoryView.set_cursor(
289 self._find_result[self._findIndex][2], self._categoryColumn, False
292 self._unitsView.set_cursor(
293 self._find_result[self._findIndex][3], self._unitNameColumn, True
296 def _find_next(self):
298 check if 'new find' or 'last find' or 'next-find'
300 new-find = run the find algorithm which also selects the first found unit
301 = self._findIndex = 0 and self._find_result = []
303 last-find = restart from top again
304 = self._findIndex = len(self._find_result)
306 next-find = continue to next found location
307 = self._findIndex = 0 and len(self._find_result)>0
309 if len(self._find_result) == 0:
312 if self._findIndex == len(self._find_result)-1:
317 if not self._find_result:
318 self._findLabel.set_text('Text not found')
320 self._update_find_selection()
321 resultsLeft = len(self._find_result) - self._findIndex - 1
322 self._findLabel.set_text(
323 '%s result(s) left' % (resultsLeft, )
326 def _find_previous(self):
328 check if 'new find' or 'last find' or 'next-find'
330 new-find = run the find algorithm which also selects the first found unit
331 = self._findIndex = 0 and self._find_result = []
333 last-find = restart from top again
334 = self._findIndex = len(self._find_result)
336 next-find = continue to next found location
337 = self._findIndex = 0 and len(self._find_result)>0
339 if len(self._find_result) == 0:
342 if self._findIndex == 0:
343 self._findIndex = len(self._find_result)-1
347 if not self._find_result:
348 self._findLabel.set_text('Text not found')
350 self._update_find_selection()
351 resultsLeft = len(self._find_result) - self._findIndex - 1
352 self._findLabel.set_text(
353 '%s result(s) left' % (resultsLeft, )
356 def _toggle_find(self):
357 if self._searchLayout.get_property("visible"):
358 self._searchLayout.hide()
360 self._searchLayout.show()
362 def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
363 leftUnitText = self._unitModel.get_value(leftItr, 0)
364 rightUnitText = self._unitModel.get_value(rightItr, 0)
365 return cmp(leftUnitText, rightUnitText)
367 def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
368 leftSymbolText = self._unitModel.get_value(leftItr, 2)
369 rightSymbolText = self._unitModel.get_value(rightItr, 2)
370 return cmp(leftSymbolText, rightSymbolText)
372 def _value_model_cmp(self, sortedModel, leftItr, rightItr):
373 #special sorting exceptions for ascii values (instead of float values)
374 if self._selectedCategory == "Computer Numbers":
375 leftValue = self._unitModel.get_value(leftItr, 1)
376 rightValue = self._unitModel.get_value(rightItr, 1)
378 leftValueText = self._unitModel.get_value(leftItr, 1)
379 leftValue = float(leftValueText) if leftValueText else 0.0
381 rightValueText = self._unitModel.get_value(rightItr, 1)
382 rightValue = float(rightValueText) if rightValueText else 0.0
383 return cmp(leftValue, rightValue)
385 def _get_column_sort_stuff(self):
387 (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
388 (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
389 (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
393 def _switch_category(self, category):
394 self._selectedCategory = category
395 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategory]
397 #Fill up the units descriptions and clear the value cells
398 self._clear_visible_unit_data()
399 for key in unit_data.get_units(self._selectedCategory):
400 iter = self._unitModel.append()
401 self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
402 self._sortedUnitModel.sort_column_changed()
404 self._select_default_unit()
406 def _clear_visible_unit_data(self):
407 self._unitDescription.get_buffer().set_text("")
408 self._unitName.set_text('')
409 self._unitValue.set_text('')
410 self._unitSymbol.set_text('')
412 self._previousUnitName.set_text('')
413 self._previousUnitValue.set_text('')
414 self._previousUnitSymbol.set_text('')
416 self._unitModel.clear()
418 def _select_default_unit(self):
419 # Restore the previous historical settings of previously selected units
420 # in this newly selected category
421 if self._selectedCategory in self._defaultUnitForCategory:
422 units = unit_data.get_units(self._selectedCategory)
424 #Restore oldest selection first.
425 if self._defaultUnitForCategory[self._selectedCategory][1]:
426 unitIndex = units.index(self._defaultUnitForCategory[self._selectedCategory][1])
427 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
429 #Restore newest selection second.
430 if self._defaultUnitForCategory[self._selectedCategory][0]:
431 unitIndex = units.index(self._defaultUnitForCategory[self._selectedCategory][0])
432 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
434 # select the text so user can start typing right away
435 self._unitValue.grab_focus()
436 self._unitValue.select_region(0, -1)
438 def _sanitize_value(self, userEntry):
439 if self._selectedCategory == "Computer Numbers":
448 value = float(userEntry)
451 def _on_shortlist_changed(self, *args):
453 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
455 _moduleLogger.exception("")
457 def _on_edit_shortlist(self, *args):
459 raise NotImplementedError("%s" % self._toggleShortList.get_active())
461 _moduleLogger.exception("")
463 def _on_user_clear_selections(self, *args):
465 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
466 os.remove(selectionsDatPath)
467 self._defaultUnitForCategory = {}
469 _moduleLogger.exception("")
471 def _on_key_press(self, widget, event, *args):
473 @note Hildon specific
475 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
478 event.keyval == gtk.keysyms.F6 or
479 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
481 if self._isFullScreen:
482 self._mainWindow.unfullscreen()
484 self._mainWindow.fullscreen()
485 elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
487 elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
488 self._find_previous()
489 elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
492 _moduleLogger.exception("")
494 def _on_window_state_change(self, widget, event, *args):
496 @note Hildon specific
499 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
500 self._isFullScreen = True
502 self._isFullScreen = False
504 _moduleLogger.exception("")
506 def _on_findEntry_changed(self, *args):
508 Clear out find results since the user wants to look for something new
513 _moduleLogger.exception("")
515 def _on_find_activate(self, *args):
518 self._findButton.grab_focus()
520 _moduleLogger.exception("")
522 def _on_click_unit_column(self, col):
524 Sort the contents of the col when the user clicks on the title.
527 #Determine which column requires sorting
528 columns = self._get_column_sort_stuff()
529 for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
531 direction = getattr(self, directionName)
532 gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
535 self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
537 # set the visual for sorting
538 col.set_sort_indicator(True)
539 col.set_sort_order(not direction)
541 setattr(self, directionName, not direction)
544 maybeCol.set_sort_indicator(False)
546 assert False, "Unknown column: %s" % (col.get_title(), )
548 _moduleLogger.exception("")
550 def _on_click_category(self, *args):
552 selected, iter = self._categoryView.get_selection().get_selected()
553 selectedCategory = self._categoryModel.get_value(iter, 0)
554 self._switch_category(selectedCategory)
556 _moduleLogger.exception("")
558 def _on_click_unit(self, *args):
560 selected, iter = self._unitsView.get_selection().get_selected()
561 selected_unit = selected.get_value(iter, 0)
562 unit_spec = self._unitDataInCategory[selected_unit]
564 if self._unitName.get_text() != selected_unit:
565 self._previousUnitName.set_text(self._unitName.get_text())
566 self._previousUnitValue.set_text(self._unitValue.get_text())
567 self._previousUnitSymbol.set_text(self._unitSymbol.get())
569 self._unitName.set_text(selected_unit)
570 self._unitValue.set_text(selected.get_value(iter, 1))
571 buffer = self._unitDescription.get_buffer()
572 buffer.set_text(unit_spec[2])
573 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
575 if self._unitValue.get_text() == '':
576 if self._selectedCategory == "Computer Numbers":
577 self._unitValue.set_text("0")
579 self._unitValue.set_text("0.0")
581 self._defaultUnitForCategory[self._selectedCategory] = [
582 self._unitName.get_text(), self._previousUnitName.get_text()
585 # select the text so user can start typing right away
586 self._unitValue.grab_focus()
587 self._unitValue.select_region(0, -1)
589 _moduleLogger.exception("")
591 def _on_unit_value_changed(self, *args):
592 if self._unitName.get_text() == '':
594 if not self._unitValue.is_focus():
597 value = self._sanitize_value(self._unitValue.get_text())
599 #retrieve the conversion function and value from the selected unit
600 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
601 base = func.to_base(value, arg)
603 #point to the first row
604 for row in self._unitModel:
605 func, arg = self._unitDataInCategory[row[0]][0]
606 row[1] = str(func.from_base(base, arg))
608 # if the second row has a unit then update its value
609 if self._previousUnitName.get_text() != '':
610 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
611 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
613 def _on_previous_unit_value_changed(self, *args):
614 if self._previousUnitName.get_text() == '':
616 if not self._previousUnitValue.is_focus():
619 value = self._sanitize_value(self._previousUnitValue.get_text())
621 #retrieve the conversion function and value from the selected unit
622 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
623 base = func.to_base(value, arg)
625 #point to the first row
626 for row in self._unitModel:
627 func, arg = self._unitDataInCategory[row[0]][0]
628 row[1] = str(func.from_base(base, arg))
630 # if the second row has a unit then update its value
631 if self._unitName.get_text() != '':
632 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
633 self._unitValue.set_text(str(func.from_base(base, arg, )))
635 def messagebox_ok_clicked(self, a):
638 def _on_user_write_units(self, a):
639 ''"Write the list of categories and units to stdout for documentation purposes.''"
640 messagebox_model = gtk.TextBuffer(None)
641 messageboxtext.set_buffer(messagebox_model)
642 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)
644 while gtk.events_pending():
645 gtk.mainiteration(False)
649 print 'gonvert-%s%s' % (
650 constants.__version__,
651 _(u' - Unit Conversion Utility - Convertible units listing: ')
653 for category_key in unit_data.UNIT_CATEGORIES:
654 total_categories = total_categories + 1
655 print category_key, ": "
656 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[category_key]
657 unit_keys = unit_data.get_units_from_category(self._unitDataInCategory)
658 for unit_key in unit_keys:
659 total_units = total_units + 1
661 print total_categories, ' categories'
662 print total_units, ' units'
664 def _on_about_clicked(self, a):
665 dlg = gtk.AboutDialog()
666 dlg.set_name(constants.__pretty_app_name__)
667 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
668 dlg.set_copyright("Copyright 2009 - GPL")
670 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
671 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
675 def _on_user_exit(self, *args):
677 self._save_settings()
679 _moduleLogger.exception("")
685 logging.basicConfig(level = logging.DEBUG)
687 os.makedirs(constants._data_path_)
696 if __name__ == "__main__":