19 _moduleLogger = logging.getLogger("gonvert_glade")
20 PROFILE_STARTUP = False
22 gettext.bindtextdomain('gonvert', '/usr/share/locale')
23 gettext.textdomain('gonvert')
27 def change_menu_label(widgets, labelname, newtext):
28 item_label = widgets.get_widget(labelname).get_children()[0]
29 item_label.set_text(newtext)
32 class Gonvert(object):
35 os.path.join(os.path.dirname(__file__), "gonvert.glade"),
36 os.path.join(os.path.dirname(__file__), "../data/gonvert.glade"),
37 os.path.join(os.path.dirname(__file__), "../lib/gonvert.glade"),
38 '/usr/lib/gonvert/gonvert.glade',
42 self._unitDataInCategory = None
43 self._unit_sort_direction = False
44 self._value_sort_direction = False
45 self._units_sort_direction = False
46 self._isFullScreen = False
48 self._find_result = [] # empty find result list
49 self._findIndex = 0 # default to find result number zero
51 self._selectedCategoryName = '' # preset to no selected category
52 self._defaultUnitForCategory = {} # empty dictionary for later use
54 #check to see if glade file is in current directory (user must be
55 # running from download untar directory)
56 for gladePath in self._glade_files:
57 if os.path.isfile(gladePath):
58 homepath = os.path.dirname(gladePath)
59 pixmapspath = "/".join((homepath, "pixmaps"))
60 widgets = gtk.glade.XML(gladePath)
63 _moduleLogger.error("UI Descriptor not found!")
67 self._mainWindow = widgets.get_widget('mainWindow')
69 change_menu_label(widgets, 'fileMenuItem', _('File'))
70 change_menu_label(widgets, 'exitMenuItem', _('Exit'))
71 change_menu_label(widgets, 'toolsMenuItem', _('Tools'))
72 change_menu_label(widgets, 'clearSelectionMenuItem', _('Clear selections'))
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')
91 self._unitSymbol = widgets.get_widget('unitSymbol')
92 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
94 self._unitDescription = widgets.get_widget('unitDescription')
96 self._searchLayout = widgets.get_widget('searchLayout')
97 self._searchLayout.hide()
98 self._findEntry = widgets.get_widget('findEntry')
99 self._findLabel = widgets.get_widget('findLabel')
100 self._findButton = widgets.get_widget('findButton')
101 ToolTips = gtk.Tooltips()
102 ToolTips.set_tip(self._findButton, _(u'Find unit (F6)'))
104 #insert a self._categoryColumnumn into the units list even though the heading will not be seen
105 renderer = gtk.CellRendererText()
106 self._unitNameColumn = gtk.TreeViewColumn(_('Unit Name'), renderer)
107 self._unitNameColumn.set_property('resizable', 1)
108 self._unitNameColumn.add_attribute(renderer, 'text', 0)
109 self._unitNameColumn.set_clickable(True)
110 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
111 self._unitsView.append_column(self._unitNameColumn)
113 self._unitValueColumn = gtk.TreeViewColumn(_('Value'), renderer)
114 self._unitValueColumn.set_property('resizable', 1)
115 self._unitValueColumn.add_attribute(renderer, 'text', 1)
116 self._unitValueColumn.set_clickable(True)
117 self._unitValueColumn.connect("clicked", self._on_click_unit_column)
118 self._unitsView.append_column(self._unitValueColumn)
120 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
121 self._unitSymbolColumn.set_property('resizable', 1)
122 self._unitSymbolColumn.add_attribute(renderer, 'text', 2)
123 self._unitSymbolColumn.set_clickable(True)
124 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
125 self._unitsView.append_column(self._unitSymbolColumn)
127 self._unitModel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
128 self._sortedUnitModel = gtk.TreeModelSort(self._unitModel)
129 columns = self._get_column_sort_stuff()
130 for columnIndex, (column, sortDirection, col_cmp) in enumerate(columns):
131 self._sortedUnitModel.set_sort_func(columnIndex, col_cmp)
132 self._unitsView.set_model(self._sortedUnitModel)
134 #Insert a column into the category list even though the heading will not be seen
135 renderer = gtk.CellRendererText()
136 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
137 self._categoryColumn.set_property('resizable', 1)
138 self._categoryColumn.add_attribute(renderer, 'text', 0)
139 self._categoryView.append_column(self._categoryColumn)
141 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
142 self._categoryView.set_model(self._categoryModel)
143 #colourize each row differently for easier reading
144 self._categoryView.set_property('rules_hint', 1)
146 #Populate the catagories list
147 for key in unit_data.UNIT_CATEGORIES:
148 iter = self._categoryModel.append()
149 self._categoryModel.set(iter, 0, key)
151 #--------- connections to GUI ----------------
153 "on_exit_menu_activate": self._on_user_exit,
154 "on_main_window_destroy": self._on_user_exit,
155 "on_categoryView_select_row": self._on_click_category,
156 "on_unitValue_changed": self._on_unit_value_changed,
157 "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
158 "on_findButton_clicked": self._on_find_activate,
159 "on_findEntry_activated": self._on_find_activate,
160 "on_findEntry_changed": self._on_findEntry_changed,
161 "on_aboutMenuItem_activate": self._on_about_clicked,
162 "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
163 "on_unitsView_cursor_changed": self._on_click_unit,
164 "on_shortlistcheck_toggled": self._on_shortlist_changed,
165 "on_toggleShortList_activate": self._on_edit_shortlist,
167 widgets.signal_autoconnect(dic)
168 self._mainWindow.connect("key-press-event", self._on_key_press)
169 self._mainWindow.connect("window-state-event", self._on_window_state_change)
171 self._mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__)
172 iconPath = pixmapspath + '/gonvert.png'
173 if os.path.exists(iconPath):
174 self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
176 _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
178 self._load_settings()
180 def _load_settings(self):
181 #Restore window size from previously saved settings if it exists and is valid.
182 windowDatPath = "/".join((constants._data_path_, "window.dat"))
183 if os.path.exists(windowDatPath):
184 #Retrieving previous window settings from ~/.gonvert/window.dat
185 saved_window = pickle.load(open(windowDatPath, "r"))
186 #If the 'size' has been stored, then extract size from saved_window.
187 if 'size' in saved_window:
188 a, b = saved_window['size']
189 self._mainWindow.resize(a, b)
191 #Maximize if no previous size was found
192 #self._mainWindow.maximize()
195 #Maximize if no previous window.dat file was found
196 #self._mainWindow.maximize()
199 #Restore selections from previously saved settings if it exists and is valid.
200 historical_catergory_found = False
201 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
202 if os.path.exists(selectionsDatPath):
203 #Retrieving previous selections from ~/.gonvert/selections.dat
204 selections = pickle.load(open(selectionsDatPath, 'r'))
205 #Restoring previous selections.
206 #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
207 if 'selected_units' in selections:
208 self._defaultUnitForCategory = selections['selected_units']
209 #Make sure that the 'self._selectedCategoryName' has been stored.
210 if 'selected_category' in selections:
211 #Match an available category to the previously selected category.
212 for counter in range(len(unit_data.UNIT_CATEGORIES)):
213 if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
214 # Restore the previously selected category.
215 self._categoryView.set_cursor(counter, self._categoryColumn, False)
216 self._categoryView.grab_focus()
217 historical_catergory_found = True
219 if not historical_catergory_found:
220 print "Couldn't find saved category, using default."
221 #If historical records were not kept then default to
222 # put the focus on the first category
223 self._categoryView.set_cursor(0, self._categoryColumn, False)
224 self._categoryView.grab_focus()
226 self._select_default_unit()
228 def _save_settings(self):
230 This routine saves the selections to a file, and
231 should therefore only be called when exiting the program.
233 Update selections dictionary which consists of the following keys:
234 'self._selectedCategoryName': full name of selected category
235 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
236 [categoryname: #1 displayed unit, #2 displayed unit]
238 #Determine the contents of the selected category row
239 selected, iter = self._categoryView.get_selection().get_selected()
240 self._selectedCategoryName = self._categoryModel.get_value(iter, 0)
243 'selected_category': self._selectedCategoryName,
244 'selected_units': self._defaultUnitForCategory
246 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
247 pickle.dump(selections, open(selectionsDatPath, 'w'))
249 #Get last size of app and save it
251 'size': self._mainWindow.get_size()
253 windowDatPath = "/".join((constants._data_path_, "window.dat"))
254 pickle.dump(window_settings, open(windowDatPath, 'w'))
256 def _clear_find(self):
257 # switch to "new find" state
258 self._find_result = []
261 # Clear our user message
262 self._findLabel.set_text('')
264 def _find_first(self):
265 assert len(self._find_result) == 0
266 assert self._findIndex == 0
267 findString = string.lower(string.strip(self._findEntry.get_text()))
271 # Gather info on all the matching units from all categories
272 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
273 units = unit_data.get_units(category)
274 for unitIndex, unit in enumerate(units):
275 loweredUnit = unit.lower()
276 if loweredUnit in findString or findString in loweredUnit:
277 self._find_result.append((category, unit, catIndex, unitIndex))
279 def _update_find_selection(self):
280 assert 0 < len(self._find_result)
282 #check if next find is in a new category (prevent category changes when unnecessary
283 if self._selectedCategoryName != self._find_result[self._findIndex][0]:
284 self._categoryView.set_cursor(
285 self._find_result[self._findIndex][2], self._categoryColumn, False
288 self._unitsView.set_cursor(
289 self._find_result[self._findIndex][3], self._unitNameColumn, True
292 def _find_next(self):
293 if len(self._find_result) == 0:
296 if self._findIndex == len(self._find_result)-1:
301 if not self._find_result:
302 self._findLabel.set_text('Text not found')
304 self._update_find_selection()
305 resultsLeft = len(self._find_result) - self._findIndex - 1
306 self._findLabel.set_text(
307 '%s result(s) left' % (resultsLeft, )
310 def _find_previous(self):
311 if len(self._find_result) == 0:
314 if self._findIndex == 0:
315 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 _toggle_find(self):
329 if self._searchLayout.get_property("visible"):
330 self._searchLayout.hide()
332 self._searchLayout.show()
334 def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
335 leftUnitText = self._unitModel.get_value(leftItr, 0)
336 rightUnitText = self._unitModel.get_value(rightItr, 0)
337 return cmp(leftUnitText, rightUnitText)
339 def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
340 leftSymbolText = self._unitModel.get_value(leftItr, 2)
341 rightSymbolText = self._unitModel.get_value(rightItr, 2)
342 return cmp(leftSymbolText, rightSymbolText)
344 def _value_model_cmp(self, sortedModel, leftItr, rightItr):
345 #special sorting exceptions for ascii values (instead of float values)
346 if self._selectedCategoryName == "Computer Numbers":
347 leftValue = self._unitModel.get_value(leftItr, 1)
348 rightValue = self._unitModel.get_value(rightItr, 1)
350 leftValueText = self._unitModel.get_value(leftItr, 1)
351 leftValue = float(leftValueText) if leftValueText else 0.0
353 rightValueText = self._unitModel.get_value(rightItr, 1)
354 rightValue = float(rightValueText) if rightValueText else 0.0
355 return cmp(leftValue, rightValue)
357 def _get_column_sort_stuff(self):
359 (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
360 (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
361 (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
365 def _switch_category(self, category):
366 self._selectedCategoryName = category
367 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategoryName]
369 #Fill up the units descriptions and clear the value cells
370 self._clear_visible_unit_data()
371 for key in unit_data.get_units(self._selectedCategoryName):
372 iter = self._unitModel.append()
373 self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
374 self._sortedUnitModel.sort_column_changed()
376 self._select_default_unit()
378 def _clear_visible_unit_data(self):
379 self._unitDescription.get_buffer().set_text("")
380 self._unitName.set_text('')
381 self._unitValue.set_text('')
382 self._unitSymbol.set_text('')
384 self._previousUnitName.set_text('')
385 self._previousUnitValue.set_text('')
386 self._previousUnitSymbol.set_text('')
388 self._unitModel.clear()
390 def _select_default_unit(self):
391 # Restore the previous historical settings of previously selected units
392 # in this newly selected category
393 defaultPrimary = unit_data.get_base_unit(self._selectedCategoryName)
394 defaultSecondary = ""
395 if self._selectedCategoryName in self._defaultUnitForCategory:
396 if self._defaultUnitForCategory[self._selectedCategoryName][0]:
397 defaultPrimary = self._defaultUnitForCategory[self._selectedCategoryName][0]
398 if self._defaultUnitForCategory[self._selectedCategoryName][1]:
399 defaultSecondary = self._defaultUnitForCategory[self._selectedCategoryName][1]
401 units = unit_data.get_units(self._selectedCategoryName)
403 #Restore oldest selection first.
405 unitIndex = units.index(defaultPrimary)
406 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
408 #Restore newest selection second.
410 unitIndex = units.index(defaultSecondary)
411 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
413 # select the text so user can start typing right away
414 self._unitValue.grab_focus()
415 self._unitValue.select_region(0, -1)
417 def _sanitize_value(self, userEntry):
418 if self._selectedCategoryName == "Computer Numbers":
427 value = float(userEntry)
430 def _on_shortlist_changed(self, *args):
432 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
434 _moduleLogger.exception("")
436 def _on_edit_shortlist(self, *args):
438 raise NotImplementedError("%s" % self._toggleShortList.get_active())
440 _moduleLogger.exception("")
442 def _on_user_clear_selections(self, *args):
444 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
445 os.remove(selectionsDatPath)
446 self._defaultUnitForCategory = {}
448 _moduleLogger.exception("")
450 def _on_key_press(self, widget, event, *args):
452 @note Hildon specific
454 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
457 event.keyval == gtk.keysyms.F6 or
458 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
460 if self._isFullScreen:
461 self._mainWindow.unfullscreen()
463 self._mainWindow.fullscreen()
464 elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
466 elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
467 self._find_previous()
468 elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
471 _moduleLogger.exception("")
473 def _on_window_state_change(self, widget, event, *args):
475 @note Hildon specific
478 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
479 self._isFullScreen = True
481 self._isFullScreen = False
483 _moduleLogger.exception("")
485 def _on_findEntry_changed(self, *args):
487 Clear out find results since the user wants to look for something new
492 _moduleLogger.exception("")
494 def _on_find_activate(self, *args):
497 self._findButton.grab_focus()
499 _moduleLogger.exception("")
501 def _on_click_unit_column(self, col):
503 Sort the contents of the col when the user clicks on the title.
506 #Determine which column requires sorting
507 columns = self._get_column_sort_stuff()
508 for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
510 direction = getattr(self, directionName)
511 gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
514 self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
516 # set the visual for sorting
517 col.set_sort_indicator(True)
518 col.set_sort_order(not direction)
520 setattr(self, directionName, not direction)
523 maybeCol.set_sort_indicator(False)
525 assert False, "Unknown column: %s" % (col.get_title(), )
527 _moduleLogger.exception("")
529 def _on_click_category(self, *args):
531 selected, iter = self._categoryView.get_selection().get_selected()
533 # User is typing in an invalid string, not selecting any category
535 selectedCategory = self._categoryModel.get_value(iter, 0)
536 self._switch_category(selectedCategory)
538 _moduleLogger.exception("")
540 def _on_click_unit(self, *args):
542 selected, iter = self._unitsView.get_selection().get_selected()
543 selected_unit = selected.get_value(iter, 0)
544 unit_spec = self._unitDataInCategory[selected_unit]
546 if self._unitName.get_text() != selected_unit:
547 self._previousUnitName.set_text(self._unitName.get_text())
548 self._previousUnitValue.set_text(self._unitValue.get_text())
549 self._previousUnitSymbol.set_text(self._unitSymbol.get())
551 self._unitName.set_text(selected_unit)
552 self._unitValue.set_text(selected.get_value(iter, 1))
553 buffer = self._unitDescription.get_buffer()
554 buffer.set_text(unit_spec[2])
555 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
557 if self._unitValue.get_text() == '':
558 if self._selectedCategoryName == "Computer Numbers":
559 self._unitValue.set_text("0")
561 self._unitValue.set_text("0.0")
563 self._defaultUnitForCategory[self._selectedCategoryName] = [
564 self._unitName.get_text(), self._previousUnitName.get_text()
567 # select the text so user can start typing right away
568 self._unitValue.grab_focus()
569 self._unitValue.select_region(0, -1)
571 _moduleLogger.exception("")
573 def _on_unit_value_changed(self, *args):
575 if self._unitName.get_text() == '':
577 if not self._unitValue.is_focus():
580 #retrieve the conversion function and value from the selected unit
581 value = self._sanitize_value(self._unitValue.get_text())
582 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
583 base = func.to_base(value, arg)
585 #point to the first row
586 for row in self._unitModel:
587 func, arg = self._unitDataInCategory[row[0]][0]
588 row[1] = str(func.from_base(base, arg))
590 # Update the secondary unit entry
591 if self._previousUnitName.get_text() != '':
592 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
593 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
595 _moduleLogger.exception("")
597 def _on_previous_unit_value_changed(self, *args):
599 if self._previousUnitName.get_text() == '':
601 if not self._previousUnitValue.is_focus():
604 #retrieve the conversion function and value from the selected unit
605 value = self._sanitize_value(self._previousUnitValue.get_text())
606 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
607 base = func.to_base(value, arg)
609 #point to the first row
610 for row in self._unitModel:
611 func, arg = self._unitDataInCategory[row[0]][0]
612 row[1] = str(func.from_base(base, arg))
614 # Update the primary unit entry
615 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
616 self._unitValue.set_text(str(func.from_base(base, arg, )))
618 _moduleLogger.exception("")
620 def _on_about_clicked(self, a):
621 dlg = gtk.AboutDialog()
622 dlg.set_name(constants.__pretty_app_name__)
623 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
624 dlg.set_copyright("Copyright 2009 - GPL")
626 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
627 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
631 def _on_user_exit(self, *args):
633 self._save_settings()
635 _moduleLogger.exception("")
641 logging.basicConfig(level = logging.DEBUG)
643 os.makedirs(constants._data_path_)
649 if not PROFILE_STARTUP:
653 if __name__ == "__main__":