19 _moduleLogger = logging.getLogger("gonvert_glade")
20 PROFILE_STARTUP = False
21 FORCE_HILDON_LIKE = True
23 gettext.bindtextdomain('gonvert', '/usr/share/locale')
24 gettext.textdomain('gonvert')
28 def change_menu_label(widgets, labelname, newtext):
29 item_label = widgets.get_widget(labelname).get_children()[0]
30 item_label.set_text(newtext)
33 class Gonvert(object):
36 os.path.join(os.path.dirname(__file__), "gonvert.glade"),
37 os.path.join(os.path.dirname(__file__), "../data/gonvert.glade"),
38 os.path.join(os.path.dirname(__file__), "../lib/gonvert.glade"),
39 '/usr/lib/gonvert/gonvert.glade',
43 self._unitDataInCategory = None
44 self._unit_sort_direction = False
45 self._value_sort_direction = False
46 self._units_sort_direction = False
47 self._isFullScreen = False
49 self._find_result = [] # empty find result list
50 self._findIndex = 0 # default to find result number zero
52 self._selectedCategoryName = '' # preset to no selected category
53 self._defaultUnitForCategory = {} # empty dictionary for later use
55 #check to see if glade file is in current directory (user must be
56 # running from download untar directory)
57 for gladePath in self._glade_files:
58 if os.path.isfile(gladePath):
59 homepath = os.path.dirname(gladePath)
60 pixmapspath = "/".join((homepath, "pixmaps"))
61 widgets = gtk.glade.XML(gladePath)
64 _moduleLogger.error("UI Descriptor not found!")
68 self._mainWindow = widgets.get_widget('mainWindow')
69 self._app = hildonize.get_app_class()()
70 self._mainWindow = hildonize.hildonize_window(self._app, self._mainWindow)
72 change_menu_label(widgets, 'fileMenuItem', _('File'))
73 change_menu_label(widgets, 'exitMenuItem', _('Exit'))
74 change_menu_label(widgets, 'toolsMenuItem', _('Tools'))
75 change_menu_label(widgets, 'clearSelectionMenuItem', _('Clear selections'))
76 change_menu_label(widgets, 'helpMenuItem', _('Help'))
77 change_menu_label(widgets, 'aboutMenuItem', _('About'))
78 change_menu_label(widgets, 'findButton', _('Find'))
80 self._shortlistcheck = widgets.get_widget('shortlistcheck')
81 self._toggleShortList = widgets.get_widget('toggleShortList')
83 self._categoryView = widgets.get_widget('categoryView')
85 self._unitsView = widgets.get_widget('unitsView')
86 self._unitsView.set_property('rules_hint', 1)
87 self._unitsView_selection = self._unitsView.get_selection()
88 if hildonize.IS_HILDON_SUPPORTED or FORCE_HILDON_LIKE:
89 self._unitsView.set_headers_visible(False)
91 self._unitName = widgets.get_widget('unitName')
92 self._unitValue = widgets.get_widget('unitValue')
93 self._previousUnitName = widgets.get_widget('previousUnitName')
94 self._previousUnitValue = widgets.get_widget('previousUnitValue')
95 if hildonize.IS_HILDON_SUPPORTED or FORCE_HILDON_LIKE:
96 self._previousUnitName.get_parent().hide()
98 self._unitSymbol = widgets.get_widget('unitSymbol')
99 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
101 self._unitDescription = widgets.get_widget('unitDescription')
102 if hildonize.IS_HILDON_SUPPORTED or FORCE_HILDON_LIKE:
103 self._unitDescription.get_parent().get_parent().hide()
105 self._searchLayout = widgets.get_widget('searchLayout')
106 self._searchLayout.hide()
107 self._findEntry = widgets.get_widget('findEntry')
108 self._findLabel = widgets.get_widget('findLabel')
109 self._findButton = widgets.get_widget('findButton')
110 ToolTips = gtk.Tooltips()
111 ToolTips.set_tip(self._findButton, _(u'Find unit (F6)'))
113 #insert a self._categoryColumnumn into the units list even though the heading will not be seen
114 renderer = gtk.CellRendererText()
115 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
116 self._unitNameColumn.set_property('resizable', 1)
117 self._unitNameColumn.add_attribute(renderer, 'text', 0)
118 self._unitNameColumn.set_clickable(True)
119 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
120 self._unitsView.append_column(self._unitNameColumn)
122 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
123 self._unitValueColumn.set_property('resizable', 1)
124 self._unitValueColumn.add_attribute(renderer, 'text', 1)
125 self._unitValueColumn.set_clickable(True)
126 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
127 self._unitsView.append_column(self._unitValueColumn)
129 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
130 self._unitSymbolColumn.set_property('resizable', 1)
131 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
132 self._unitSymbolColumn.set_clickable(True)
133 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
134 self._unitsView.append_column(self._unitSymbolColumn)
136 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
137 self._sortedUnitModel = gtk.TreeModelSort(self._unitModel)
138 columns = self._get_column_sort_stuff()
139 for columnIndex, (column, sortDirection, col_cmp) in enumerate(columns):
140 self._sortedUnitModel.set_sort_func(columnIndex, col_cmp)
141 self._unitsView.set_model(self._sortedUnitModel)
143 #Insert a column into the category list even though the heading will not be seen
144 renderer = gtk.CellRendererText()
145 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
146 self._categoryColumn.set_property('resizable', 1)
147 self._categoryColumn.add_attribute(renderer, 'text', 0)
148 self._categoryView.append_column(self._categoryColumn)
150 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
151 self._categoryView.set_model(self._categoryModel)
152 #colourize each row differently for easier reading
153 self._categoryView.set_property('rules_hint', 1)
155 #Populate the catagories list
156 for key in unit_data.UNIT_CATEGORIES:
157 iter = self._categoryModel.append()
158 self._categoryModel.set(iter, 0, key)
160 #--------- connections to GUI ----------------
162 "on_exit_menu_activate": self._on_user_exit,
163 "on_main_window_destroy": self._on_user_exit,
164 "on_categoryView_select_row": self._on_click_category,
165 "on_unitValue_changed": self._on_unit_value_changed,
166 "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
167 "on_findButton_clicked": self._on_find_activate,
168 "on_findEntry_activated": self._on_find_activate,
169 "on_findEntry_changed": self._on_findEntry_changed,
170 "on_aboutMenuItem_activate": self._on_about_clicked,
171 "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
172 "on_unitsView_cursor_changed": self._on_click_unit,
173 "on_shortlistcheck_toggled": self._on_shortlist_changed,
174 "on_toggleShortList_activate": self._on_edit_shortlist,
176 widgets.signal_autoconnect(dic)
177 self._mainWindow.connect("key-press-event", self._on_key_press)
178 self._mainWindow.connect("window-state-event", self._on_window_state_change)
180 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
181 iconPath = pixmapspath + '/gonvert.png'
182 if os.path.exists(iconPath):
183 self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
185 _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
187 self._load_settings()
189 def _load_settings(self):
190 #Restore window size from previously saved settings if it exists and is valid.
191 windowDatPath = "/".join((constants._data_path_, "window.dat"))
192 if os.path.exists(windowDatPath):
193 #Retrieving previous window settings from ~/.gonvert/window.dat
194 saved_window = pickle.load(open(windowDatPath, "r"))
195 #If the 'size' has been stored, then extract size from saved_window.
196 if 'size' in saved_window:
197 a, b = saved_window['size']
198 self._mainWindow.resize(a, b)
200 #Restore selections from previously saved settings if it exists and is valid.
201 historical_catergory_found = False
202 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
203 if os.path.exists(selectionsDatPath):
204 #Retrieving previous selections from ~/.gonvert/selections.dat
205 selections = pickle.load(open(selectionsDatPath, 'r'))
206 #Restoring previous selections.
207 #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
208 if 'selected_units' in selections:
209 self._defaultUnitForCategory = selections['selected_units']
210 #Make sure that the 'self._selectedCategoryName' has been stored.
211 if 'selected_category' in selections:
212 #Match an available category to the previously selected category.
213 for counter in range(len(unit_data.UNIT_CATEGORIES)):
214 if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
215 # Restore the previously selected category.
216 self._categoryView.set_cursor(counter, self._categoryColumn, False)
217 self._categoryView.grab_focus()
218 historical_catergory_found = True
220 if not historical_catergory_found:
221 print "Couldn't find saved category, using default."
222 #If historical records were not kept then default to
223 # put the focus on the first category
224 self._categoryView.set_cursor(0, self._categoryColumn, False)
225 self._categoryView.grab_focus()
227 self._select_default_unit()
229 def _save_settings(self):
231 This routine saves the selections to a file, and
232 should therefore only be called when exiting the program.
234 Update selections dictionary which consists of the following keys:
235 'self._selectedCategoryName': full name of selected category
236 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
237 [categoryname: #1 displayed unit, #2 displayed unit]
239 #Determine the contents of the selected category row
240 selected, iter = self._categoryView.get_selection().get_selected()
241 self._selectedCategoryName = self._categoryModel.get_value(iter, 0)
244 'selected_category': self._selectedCategoryName,
245 'selected_units': self._defaultUnitForCategory
247 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
248 pickle.dump(selections, open(selectionsDatPath, 'w'))
250 #Get last size of app and save it
252 'size': self._mainWindow.get_size()
254 windowDatPath = "/".join((constants._data_path_, "window.dat"))
255 pickle.dump(window_settings, open(windowDatPath, 'w'))
257 def _clear_find(self):
258 # switch to "new find" state
259 self._find_result = []
262 # Clear our user message
263 self._findLabel.set_text('')
265 def _find_first(self):
266 assert len(self._find_result) == 0
267 assert self._findIndex == 0
268 findString = self._findEntry.get_text().strip().lower()
272 # Gather info on all the matching units from all categories
273 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
274 units = unit_data.get_units(category)
275 for unitIndex, unit in enumerate(units):
276 loweredUnit = unit.lower()
277 if loweredUnit in findString or findString in loweredUnit:
278 self._find_result.append((category, unit, catIndex, unitIndex))
280 def _update_find_selection(self):
281 assert 0 < len(self._find_result)
283 #check if next find is in a new category (prevent category changes when unnecessary
284 if self._selectedCategoryName != self._find_result[self._findIndex][0]:
285 self._categoryView.set_cursor(
286 self._find_result[self._findIndex][2], self._categoryColumn, False
289 self._unitsView.set_cursor(
290 self._find_result[self._findIndex][3], self._unitNameColumn, True
293 def _find_next(self):
294 if len(self._find_result) == 0:
297 if self._findIndex == len(self._find_result)-1:
302 if not self._find_result:
303 self._findLabel.set_text('Text not found')
305 self._update_find_selection()
306 resultsLeft = len(self._find_result) - self._findIndex - 1
307 self._findLabel.set_text(
308 '%s result(s) left' % (resultsLeft, )
311 def _find_previous(self):
312 if len(self._find_result) == 0:
315 if self._findIndex == 0:
316 self._findIndex = len(self._find_result)-1
320 if not self._find_result:
321 self._findLabel.set_text('Text not found')
323 self._update_find_selection()
324 resultsLeft = len(self._find_result) - self._findIndex - 1
325 self._findLabel.set_text(
326 '%s result(s) left' % (resultsLeft, )
329 def _toggle_find(self):
330 if self._searchLayout.get_property("visible"):
331 self._searchLayout.hide()
333 self._searchLayout.show()
335 def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
336 leftUnitText = self._unitModel.get_value(leftItr, 0)
337 rightUnitText = self._unitModel.get_value(rightItr, 0)
338 return cmp(leftUnitText, rightUnitText)
340 def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
341 leftSymbolText = self._unitModel.get_value(leftItr, 2)
342 rightSymbolText = self._unitModel.get_value(rightItr, 2)
343 return cmp(leftSymbolText, rightSymbolText)
345 def _value_model_cmp(self, sortedModel, leftItr, rightItr):
346 #special sorting exceptions for ascii values (instead of float values)
347 if self._selectedCategoryName == "Computer Numbers":
348 leftValue = self._unitModel.get_value(leftItr, 1)
349 rightValue = self._unitModel.get_value(rightItr, 1)
351 leftValueText = self._unitModel.get_value(leftItr, 1)
352 leftValue = float(leftValueText) if leftValueText else 0.0
354 rightValueText = self._unitModel.get_value(rightItr, 1)
355 rightValue = float(rightValueText) if rightValueText else 0.0
356 return cmp(leftValue, rightValue)
358 def _get_column_sort_stuff(self):
360 (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
361 (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
362 (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
366 def _switch_category(self, category):
367 self._selectedCategoryName = category
368 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategoryName]
370 #Fill up the units descriptions and clear the value cells
371 self._clear_visible_unit_data()
372 for key in unit_data.get_units(self._selectedCategoryName):
373 iter = self._unitModel.append()
374 self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
375 self._sortedUnitModel.sort_column_changed()
377 self._select_default_unit()
379 def _clear_visible_unit_data(self):
380 self._unitDescription.get_buffer().set_text("")
381 self._unitName.set_text('')
382 self._unitValue.set_text('')
383 self._unitSymbol.set_text('')
385 self._previousUnitName.set_text('')
386 self._previousUnitValue.set_text('')
387 self._previousUnitSymbol.set_text('')
389 self._unitModel.clear()
391 def _select_default_unit(self):
392 # Restore the previous historical settings of previously selected units
393 # in this newly selected category
394 defaultPrimary = unit_data.get_base_unit(self._selectedCategoryName)
395 defaultSecondary = ""
396 if self._selectedCategoryName in self._defaultUnitForCategory:
397 if self._defaultUnitForCategory[self._selectedCategoryName][0]:
398 defaultPrimary = self._defaultUnitForCategory[self._selectedCategoryName][0]
399 if self._defaultUnitForCategory[self._selectedCategoryName][1]:
400 defaultSecondary = self._defaultUnitForCategory[self._selectedCategoryName][1]
402 units = unit_data.get_units(self._selectedCategoryName)
404 #Restore oldest selection first.
406 unitIndex = units.index(defaultPrimary)
407 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
409 #Restore newest selection second.
411 unitIndex = units.index(defaultSecondary)
412 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
414 # select the text so user can start typing right away
415 self._unitValue.grab_focus()
416 self._unitValue.select_region(0, -1)
418 def _sanitize_value(self, userEntry):
419 if self._selectedCategoryName == "Computer Numbers":
428 value = float(userEntry)
431 def _on_shortlist_changed(self, *args):
433 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
435 _moduleLogger.exception("")
437 def _on_edit_shortlist(self, *args):
439 raise NotImplementedError("%s" % self._toggleShortList.get_active())
441 _moduleLogger.exception("")
443 def _on_user_clear_selections(self, *args):
445 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
446 os.remove(selectionsDatPath)
447 self._defaultUnitForCategory = {}
449 _moduleLogger.exception("")
451 def _on_key_press(self, widget, event, *args):
453 @note Hildon specific
455 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
458 event.keyval == gtk.keysyms.F6 or
459 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
461 if self._isFullScreen:
462 self._mainWindow.unfullscreen()
464 self._mainWindow.fullscreen()
465 elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
467 elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
468 self._find_previous()
469 elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
472 _moduleLogger.exception("")
474 def _on_window_state_change(self, widget, event, *args):
476 @note Hildon specific
479 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
480 self._isFullScreen = True
482 self._isFullScreen = False
484 _moduleLogger.exception("")
486 def _on_findEntry_changed(self, *args):
488 Clear out find results since the user wants to look for something new
493 _moduleLogger.exception("")
495 def _on_find_activate(self, *args):
498 self._findButton.grab_focus()
500 _moduleLogger.exception("")
502 def _on_click_unit_column(self, col):
504 Sort the contents of the col when the user clicks on the title.
507 #Determine which column requires sorting
508 columns = self._get_column_sort_stuff()
509 for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
511 direction = getattr(self, directionName)
512 gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
515 self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
517 # set the visual for sorting
518 col.set_sort_indicator(True)
519 col.set_sort_order(not direction)
521 setattr(self, directionName, not direction)
524 maybeCol.set_sort_indicator(False)
526 assert False, "Unknown column: %s" % (col.get_title(), )
528 _moduleLogger.exception("")
530 def _on_click_category(self, *args):
532 selected, iter = self._categoryView.get_selection().get_selected()
534 # User is typing in an invalid string, not selecting any category
536 selectedCategory = self._categoryModel.get_value(iter, 0)
537 self._switch_category(selectedCategory)
539 _moduleLogger.exception("")
541 def _on_click_unit(self, *args):
543 selected, iter = self._unitsView.get_selection().get_selected()
544 selected_unit = selected.get_value(iter, 0)
545 unit_spec = self._unitDataInCategory[selected_unit]
547 if self._unitName.get_text() != selected_unit:
548 self._previousUnitName.set_text(self._unitName.get_text())
549 self._previousUnitValue.set_text(self._unitValue.get_text())
550 self._previousUnitSymbol.set_text(self._unitSymbol.get())
552 self._unitName.set_text(selected_unit)
553 self._unitValue.set_text(selected.get_value(iter, 1))
554 buffer = self._unitDescription.get_buffer()
555 buffer.set_text(unit_spec[2])
556 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
558 self._unitSymbol.show()
560 self._unitSymbol.hide()
562 if self._unitValue.get_text() == '':
563 if self._selectedCategoryName == "Computer Numbers":
564 self._unitValue.set_text("0")
566 self._unitValue.set_text("0.0")
568 self._defaultUnitForCategory[self._selectedCategoryName] = [
569 self._unitName.get_text(), self._previousUnitName.get_text()
572 # select the text so user can start typing right away
573 self._unitValue.grab_focus()
574 self._unitValue.select_region(0, -1)
576 _moduleLogger.exception("")
578 def _on_unit_value_changed(self, *args):
580 if self._unitName.get_text() == '':
582 if not self._unitValue.is_focus():
585 #retrieve the conversion function and value from the selected unit
586 value = self._sanitize_value(self._unitValue.get_text())
587 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
588 base = func.to_base(value, arg)
590 #point to the first row
591 for row in self._unitModel:
592 func, arg = self._unitDataInCategory[row[0]][0]
593 row[1] = str(func.from_base(base, arg))
595 # Update the secondary unit entry
596 if self._previousUnitName.get_text() != '':
597 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
598 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
600 _moduleLogger.exception("")
602 def _on_previous_unit_value_changed(self, *args):
604 if self._previousUnitName.get_text() == '':
606 if not self._previousUnitValue.is_focus():
609 #retrieve the conversion function and value from the selected unit
610 value = self._sanitize_value(self._previousUnitValue.get_text())
611 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
612 base = func.to_base(value, arg)
614 #point to the first row
615 for row in self._unitModel:
616 func, arg = self._unitDataInCategory[row[0]][0]
617 row[1] = str(func.from_base(base, arg))
619 # Update the primary unit entry
620 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
621 self._unitValue.set_text(str(func.from_base(base, arg, )))
623 _moduleLogger.exception("")
625 def _on_about_clicked(self, a):
626 dlg = gtk.AboutDialog()
627 dlg.set_name(constants.__pretty_app_name__)
628 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
629 dlg.set_copyright("Copyright 2009 - GPL")
631 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
632 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
636 def _on_user_exit(self, *args):
638 self._save_settings()
640 _moduleLogger.exception("")
646 logging.basicConfig(level = logging.DEBUG)
648 os.makedirs(constants._data_path_)
654 if not PROFILE_STARTUP:
658 if __name__ == "__main__":