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._categorySelectionButton = widgets.get_widget("categorySelectionButton")
84 self._categoryView = widgets.get_widget('categoryView')
85 if hildonize.IS_HILDON_SUPPORTED or FORCE_HILDON_LIKE:
86 self._categoryView.get_parent().hide()
88 self._categorySelectionButton.hide()
90 self._unitsView = widgets.get_widget('unitsView')
91 self._unitsView.set_property('rules_hint', 1)
92 self._unitsView_selection = self._unitsView.get_selection()
93 if hildonize.IS_HILDON_SUPPORTED or FORCE_HILDON_LIKE:
94 self._unitsView.set_headers_visible(False)
96 self._unitName = widgets.get_widget('unitName')
97 self._unitValue = widgets.get_widget('unitValue')
98 self._previousUnitName = widgets.get_widget('previousUnitName')
99 self._previousUnitValue = widgets.get_widget('previousUnitValue')
100 if hildonize.IS_HILDON_SUPPORTED or FORCE_HILDON_LIKE:
101 self._previousUnitName.get_parent().hide()
103 self._unitSymbol = widgets.get_widget('unitSymbol')
104 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
106 self._unitDescription = widgets.get_widget('unitDescription')
107 if hildonize.IS_HILDON_SUPPORTED or FORCE_HILDON_LIKE:
108 self._unitDescription.get_parent().get_parent().hide()
110 self._searchLayout = widgets.get_widget('searchLayout')
111 self._searchLayout.hide()
112 self._findEntry = widgets.get_widget('findEntry')
113 self._findLabel = widgets.get_widget('findLabel')
114 self._findButton = widgets.get_widget('findButton')
115 ToolTips = gtk.Tooltips()
116 ToolTips.set_tip(self._findButton, _(u'Find unit (F6)'))
118 #insert a self._categoryColumnumn into the units list even though the heading will not be seen
119 renderer = gtk.CellRendererText()
120 hildonize.set_cell_thumb_selectable(renderer)
121 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
122 self._unitNameColumn.set_property('resizable', 1)
123 self._unitNameColumn.add_attribute(renderer, 'text', 0)
124 self._unitNameColumn.set_clickable(True)
125 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
126 self._unitsView.append_column(self._unitNameColumn)
128 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
129 self._unitValueColumn.set_property('resizable', 1)
130 self._unitValueColumn.add_attribute(renderer, 'text', 1)
131 self._unitValueColumn.set_clickable(True)
132 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
133 self._unitsView.append_column(self._unitValueColumn)
135 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
136 self._unitSymbolColumn.set_property('resizable', 1)
137 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
138 self._unitSymbolColumn.set_clickable(True)
139 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
140 self._unitsView.append_column(self._unitSymbolColumn)
142 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
143 self._sortedUnitModel = gtk.TreeModelSort(self._unitModel)
144 columns = self._get_column_sort_stuff()
145 for columnIndex, (column, sortDirection, col_cmp) in enumerate(columns):
146 self._sortedUnitModel.set_sort_func(columnIndex, col_cmp)
147 self._unitsView.set_model(self._sortedUnitModel)
149 #Insert a column into the category list even though the heading will not be seen
150 renderer = gtk.CellRendererText()
151 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
152 self._categoryColumn.set_property('resizable', 1)
153 self._categoryColumn.add_attribute(renderer, 'text', 0)
154 self._categoryView.append_column(self._categoryColumn)
156 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
157 self._categoryView.set_model(self._categoryModel)
158 #colourize each row differently for easier reading
159 self._categoryView.set_property('rules_hint', 1)
161 #Populate the catagories list
162 for key in unit_data.UNIT_CATEGORIES:
164 self._categoryModel.append(row)
166 #--------- connections to GUI ----------------
168 "on_exit_menu_activate": self._on_user_exit,
169 "on_main_window_destroy": self._on_user_exit,
170 "on_categoryView_select_row": self._on_click_category,
171 "on_unitValue_changed": self._on_unit_value_changed,
172 "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
173 "on_findButton_clicked": self._on_find_activate,
174 "on_findEntry_activated": self._on_find_activate,
175 "on_findEntry_changed": self._on_findEntry_changed,
176 "on_aboutMenuItem_activate": self._on_about_clicked,
177 "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
178 "on_unitsView_cursor_changed": self._on_click_unit,
179 "on_shortlistcheck_toggled": self._on_shortlist_changed,
180 "on_toggleShortList_activate": self._on_edit_shortlist,
182 widgets.signal_autoconnect(dic)
183 self._mainWindow.connect("key-press-event", self._on_key_press)
184 self._mainWindow.connect("window-state-event", self._on_window_state_change)
185 self._categorySelectionButton.connect("clicked", self._on_category_selector_clicked)
187 replacementButtons = []
188 menu = hildonize.hildonize_menu(
190 widgets.get_widget("mainMenuBar"),
193 if not hildonize.IS_HILDON_SUPPORTED:
194 _moduleLogger.warning("No hildonization support")
196 hildonize.set_application_title(
197 self._mainWindow, "%s - Unit Conversion Utility" % constants.__pretty_app_name__
199 iconPath = pixmapspath + '/gonvert.png'
200 if os.path.exists(iconPath):
201 self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
203 _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
205 self._load_settings()
207 def _load_settings(self):
208 #Restore window size from previously saved settings if it exists and is valid.
209 windowDatPath = "/".join((constants._data_path_, "window.dat"))
210 if os.path.exists(windowDatPath):
211 #Retrieving previous window settings from ~/.gonvert/window.dat
212 saved_window = pickle.load(open(windowDatPath, "r"))
213 #If the 'size' has been stored, then extract size from saved_window.
214 if 'size' in saved_window:
215 a, b = saved_window['size']
216 self._mainWindow.resize(a, b)
218 #Restore selections from previously saved settings if it exists and is valid.
220 selectedCategoryName = unit_data.UNIT_CATEGORIES[0]
221 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
222 if os.path.exists(selectionsDatPath):
223 #Retrieving previous selections from ~/.gonvert/selections.dat
224 selections = pickle.load(open(selectionsDatPath, 'r'))
225 #Restoring previous selections.
226 #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
227 if 'selected_units' in selections:
228 self._defaultUnitForCategory = selections['selected_units']
229 #Make sure that the 'self._selectedCategoryName' has been stored.
230 if 'selected_category' in selections:
231 #Match an available category to the previously selected category.
232 selectedCategoryName = selections['selected_category']
234 categoryIndex = unit_data.UNIT_CATEGORIES.index(selectedCategoryName)
236 _moduleLogger.warn("Unknown category: %s" % selectedCategoryName)
238 self._categorySelectionButton.set_label(selectedCategoryName)
239 self._categoryView.set_cursor(categoryIndex, self._categoryColumn, False)
240 self._categoryView.grab_focus()
242 self._select_default_unit()
244 def _save_settings(self):
246 This routine saves the selections to a file, and
247 should therefore only be called when exiting the program.
249 Update selections dictionary which consists of the following keys:
250 'self._selectedCategoryName': full name of selected category
251 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
252 [categoryname: #1 displayed unit, #2 displayed unit]
254 #Determine the contents of the selected category row
255 selected, iter = self._categoryView.get_selection().get_selected()
256 self._selectedCategoryName = self._categoryModel.get_value(iter, 0)
259 'selected_category': self._selectedCategoryName,
260 'selected_units': self._defaultUnitForCategory
262 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
263 pickle.dump(selections, open(selectionsDatPath, 'w'))
265 #Get last size of app and save it
267 'size': self._mainWindow.get_size()
269 windowDatPath = "/".join((constants._data_path_, "window.dat"))
270 pickle.dump(window_settings, open(windowDatPath, 'w'))
272 def _clear_find(self):
273 # switch to "new find" state
274 self._find_result = []
277 # Clear our user message
278 self._findLabel.set_text('')
280 def _find_first(self):
281 assert len(self._find_result) == 0
282 assert self._findIndex == 0
283 findString = self._findEntry.get_text().strip().lower()
287 # Gather info on all the matching units from all categories
288 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
289 units = unit_data.get_units(category)
290 for unitIndex, unit in enumerate(units):
291 loweredUnit = unit.lower()
292 if loweredUnit in findString or findString in loweredUnit:
293 self._find_result.append((category, unit, catIndex, unitIndex))
295 def _update_find_selection(self):
296 assert 0 < len(self._find_result)
298 #check if next find is in a new category (prevent category changes when unnecessary
299 searchCategoryName = self._find_result[self._findIndex][0]
300 if self._selectedCategoryName != searchCategoryName:
301 self._categorySelectionButton.set_label(searchCategoryName)
302 self._categoryView.set_cursor(
303 self._find_result[self._findIndex][2], self._categoryColumn, False
306 self._unitsView.set_cursor(
307 self._find_result[self._findIndex][3], self._unitNameColumn, True
310 def _find_next(self):
311 if len(self._find_result) == 0:
314 if self._findIndex == len(self._find_result)-1:
319 if not self._find_result:
320 self._findLabel.set_text('Text not found')
322 self._update_find_selection()
323 resultsLeft = len(self._find_result) - self._findIndex - 1
324 self._findLabel.set_text(
325 '%s result(s) left' % (resultsLeft, )
328 def _find_previous(self):
329 if len(self._find_result) == 0:
332 if self._findIndex == 0:
333 self._findIndex = len(self._find_result)-1
337 if not self._find_result:
338 self._findLabel.set_text('Text not found')
340 self._update_find_selection()
341 resultsLeft = len(self._find_result) - self._findIndex - 1
342 self._findLabel.set_text(
343 '%s result(s) left' % (resultsLeft, )
346 def _toggle_find(self):
347 if self._searchLayout.get_property("visible"):
348 self._searchLayout.hide()
349 self._unitsView.grab_focus()
351 self._searchLayout.show()
352 self._findEntry.grab_focus()
354 def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
355 leftUnitText = self._unitModel.get_value(leftItr, 0)
356 rightUnitText = self._unitModel.get_value(rightItr, 0)
357 return cmp(leftUnitText, rightUnitText)
359 def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
360 leftSymbolText = self._unitModel.get_value(leftItr, 2)
361 rightSymbolText = self._unitModel.get_value(rightItr, 2)
362 return cmp(leftSymbolText, rightSymbolText)
364 def _value_model_cmp(self, sortedModel, leftItr, rightItr):
365 #special sorting exceptions for ascii values (instead of float values)
366 if self._selectedCategoryName == "Computer Numbers":
367 leftValue = self._unitModel.get_value(leftItr, 1)
368 rightValue = self._unitModel.get_value(rightItr, 1)
370 leftValueText = self._unitModel.get_value(leftItr, 1)
371 leftValue = float(leftValueText) if leftValueText else 0.0
373 rightValueText = self._unitModel.get_value(rightItr, 1)
374 rightValue = float(rightValueText) if rightValueText else 0.0
375 return cmp(leftValue, rightValue)
377 def _get_column_sort_stuff(self):
379 (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
380 (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
381 (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
385 def _switch_category(self, category):
386 self._selectedCategoryName = category
387 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategoryName]
389 #Fill up the units descriptions and clear the value cells
390 self._clear_visible_unit_data()
391 for key in unit_data.get_units(self._selectedCategoryName):
392 iter = self._unitModel.append()
393 self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
394 self._sortedUnitModel.sort_column_changed()
396 self._select_default_unit()
398 def _clear_visible_unit_data(self):
399 self._unitDescription.get_buffer().set_text("")
400 self._unitName.set_text('')
401 self._unitValue.set_text('')
402 self._unitSymbol.set_text('')
404 self._previousUnitName.set_text('')
405 self._previousUnitValue.set_text('')
406 self._previousUnitSymbol.set_text('')
408 self._unitModel.clear()
410 def _select_default_unit(self):
411 # Restore the previous historical settings of previously selected units
412 # in this newly selected category
413 defaultPrimary = unit_data.get_base_unit(self._selectedCategoryName)
414 defaultSecondary = ""
415 if self._selectedCategoryName in self._defaultUnitForCategory:
416 if self._defaultUnitForCategory[self._selectedCategoryName][0]:
417 defaultPrimary = self._defaultUnitForCategory[self._selectedCategoryName][0]
418 if self._defaultUnitForCategory[self._selectedCategoryName][1]:
419 defaultSecondary = self._defaultUnitForCategory[self._selectedCategoryName][1]
421 units = unit_data.get_units(self._selectedCategoryName)
423 #Restore oldest selection first.
426 unitIndex = units.index(defaultPrimary)
429 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
431 #Restore newest selection second.
434 unitIndex = units.index(defaultSecondary)
437 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
439 # select the text so user can start typing right away
440 self._unitValue.grab_focus()
441 self._unitValue.select_region(0, -1)
443 def _sanitize_value(self, userEntry):
444 if self._selectedCategoryName == "Computer Numbers":
453 value = float(userEntry)
456 def _on_shortlist_changed(self, *args):
458 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
460 _moduleLogger.exception("")
462 def _on_edit_shortlist(self, *args):
464 raise NotImplementedError("%s" % self._toggleShortList.get_active())
466 _moduleLogger.exception("")
468 def _on_user_clear_selections(self, *args):
470 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
471 os.remove(selectionsDatPath)
472 self._defaultUnitForCategory = {}
474 _moduleLogger.exception("")
476 def _on_key_press(self, widget, event, *args):
478 @note Hildon specific
480 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
483 event.keyval == gtk.keysyms.F6 or
484 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
486 if self._isFullScreen:
487 self._mainWindow.unfullscreen()
489 self._mainWindow.fullscreen()
490 elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
492 elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
493 self._find_previous()
494 elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
497 _moduleLogger.exception("")
499 def _on_window_state_change(self, widget, event, *args):
501 @note Hildon specific
504 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
505 self._isFullScreen = True
507 self._isFullScreen = False
509 _moduleLogger.exception("")
511 def _on_findEntry_changed(self, *args):
513 Clear out find results since the user wants to look for something new
518 _moduleLogger.exception("")
520 def _on_find_activate(self, *args):
523 self._findButton.grab_focus()
525 _moduleLogger.exception("")
527 def _on_click_unit_column(self, col):
529 Sort the contents of the col when the user clicks on the title.
532 #Determine which column requires sorting
533 columns = self._get_column_sort_stuff()
534 for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
536 direction = getattr(self, directionName)
537 gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
540 self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
542 # set the visual for sorting
543 col.set_sort_indicator(True)
544 col.set_sort_order(not direction)
546 setattr(self, directionName, not direction)
549 maybeCol.set_sort_indicator(False)
551 assert False, "Unknown column: %s" % (col.get_title(), )
553 _moduleLogger.exception("")
555 def _on_category_selector_clicked(self, *args):
557 currenntIndex = unit_data.UNIT_CATEGORIES.index(self._selectedCategoryName)
558 newIndex = hildonize.touch_selector(
561 unit_data.UNIT_CATEGORIES,
565 selectedCategoryName = unit_data.UNIT_CATEGORIES[newIndex]
566 self._categorySelectionButton.set_label(selectedCategoryName)
567 self._categoryView.set_cursor(newIndex, self._categoryColumn, False)
568 self._categoryView.grab_focus()
570 _moduleLogger.exception("")
572 def _on_click_category(self, *args):
574 selected, iter = self._categoryView.get_selection().get_selected()
576 # User is typing in an invalid string, not selecting any category
578 selectedCategory = self._categoryModel.get_value(iter, 0)
579 self._switch_category(selectedCategory)
581 _moduleLogger.exception("")
583 def _on_click_unit(self, *args):
585 selected, iter = self._unitsView.get_selection().get_selected()
586 selected_unit = selected.get_value(iter, 0)
587 unit_spec = self._unitDataInCategory[selected_unit]
589 if self._unitName.get_text() != selected_unit:
590 self._previousUnitName.set_text(self._unitName.get_text())
591 self._previousUnitValue.set_text(self._unitValue.get_text())
592 self._previousUnitSymbol.set_text(self._unitSymbol.get())
594 self._unitName.set_text(selected_unit)
595 self._unitValue.set_text(selected.get_value(iter, 1))
596 buffer = self._unitDescription.get_buffer()
597 buffer.set_text(unit_spec[2])
598 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
600 self._unitSymbol.show()
602 self._unitSymbol.hide()
604 if self._unitValue.get_text() == '':
605 if self._selectedCategoryName == "Computer Numbers":
606 self._unitValue.set_text("0")
608 self._unitValue.set_text("0.0")
610 self._defaultUnitForCategory[self._selectedCategoryName] = [
611 self._unitName.get_text(), self._previousUnitName.get_text()
614 # select the text so user can start typing right away
615 self._unitValue.grab_focus()
616 self._unitValue.select_region(0, -1)
618 _moduleLogger.exception("")
620 def _on_unit_value_changed(self, *args):
622 if self._unitName.get_text() == '':
624 if not self._unitValue.is_focus():
627 #retrieve the conversion function and value from the selected unit
628 value = self._sanitize_value(self._unitValue.get_text())
629 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
630 base = func.to_base(value, arg)
632 #point to the first row
633 for row in self._unitModel:
634 func, arg = self._unitDataInCategory[row[0]][0]
635 row[1] = str(func.from_base(base, arg))
637 # Update the secondary unit entry
638 if self._previousUnitName.get_text() != '':
639 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
640 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
642 _moduleLogger.exception("")
644 def _on_previous_unit_value_changed(self, *args):
646 if self._previousUnitName.get_text() == '':
648 if not self._previousUnitValue.is_focus():
651 #retrieve the conversion function and value from the selected unit
652 value = self._sanitize_value(self._previousUnitValue.get_text())
653 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
654 base = func.to_base(value, arg)
656 #point to the first row
657 for row in self._unitModel:
658 func, arg = self._unitDataInCategory[row[0]][0]
659 row[1] = str(func.from_base(base, arg))
661 # Update the primary unit entry
662 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
663 self._unitValue.set_text(str(func.from_base(base, arg, )))
665 _moduleLogger.exception("")
667 def _on_about_clicked(self, a):
668 dlg = gtk.AboutDialog()
669 dlg.set_name(constants.__pretty_app_name__)
670 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
671 dlg.set_copyright("Copyright 2009 - GPL")
673 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
674 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
678 def _on_user_exit(self, *args):
680 self._save_settings()
682 _moduleLogger.exception("")
688 logging.basicConfig(level = logging.DEBUG)
690 os.makedirs(constants._data_path_)
696 if not PROFILE_STARTUP:
700 if __name__ == "__main__":