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 hildonize.set_cell_thumb_selectable(renderer)
116 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
117 self._unitNameColumn.set_property('resizable', 1)
118 self._unitNameColumn.add_attribute(renderer, 'text', 0)
119 self._unitNameColumn.set_clickable(True)
120 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
121 self._unitsView.append_column(self._unitNameColumn)
123 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
124 self._unitValueColumn.set_property('resizable', 1)
125 self._unitValueColumn.add_attribute(renderer, 'text', 1)
126 self._unitValueColumn.set_clickable(True)
127 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
128 self._unitsView.append_column(self._unitValueColumn)
130 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
131 self._unitSymbolColumn.set_property('resizable', 1)
132 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
133 self._unitSymbolColumn.set_clickable(True)
134 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
135 self._unitsView.append_column(self._unitSymbolColumn)
137 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
138 self._sortedUnitModel = gtk.TreeModelSort(self._unitModel)
139 columns = self._get_column_sort_stuff()
140 for columnIndex, (column, sortDirection, col_cmp) in enumerate(columns):
141 self._sortedUnitModel.set_sort_func(columnIndex, col_cmp)
142 self._unitsView.set_model(self._sortedUnitModel)
144 #Insert a column into the category list even though the heading will not be seen
145 renderer = gtk.CellRendererText()
146 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
147 self._categoryColumn.set_property('resizable', 1)
148 self._categoryColumn.add_attribute(renderer, 'text', 0)
149 self._categoryView.append_column(self._categoryColumn)
151 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
152 self._categoryView.set_model(self._categoryModel)
153 #colourize each row differently for easier reading
154 self._categoryView.set_property('rules_hint', 1)
156 #Populate the catagories list
157 for key in unit_data.UNIT_CATEGORIES:
159 self._categoryModel.append(row)
161 #--------- connections to GUI ----------------
163 "on_exit_menu_activate": self._on_user_exit,
164 "on_main_window_destroy": self._on_user_exit,
165 "on_categoryView_select_row": self._on_click_category,
166 "on_unitValue_changed": self._on_unit_value_changed,
167 "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
168 "on_findButton_clicked": self._on_find_activate,
169 "on_findEntry_activated": self._on_find_activate,
170 "on_findEntry_changed": self._on_findEntry_changed,
171 "on_aboutMenuItem_activate": self._on_about_clicked,
172 "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
173 "on_unitsView_cursor_changed": self._on_click_unit,
174 "on_shortlistcheck_toggled": self._on_shortlist_changed,
175 "on_toggleShortList_activate": self._on_edit_shortlist,
177 widgets.signal_autoconnect(dic)
178 self._mainWindow.connect("key-press-event", self._on_key_press)
179 self._mainWindow.connect("window-state-event", self._on_window_state_change)
181 replacementButtons = []
182 menu = hildonize.hildonize_menu(
184 widgets.get_widget("mainMenuBar"),
187 if not hildonize.IS_HILDON_SUPPORTED:
188 _moduleLogger.warning("No hildonization support")
190 hildonize.set_application_title(
191 self._mainWindow, "%s - Unit Conversion Utility" % constants.__pretty_app_name__
193 iconPath = pixmapspath + '/gonvert.png'
194 if os.path.exists(iconPath):
195 self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
197 _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
199 self._load_settings()
201 def _load_settings(self):
202 #Restore window size from previously saved settings if it exists and is valid.
203 windowDatPath = "/".join((constants._data_path_, "window.dat"))
204 if os.path.exists(windowDatPath):
205 #Retrieving previous window settings from ~/.gonvert/window.dat
206 saved_window = pickle.load(open(windowDatPath, "r"))
207 #If the 'size' has been stored, then extract size from saved_window.
208 if 'size' in saved_window:
209 a, b = saved_window['size']
210 self._mainWindow.resize(a, b)
212 #Restore selections from previously saved settings if it exists and is valid.
213 historical_catergory_found = False
214 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
215 if os.path.exists(selectionsDatPath):
216 #Retrieving previous selections from ~/.gonvert/selections.dat
217 selections = pickle.load(open(selectionsDatPath, 'r'))
218 #Restoring previous selections.
219 #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
220 if 'selected_units' in selections:
221 self._defaultUnitForCategory = selections['selected_units']
222 #Make sure that the 'self._selectedCategoryName' has been stored.
223 if 'selected_category' in selections:
224 #Match an available category to the previously selected category.
225 for counter in range(len(unit_data.UNIT_CATEGORIES)):
226 if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
227 # Restore the previously selected category.
228 self._categoryView.set_cursor(counter, self._categoryColumn, False)
229 self._categoryView.grab_focus()
230 historical_catergory_found = True
232 if not historical_catergory_found:
233 print "Couldn't find saved category, using default."
234 #If historical records were not kept then default to
235 # put the focus on the first category
236 self._categoryView.set_cursor(0, self._categoryColumn, False)
237 self._categoryView.grab_focus()
239 self._select_default_unit()
241 def _save_settings(self):
243 This routine saves the selections to a file, and
244 should therefore only be called when exiting the program.
246 Update selections dictionary which consists of the following keys:
247 'self._selectedCategoryName': full name of selected category
248 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
249 [categoryname: #1 displayed unit, #2 displayed unit]
251 #Determine the contents of the selected category row
252 selected, iter = self._categoryView.get_selection().get_selected()
253 self._selectedCategoryName = self._categoryModel.get_value(iter, 0)
256 'selected_category': self._selectedCategoryName,
257 'selected_units': self._defaultUnitForCategory
259 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
260 pickle.dump(selections, open(selectionsDatPath, 'w'))
262 #Get last size of app and save it
264 'size': self._mainWindow.get_size()
266 windowDatPath = "/".join((constants._data_path_, "window.dat"))
267 pickle.dump(window_settings, open(windowDatPath, 'w'))
269 def _clear_find(self):
270 # switch to "new find" state
271 self._find_result = []
274 # Clear our user message
275 self._findLabel.set_text('')
277 def _find_first(self):
278 assert len(self._find_result) == 0
279 assert self._findIndex == 0
280 findString = self._findEntry.get_text().strip().lower()
284 # Gather info on all the matching units from all categories
285 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
286 units = unit_data.get_units(category)
287 for unitIndex, unit in enumerate(units):
288 loweredUnit = unit.lower()
289 if loweredUnit in findString or findString in loweredUnit:
290 self._find_result.append((category, unit, catIndex, unitIndex))
292 def _update_find_selection(self):
293 assert 0 < len(self._find_result)
295 #check if next find is in a new category (prevent category changes when unnecessary
296 if self._selectedCategoryName != self._find_result[self._findIndex][0]:
297 self._categoryView.set_cursor(
298 self._find_result[self._findIndex][2], self._categoryColumn, False
301 self._unitsView.set_cursor(
302 self._find_result[self._findIndex][3], self._unitNameColumn, True
305 def _find_next(self):
306 if len(self._find_result) == 0:
309 if self._findIndex == len(self._find_result)-1:
314 if not self._find_result:
315 self._findLabel.set_text('Text not found')
317 self._update_find_selection()
318 resultsLeft = len(self._find_result) - self._findIndex - 1
319 self._findLabel.set_text(
320 '%s result(s) left' % (resultsLeft, )
323 def _find_previous(self):
324 if len(self._find_result) == 0:
327 if self._findIndex == 0:
328 self._findIndex = len(self._find_result)-1
332 if not self._find_result:
333 self._findLabel.set_text('Text not found')
335 self._update_find_selection()
336 resultsLeft = len(self._find_result) - self._findIndex - 1
337 self._findLabel.set_text(
338 '%s result(s) left' % (resultsLeft, )
341 def _toggle_find(self):
342 if self._searchLayout.get_property("visible"):
343 self._searchLayout.hide()
345 self._searchLayout.show()
347 def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
348 leftUnitText = self._unitModel.get_value(leftItr, 0)
349 rightUnitText = self._unitModel.get_value(rightItr, 0)
350 return cmp(leftUnitText, rightUnitText)
352 def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
353 leftSymbolText = self._unitModel.get_value(leftItr, 2)
354 rightSymbolText = self._unitModel.get_value(rightItr, 2)
355 return cmp(leftSymbolText, rightSymbolText)
357 def _value_model_cmp(self, sortedModel, leftItr, rightItr):
358 #special sorting exceptions for ascii values (instead of float values)
359 if self._selectedCategoryName == "Computer Numbers":
360 leftValue = self._unitModel.get_value(leftItr, 1)
361 rightValue = self._unitModel.get_value(rightItr, 1)
363 leftValueText = self._unitModel.get_value(leftItr, 1)
364 leftValue = float(leftValueText) if leftValueText else 0.0
366 rightValueText = self._unitModel.get_value(rightItr, 1)
367 rightValue = float(rightValueText) if rightValueText else 0.0
368 return cmp(leftValue, rightValue)
370 def _get_column_sort_stuff(self):
372 (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
373 (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
374 (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
378 def _switch_category(self, category):
379 self._selectedCategoryName = category
380 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategoryName]
382 #Fill up the units descriptions and clear the value cells
383 self._clear_visible_unit_data()
384 for key in unit_data.get_units(self._selectedCategoryName):
385 iter = self._unitModel.append()
386 self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
387 self._sortedUnitModel.sort_column_changed()
389 self._select_default_unit()
391 def _clear_visible_unit_data(self):
392 self._unitDescription.get_buffer().set_text("")
393 self._unitName.set_text('')
394 self._unitValue.set_text('')
395 self._unitSymbol.set_text('')
397 self._previousUnitName.set_text('')
398 self._previousUnitValue.set_text('')
399 self._previousUnitSymbol.set_text('')
401 self._unitModel.clear()
403 def _select_default_unit(self):
404 # Restore the previous historical settings of previously selected units
405 # in this newly selected category
406 defaultPrimary = unit_data.get_base_unit(self._selectedCategoryName)
407 defaultSecondary = ""
408 if self._selectedCategoryName in self._defaultUnitForCategory:
409 if self._defaultUnitForCategory[self._selectedCategoryName][0]:
410 defaultPrimary = self._defaultUnitForCategory[self._selectedCategoryName][0]
411 if self._defaultUnitForCategory[self._selectedCategoryName][1]:
412 defaultSecondary = self._defaultUnitForCategory[self._selectedCategoryName][1]
414 units = unit_data.get_units(self._selectedCategoryName)
416 #Restore oldest selection first.
418 unitIndex = units.index(defaultPrimary)
419 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
421 #Restore newest selection second.
423 unitIndex = units.index(defaultSecondary)
424 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
426 # select the text so user can start typing right away
427 self._unitValue.grab_focus()
428 self._unitValue.select_region(0, -1)
430 def _sanitize_value(self, userEntry):
431 if self._selectedCategoryName == "Computer Numbers":
440 value = float(userEntry)
443 def _on_shortlist_changed(self, *args):
445 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
447 _moduleLogger.exception("")
449 def _on_edit_shortlist(self, *args):
451 raise NotImplementedError("%s" % self._toggleShortList.get_active())
453 _moduleLogger.exception("")
455 def _on_user_clear_selections(self, *args):
457 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
458 os.remove(selectionsDatPath)
459 self._defaultUnitForCategory = {}
461 _moduleLogger.exception("")
463 def _on_key_press(self, widget, event, *args):
465 @note Hildon specific
467 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
470 event.keyval == gtk.keysyms.F6 or
471 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
473 if self._isFullScreen:
474 self._mainWindow.unfullscreen()
476 self._mainWindow.fullscreen()
477 elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
479 elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
480 self._find_previous()
481 elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
484 _moduleLogger.exception("")
486 def _on_window_state_change(self, widget, event, *args):
488 @note Hildon specific
491 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
492 self._isFullScreen = True
494 self._isFullScreen = False
496 _moduleLogger.exception("")
498 def _on_findEntry_changed(self, *args):
500 Clear out find results since the user wants to look for something new
505 _moduleLogger.exception("")
507 def _on_find_activate(self, *args):
510 self._findButton.grab_focus()
512 _moduleLogger.exception("")
514 def _on_click_unit_column(self, col):
516 Sort the contents of the col when the user clicks on the title.
519 #Determine which column requires sorting
520 columns = self._get_column_sort_stuff()
521 for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
523 direction = getattr(self, directionName)
524 gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
527 self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
529 # set the visual for sorting
530 col.set_sort_indicator(True)
531 col.set_sort_order(not direction)
533 setattr(self, directionName, not direction)
536 maybeCol.set_sort_indicator(False)
538 assert False, "Unknown column: %s" % (col.get_title(), )
540 _moduleLogger.exception("")
542 def _on_click_category(self, *args):
544 selected, iter = self._categoryView.get_selection().get_selected()
546 # User is typing in an invalid string, not selecting any category
548 selectedCategory = self._categoryModel.get_value(iter, 0)
549 self._switch_category(selectedCategory)
551 _moduleLogger.exception("")
553 def _on_click_unit(self, *args):
555 selected, iter = self._unitsView.get_selection().get_selected()
556 selected_unit = selected.get_value(iter, 0)
557 unit_spec = self._unitDataInCategory[selected_unit]
559 if self._unitName.get_text() != selected_unit:
560 self._previousUnitName.set_text(self._unitName.get_text())
561 self._previousUnitValue.set_text(self._unitValue.get_text())
562 self._previousUnitSymbol.set_text(self._unitSymbol.get())
564 self._unitName.set_text(selected_unit)
565 self._unitValue.set_text(selected.get_value(iter, 1))
566 buffer = self._unitDescription.get_buffer()
567 buffer.set_text(unit_spec[2])
568 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
570 self._unitSymbol.show()
572 self._unitSymbol.hide()
574 if self._unitValue.get_text() == '':
575 if self._selectedCategoryName == "Computer Numbers":
576 self._unitValue.set_text("0")
578 self._unitValue.set_text("0.0")
580 self._defaultUnitForCategory[self._selectedCategoryName] = [
581 self._unitName.get_text(), self._previousUnitName.get_text()
584 # select the text so user can start typing right away
585 self._unitValue.grab_focus()
586 self._unitValue.select_region(0, -1)
588 _moduleLogger.exception("")
590 def _on_unit_value_changed(self, *args):
592 if self._unitName.get_text() == '':
594 if not self._unitValue.is_focus():
597 #retrieve the conversion function and value from the selected unit
598 value = self._sanitize_value(self._unitValue.get_text())
599 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
600 base = func.to_base(value, arg)
602 #point to the first row
603 for row in self._unitModel:
604 func, arg = self._unitDataInCategory[row[0]][0]
605 row[1] = str(func.from_base(base, arg))
607 # Update the secondary unit entry
608 if self._previousUnitName.get_text() != '':
609 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
610 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
612 _moduleLogger.exception("")
614 def _on_previous_unit_value_changed(self, *args):
616 if self._previousUnitName.get_text() == '':
618 if not self._previousUnitValue.is_focus():
621 #retrieve the conversion function and value from the selected unit
622 value = self._sanitize_value(self._previousUnitValue.get_text())
623 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
624 base = func.to_base(value, arg)
626 #point to the first row
627 for row in self._unitModel:
628 func, arg = self._unitDataInCategory[row[0]][0]
629 row[1] = str(func.from_base(base, arg))
631 # Update the primary unit entry
632 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
633 self._unitValue.set_text(str(func.from_base(base, arg, )))
635 _moduleLogger.exception("")
637 def _on_about_clicked(self, a):
638 dlg = gtk.AboutDialog()
639 dlg.set_name(constants.__pretty_app_name__)
640 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
641 dlg.set_copyright("Copyright 2009 - GPL")
643 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
644 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
648 def _on_user_exit(self, *args):
650 self._save_settings()
652 _moduleLogger.exception("")
658 logging.basicConfig(level = logging.DEBUG)
660 os.makedirs(constants._data_path_)
666 if not PROFILE_STARTUP:
670 if __name__ == "__main__":