18 _moduleLogger = logging.getLogger("gonvert_glade")
19 PROFILE_STARTUP = False
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._selectedCategoryName = '' # 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, 'helpMenuItem', _('Help'))
73 change_menu_label(widgets, 'aboutMenuItem', _('About'))
74 change_menu_label(widgets, 'findButton', _('Find'))
76 self._shortlistcheck = widgets.get_widget('shortlistcheck')
77 self._toggleShortList = widgets.get_widget('toggleShortList')
79 self._categoryView = widgets.get_widget('categoryView')
81 self._unitsView = widgets.get_widget('unitsView')
82 self._unitsView.set_property('rules_hint', 1)
83 self._unitsView_selection = self._unitsView.get_selection()
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')
90 self._unitSymbol = widgets.get_widget('unitSymbol')
91 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
93 self._unitDescription = widgets.get_widget('unitDescription')
95 self._searchLayout = widgets.get_widget('searchLayout')
96 self._searchLayout.hide()
97 self._findEntry = widgets.get_widget('findEntry')
98 self._findLabel = widgets.get_widget('findLabel')
99 self._findButton = widgets.get_widget('findButton')
100 ToolTips = gtk.Tooltips()
101 ToolTips.set_tip(self._findButton, _(u'Find unit (F6)'))
103 #insert a self._categoryColumnumn into the units list even though the heading will not be seen
104 renderer = gtk.CellRendererText()
105 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
106 self._unitNameColumn.set_property('resizable', 1)
107 self._unitNameColumn.add_attribute(renderer, 'text', 0)
108 self._unitNameColumn.set_clickable(True)
109 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
110 self._unitsView.append_column(self._unitNameColumn)
112 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
113 self._unitValueColumn.set_property('resizable', 1)
114 self._unitValueColumn.add_attribute(renderer, 'text', 1)
115 self._unitValueColumn.set_clickable(True)
116 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
117 self._unitsView.append_column(self._unitValueColumn)
119 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
120 self._unitSymbolColumn.set_property('resizable', 1)
121 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
122 self._unitSymbolColumn.set_clickable(True)
123 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
124 self._unitsView.append_column(self._unitSymbolColumn)
126 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
127 self._sortedUnitModel = gtk.TreeModelSort(self._unitModel)
128 columns = self._get_column_sort_stuff()
129 for columnIndex, (column, sortDirection, col_cmp) in enumerate(columns):
130 self._sortedUnitModel.set_sort_func(columnIndex, col_cmp)
131 self._unitsView.set_model(self._sortedUnitModel)
133 #Insert a column into the category list even though the heading will not be seen
134 renderer = gtk.CellRendererText()
135 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
136 self._categoryColumn.set_property('resizable', 1)
137 self._categoryColumn.add_attribute(renderer, 'text', 0)
138 self._categoryView.append_column(self._categoryColumn)
140 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
141 self._categoryView.set_model(self._categoryModel)
142 #colourize each row differently for easier reading
143 self._categoryView.set_property('rules_hint', 1)
145 #Populate the catagories list
146 for key in unit_data.UNIT_CATEGORIES:
147 iter = self._categoryModel.append()
148 self._categoryModel.set(iter, 0, key)
150 #--------- connections to GUI ----------------
152 "on_exit_menu_activate": self._on_user_exit,
153 "on_main_window_destroy": self._on_user_exit,
154 "on_categoryView_select_row": self._on_click_category,
155 "on_unitValue_changed": self._on_unit_value_changed,
156 "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
157 "on_findButton_clicked": self._on_find_activate,
158 "on_findEntry_activated": self._on_find_activate,
159 "on_findEntry_changed": self._on_findEntry_changed,
160 "on_aboutMenuItem_activate": self._on_about_clicked,
161 "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
162 "on_unitsView_cursor_changed": self._on_click_unit,
163 "on_shortlistcheck_toggled": self._on_shortlist_changed,
164 "on_toggleShortList_activate": self._on_edit_shortlist,
166 widgets.signal_autoconnect(dic)
167 self._mainWindow.connect("key-press-event", self._on_key_press)
168 self._mainWindow.connect("window-state-event", self._on_window_state_change)
170 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
171 iconPath = pixmapspath + '/gonvert.png'
172 if os.path.exists(iconPath):
173 self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
175 _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
177 self._load_settings()
179 def _load_settings(self):
180 #Restore window size from previously saved settings if it exists and is valid.
181 windowDatPath = "/".join((constants._data_path_, "window.dat"))
182 if os.path.exists(windowDatPath):
183 #Retrieving previous window settings from ~/.gonvert/window.dat
184 saved_window = pickle.load(open(windowDatPath, "r"))
185 #If the 'size' has been stored, then extract size from saved_window.
186 if 'size' in saved_window:
187 a, b = saved_window['size']
188 self._mainWindow.resize(a, b)
190 #Restore selections from previously saved settings if it exists and is valid.
191 historical_catergory_found = False
192 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
193 if os.path.exists(selectionsDatPath):
194 #Retrieving previous selections from ~/.gonvert/selections.dat
195 selections = pickle.load(open(selectionsDatPath, 'r'))
196 #Restoring previous selections.
197 #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
198 if 'selected_units' in selections:
199 self._defaultUnitForCategory = selections['selected_units']
200 #Make sure that the 'self._selectedCategoryName' has been stored.
201 if 'selected_category' in selections:
202 #Match an available category to the previously selected category.
203 for counter in range(len(unit_data.UNIT_CATEGORIES)):
204 if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
205 # Restore the previously selected category.
206 self._categoryView.set_cursor(counter, self._categoryColumn, False)
207 self._categoryView.grab_focus()
208 historical_catergory_found = True
210 if not historical_catergory_found:
211 print "Couldn't find saved category, using default."
212 #If historical records were not kept then default to
213 # put the focus on the first category
214 self._categoryView.set_cursor(0, self._categoryColumn, False)
215 self._categoryView.grab_focus()
217 self._select_default_unit()
219 def _save_settings(self):
221 This routine saves the selections to a file, and
222 should therefore only be called when exiting the program.
224 Update selections dictionary which consists of the following keys:
225 'self._selectedCategoryName': full name of selected category
226 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
227 [categoryname: #1 displayed unit, #2 displayed unit]
229 #Determine the contents of the selected category row
230 selected, iter = self._categoryView.get_selection().get_selected()
231 self._selectedCategoryName = self._categoryModel.get_value(iter, 0)
234 'selected_category': self._selectedCategoryName,
235 'selected_units': self._defaultUnitForCategory
237 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
238 pickle.dump(selections, open(selectionsDatPath, 'w'))
240 #Get last size of app and save it
242 'size': self._mainWindow.get_size()
244 windowDatPath = "/".join((constants._data_path_, "window.dat"))
245 pickle.dump(window_settings, open(windowDatPath, 'w'))
247 def _clear_find(self):
248 # switch to "new find" state
249 self._find_result = []
252 # Clear our user message
253 self._findLabel.set_text('')
255 def _find_first(self):
256 assert len(self._find_result) == 0
257 assert self._findIndex == 0
258 findString = self._findEntry.get_text().strip().lower()
262 # Gather info on all the matching units from all categories
263 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
264 units = unit_data.get_units(category)
265 for unitIndex, unit in enumerate(units):
266 loweredUnit = unit.lower()
267 if loweredUnit in findString or findString in loweredUnit:
268 self._find_result.append((category, unit, catIndex, unitIndex))
270 def _update_find_selection(self):
271 assert 0 < len(self._find_result)
273 #check if next find is in a new category (prevent category changes when unnecessary
274 if self._selectedCategoryName != self._find_result[self._findIndex][0]:
275 self._categoryView.set_cursor(
276 self._find_result[self._findIndex][2], self._categoryColumn, False
279 self._unitsView.set_cursor(
280 self._find_result[self._findIndex][3], self._unitNameColumn, True
283 def _find_next(self):
284 if len(self._find_result) == 0:
287 if self._findIndex == len(self._find_result)-1:
292 if not self._find_result:
293 self._findLabel.set_text('Text not found')
295 self._update_find_selection()
296 resultsLeft = len(self._find_result) - self._findIndex - 1
297 self._findLabel.set_text(
298 '%s result(s) left' % (resultsLeft, )
301 def _find_previous(self):
302 if len(self._find_result) == 0:
305 if self._findIndex == 0:
306 self._findIndex = len(self._find_result)-1
310 if not self._find_result:
311 self._findLabel.set_text('Text not found')
313 self._update_find_selection()
314 resultsLeft = len(self._find_result) - self._findIndex - 1
315 self._findLabel.set_text(
316 '%s result(s) left' % (resultsLeft, )
319 def _toggle_find(self):
320 if self._searchLayout.get_property("visible"):
321 self._searchLayout.hide()
323 self._searchLayout.show()
325 def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
326 leftUnitText = self._unitModel.get_value(leftItr, 0)
327 rightUnitText = self._unitModel.get_value(rightItr, 0)
328 return cmp(leftUnitText, rightUnitText)
330 def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
331 leftSymbolText = self._unitModel.get_value(leftItr, 2)
332 rightSymbolText = self._unitModel.get_value(rightItr, 2)
333 return cmp(leftSymbolText, rightSymbolText)
335 def _value_model_cmp(self, sortedModel, leftItr, rightItr):
336 #special sorting exceptions for ascii values (instead of float values)
337 if self._selectedCategoryName == "Computer Numbers":
338 leftValue = self._unitModel.get_value(leftItr, 1)
339 rightValue = self._unitModel.get_value(rightItr, 1)
341 leftValueText = self._unitModel.get_value(leftItr, 1)
342 leftValue = float(leftValueText) if leftValueText else 0.0
344 rightValueText = self._unitModel.get_value(rightItr, 1)
345 rightValue = float(rightValueText) if rightValueText else 0.0
346 return cmp(leftValue, rightValue)
348 def _get_column_sort_stuff(self):
350 (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
351 (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
352 (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
356 def _switch_category(self, category):
357 self._selectedCategoryName = category
358 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategoryName]
360 #Fill up the units descriptions and clear the value cells
361 self._clear_visible_unit_data()
362 for key in unit_data.get_units(self._selectedCategoryName):
363 iter = self._unitModel.append()
364 self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
365 self._sortedUnitModel.sort_column_changed()
367 self._select_default_unit()
369 def _clear_visible_unit_data(self):
370 self._unitDescription.get_buffer().set_text("")
371 self._unitName.set_text('')
372 self._unitValue.set_text('')
373 self._unitSymbol.set_text('')
375 self._previousUnitName.set_text('')
376 self._previousUnitValue.set_text('')
377 self._previousUnitSymbol.set_text('')
379 self._unitModel.clear()
381 def _select_default_unit(self):
382 # Restore the previous historical settings of previously selected units
383 # in this newly selected category
384 defaultPrimary = unit_data.get_base_unit(self._selectedCategoryName)
385 defaultSecondary = ""
386 if self._selectedCategoryName in self._defaultUnitForCategory:
387 if self._defaultUnitForCategory[self._selectedCategoryName][0]:
388 defaultPrimary = self._defaultUnitForCategory[self._selectedCategoryName][0]
389 if self._defaultUnitForCategory[self._selectedCategoryName][1]:
390 defaultSecondary = self._defaultUnitForCategory[self._selectedCategoryName][1]
392 units = unit_data.get_units(self._selectedCategoryName)
394 #Restore oldest selection first.
396 unitIndex = units.index(defaultPrimary)
397 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
399 #Restore newest selection second.
401 unitIndex = units.index(defaultSecondary)
402 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
404 # select the text so user can start typing right away
405 self._unitValue.grab_focus()
406 self._unitValue.select_region(0, -1)
408 def _sanitize_value(self, userEntry):
409 if self._selectedCategoryName == "Computer Numbers":
418 value = float(userEntry)
421 def _on_shortlist_changed(self, *args):
423 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
425 _moduleLogger.exception("")
427 def _on_edit_shortlist(self, *args):
429 raise NotImplementedError("%s" % self._toggleShortList.get_active())
431 _moduleLogger.exception("")
433 def _on_user_clear_selections(self, *args):
435 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
436 os.remove(selectionsDatPath)
437 self._defaultUnitForCategory = {}
439 _moduleLogger.exception("")
441 def _on_key_press(self, widget, event, *args):
443 @note Hildon specific
445 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
448 event.keyval == gtk.keysyms.F6 or
449 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
451 if self._isFullScreen:
452 self._mainWindow.unfullscreen()
454 self._mainWindow.fullscreen()
455 elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
457 elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
458 self._find_previous()
459 elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
462 _moduleLogger.exception("")
464 def _on_window_state_change(self, widget, event, *args):
466 @note Hildon specific
469 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
470 self._isFullScreen = True
472 self._isFullScreen = False
474 _moduleLogger.exception("")
476 def _on_findEntry_changed(self, *args):
478 Clear out find results since the user wants to look for something new
483 _moduleLogger.exception("")
485 def _on_find_activate(self, *args):
488 self._findButton.grab_focus()
490 _moduleLogger.exception("")
492 def _on_click_unit_column(self, col):
494 Sort the contents of the col when the user clicks on the title.
497 #Determine which column requires sorting
498 columns = self._get_column_sort_stuff()
499 for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
501 direction = getattr(self, directionName)
502 gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
505 self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
507 # set the visual for sorting
508 col.set_sort_indicator(True)
509 col.set_sort_order(not direction)
511 setattr(self, directionName, not direction)
514 maybeCol.set_sort_indicator(False)
516 assert False, "Unknown column: %s" % (col.get_title(), )
518 _moduleLogger.exception("")
520 def _on_click_category(self, *args):
522 selected, iter = self._categoryView.get_selection().get_selected()
524 # User is typing in an invalid string, not selecting any category
526 selectedCategory = self._categoryModel.get_value(iter, 0)
527 self._switch_category(selectedCategory)
529 _moduleLogger.exception("")
531 def _on_click_unit(self, *args):
533 selected, iter = self._unitsView.get_selection().get_selected()
534 selected_unit = selected.get_value(iter, 0)
535 unit_spec = self._unitDataInCategory[selected_unit]
537 if self._unitName.get_text() != selected_unit:
538 self._previousUnitName.set_text(self._unitName.get_text())
539 self._previousUnitValue.set_text(self._unitValue.get_text())
540 self._previousUnitSymbol.set_text(self._unitSymbol.get())
542 self._unitName.set_text(selected_unit)
543 self._unitValue.set_text(selected.get_value(iter, 1))
544 buffer = self._unitDescription.get_buffer()
545 buffer.set_text(unit_spec[2])
546 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
548 if self._unitValue.get_text() == '':
549 if self._selectedCategoryName == "Computer Numbers":
550 self._unitValue.set_text("0")
552 self._unitValue.set_text("0.0")
554 self._defaultUnitForCategory[self._selectedCategoryName] = [
555 self._unitName.get_text(), self._previousUnitName.get_text()
558 # select the text so user can start typing right away
559 self._unitValue.grab_focus()
560 self._unitValue.select_region(0, -1)
562 _moduleLogger.exception("")
564 def _on_unit_value_changed(self, *args):
566 if self._unitName.get_text() == '':
568 if not self._unitValue.is_focus():
571 #retrieve the conversion function and value from the selected unit
572 value = self._sanitize_value(self._unitValue.get_text())
573 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
574 base = func.to_base(value, arg)
576 #point to the first row
577 for row in self._unitModel:
578 func, arg = self._unitDataInCategory[row[0]][0]
579 row[1] = str(func.from_base(base, arg))
581 # Update the secondary unit entry
582 if self._previousUnitName.get_text() != '':
583 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
584 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
586 _moduleLogger.exception("")
588 def _on_previous_unit_value_changed(self, *args):
590 if self._previousUnitName.get_text() == '':
592 if not self._previousUnitValue.is_focus():
595 #retrieve the conversion function and value from the selected unit
596 value = self._sanitize_value(self._previousUnitValue.get_text())
597 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
598 base = func.to_base(value, arg)
600 #point to the first row
601 for row in self._unitModel:
602 func, arg = self._unitDataInCategory[row[0]][0]
603 row[1] = str(func.from_base(base, arg))
605 # Update the primary unit entry
606 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
607 self._unitValue.set_text(str(func.from_base(base, arg, )))
609 _moduleLogger.exception("")
611 def _on_about_clicked(self, a):
612 dlg = gtk.AboutDialog()
613 dlg.set_name(constants.__pretty_app_name__)
614 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
615 dlg.set_copyright("Copyright 2009 - GPL")
617 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
618 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
622 def _on_user_exit(self, *args):
624 self._save_settings()
626 _moduleLogger.exception("")
632 logging.basicConfig(level = logging.DEBUG)
634 os.makedirs(constants._data_path_)
640 if not PROFILE_STARTUP:
644 if __name__ == "__main__":