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 #Restore selections from previously saved settings if it exists and is valid.
192 historical_catergory_found = False
193 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
194 if os.path.exists(selectionsDatPath):
195 #Retrieving previous selections from ~/.gonvert/selections.dat
196 selections = pickle.load(open(selectionsDatPath, 'r'))
197 #Restoring previous selections.
198 #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
199 if 'selected_units' in selections:
200 self._defaultUnitForCategory = selections['selected_units']
201 #Make sure that the 'self._selectedCategoryName' has been stored.
202 if 'selected_category' in selections:
203 #Match an available category to the previously selected category.
204 for counter in range(len(unit_data.UNIT_CATEGORIES)):
205 if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
206 # Restore the previously selected category.
207 self._categoryView.set_cursor(counter, self._categoryColumn, False)
208 self._categoryView.grab_focus()
209 historical_catergory_found = True
211 if not historical_catergory_found:
212 print "Couldn't find saved category, using default."
213 #If historical records were not kept then default to
214 # put the focus on the first category
215 self._categoryView.set_cursor(0, self._categoryColumn, False)
216 self._categoryView.grab_focus()
218 self._select_default_unit()
220 def _save_settings(self):
222 This routine saves the selections to a file, and
223 should therefore only be called when exiting the program.
225 Update selections dictionary which consists of the following keys:
226 'self._selectedCategoryName': full name of selected category
227 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
228 [categoryname: #1 displayed unit, #2 displayed unit]
230 #Determine the contents of the selected category row
231 selected, iter = self._categoryView.get_selection().get_selected()
232 self._selectedCategoryName = self._categoryModel.get_value(iter, 0)
235 'selected_category': self._selectedCategoryName,
236 'selected_units': self._defaultUnitForCategory
238 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
239 pickle.dump(selections, open(selectionsDatPath, 'w'))
241 #Get last size of app and save it
243 'size': self._mainWindow.get_size()
245 windowDatPath = "/".join((constants._data_path_, "window.dat"))
246 pickle.dump(window_settings, open(windowDatPath, 'w'))
248 def _clear_find(self):
249 # switch to "new find" state
250 self._find_result = []
253 # Clear our user message
254 self._findLabel.set_text('')
256 def _find_first(self):
257 assert len(self._find_result) == 0
258 assert self._findIndex == 0
259 findString = string.lower(string.strip(self._findEntry.get_text()))
263 # Gather info on all the matching units from all categories
264 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
265 units = unit_data.get_units(category)
266 for unitIndex, unit in enumerate(units):
267 loweredUnit = unit.lower()
268 if loweredUnit in findString or findString in loweredUnit:
269 self._find_result.append((category, unit, catIndex, unitIndex))
271 def _update_find_selection(self):
272 assert 0 < len(self._find_result)
274 #check if next find is in a new category (prevent category changes when unnecessary
275 if self._selectedCategoryName != self._find_result[self._findIndex][0]:
276 self._categoryView.set_cursor(
277 self._find_result[self._findIndex][2], self._categoryColumn, False
280 self._unitsView.set_cursor(
281 self._find_result[self._findIndex][3], self._unitNameColumn, True
284 def _find_next(self):
285 if len(self._find_result) == 0:
288 if self._findIndex == len(self._find_result)-1:
293 if not self._find_result:
294 self._findLabel.set_text('Text not found')
296 self._update_find_selection()
297 resultsLeft = len(self._find_result) - self._findIndex - 1
298 self._findLabel.set_text(
299 '%s result(s) left' % (resultsLeft, )
302 def _find_previous(self):
303 if len(self._find_result) == 0:
306 if self._findIndex == 0:
307 self._findIndex = len(self._find_result)-1
311 if not self._find_result:
312 self._findLabel.set_text('Text not found')
314 self._update_find_selection()
315 resultsLeft = len(self._find_result) - self._findIndex - 1
316 self._findLabel.set_text(
317 '%s result(s) left' % (resultsLeft, )
320 def _toggle_find(self):
321 if self._searchLayout.get_property("visible"):
322 self._searchLayout.hide()
324 self._searchLayout.show()
326 def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
327 leftUnitText = self._unitModel.get_value(leftItr, 0)
328 rightUnitText = self._unitModel.get_value(rightItr, 0)
329 return cmp(leftUnitText, rightUnitText)
331 def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
332 leftSymbolText = self._unitModel.get_value(leftItr, 2)
333 rightSymbolText = self._unitModel.get_value(rightItr, 2)
334 return cmp(leftSymbolText, rightSymbolText)
336 def _value_model_cmp(self, sortedModel, leftItr, rightItr):
337 #special sorting exceptions for ascii values (instead of float values)
338 if self._selectedCategoryName == "Computer Numbers":
339 leftValue = self._unitModel.get_value(leftItr, 1)
340 rightValue = self._unitModel.get_value(rightItr, 1)
342 leftValueText = self._unitModel.get_value(leftItr, 1)
343 leftValue = float(leftValueText) if leftValueText else 0.0
345 rightValueText = self._unitModel.get_value(rightItr, 1)
346 rightValue = float(rightValueText) if rightValueText else 0.0
347 return cmp(leftValue, rightValue)
349 def _get_column_sort_stuff(self):
351 (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
352 (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
353 (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
357 def _switch_category(self, category):
358 self._selectedCategoryName = category
359 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategoryName]
361 #Fill up the units descriptions and clear the value cells
362 self._clear_visible_unit_data()
363 for key in unit_data.get_units(self._selectedCategoryName):
364 iter = self._unitModel.append()
365 self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
366 self._sortedUnitModel.sort_column_changed()
368 self._select_default_unit()
370 def _clear_visible_unit_data(self):
371 self._unitDescription.get_buffer().set_text("")
372 self._unitName.set_text('')
373 self._unitValue.set_text('')
374 self._unitSymbol.set_text('')
376 self._previousUnitName.set_text('')
377 self._previousUnitValue.set_text('')
378 self._previousUnitSymbol.set_text('')
380 self._unitModel.clear()
382 def _select_default_unit(self):
383 # Restore the previous historical settings of previously selected units
384 # in this newly selected category
385 defaultPrimary = unit_data.get_base_unit(self._selectedCategoryName)
386 defaultSecondary = ""
387 if self._selectedCategoryName in self._defaultUnitForCategory:
388 if self._defaultUnitForCategory[self._selectedCategoryName][0]:
389 defaultPrimary = self._defaultUnitForCategory[self._selectedCategoryName][0]
390 if self._defaultUnitForCategory[self._selectedCategoryName][1]:
391 defaultSecondary = self._defaultUnitForCategory[self._selectedCategoryName][1]
393 units = unit_data.get_units(self._selectedCategoryName)
395 #Restore oldest selection first.
397 unitIndex = units.index(defaultPrimary)
398 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
400 #Restore newest selection second.
402 unitIndex = units.index(defaultSecondary)
403 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
405 # select the text so user can start typing right away
406 self._unitValue.grab_focus()
407 self._unitValue.select_region(0, -1)
409 def _sanitize_value(self, userEntry):
410 if self._selectedCategoryName == "Computer Numbers":
419 value = float(userEntry)
422 def _on_shortlist_changed(self, *args):
424 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
426 _moduleLogger.exception("")
428 def _on_edit_shortlist(self, *args):
430 raise NotImplementedError("%s" % self._toggleShortList.get_active())
432 _moduleLogger.exception("")
434 def _on_user_clear_selections(self, *args):
436 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
437 os.remove(selectionsDatPath)
438 self._defaultUnitForCategory = {}
440 _moduleLogger.exception("")
442 def _on_key_press(self, widget, event, *args):
444 @note Hildon specific
446 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
449 event.keyval == gtk.keysyms.F6 or
450 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
452 if self._isFullScreen:
453 self._mainWindow.unfullscreen()
455 self._mainWindow.fullscreen()
456 elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
458 elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
459 self._find_previous()
460 elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
463 _moduleLogger.exception("")
465 def _on_window_state_change(self, widget, event, *args):
467 @note Hildon specific
470 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
471 self._isFullScreen = True
473 self._isFullScreen = False
475 _moduleLogger.exception("")
477 def _on_findEntry_changed(self, *args):
479 Clear out find results since the user wants to look for something new
484 _moduleLogger.exception("")
486 def _on_find_activate(self, *args):
489 self._findButton.grab_focus()
491 _moduleLogger.exception("")
493 def _on_click_unit_column(self, col):
495 Sort the contents of the col when the user clicks on the title.
498 #Determine which column requires sorting
499 columns = self._get_column_sort_stuff()
500 for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
502 direction = getattr(self, directionName)
503 gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
506 self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
508 # set the visual for sorting
509 col.set_sort_indicator(True)
510 col.set_sort_order(not direction)
512 setattr(self, directionName, not direction)
515 maybeCol.set_sort_indicator(False)
517 assert False, "Unknown column: %s" % (col.get_title(), )
519 _moduleLogger.exception("")
521 def _on_click_category(self, *args):
523 selected, iter = self._categoryView.get_selection().get_selected()
525 # User is typing in an invalid string, not selecting any category
527 selectedCategory = self._categoryModel.get_value(iter, 0)
528 self._switch_category(selectedCategory)
530 _moduleLogger.exception("")
532 def _on_click_unit(self, *args):
534 selected, iter = self._unitsView.get_selection().get_selected()
535 selected_unit = selected.get_value(iter, 0)
536 unit_spec = self._unitDataInCategory[selected_unit]
538 if self._unitName.get_text() != selected_unit:
539 self._previousUnitName.set_text(self._unitName.get_text())
540 self._previousUnitValue.set_text(self._unitValue.get_text())
541 self._previousUnitSymbol.set_text(self._unitSymbol.get())
543 self._unitName.set_text(selected_unit)
544 self._unitValue.set_text(selected.get_value(iter, 1))
545 buffer = self._unitDescription.get_buffer()
546 buffer.set_text(unit_spec[2])
547 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
549 if self._unitValue.get_text() == '':
550 if self._selectedCategoryName == "Computer Numbers":
551 self._unitValue.set_text("0")
553 self._unitValue.set_text("0.0")
555 self._defaultUnitForCategory[self._selectedCategoryName] = [
556 self._unitName.get_text(), self._previousUnitName.get_text()
559 # select the text so user can start typing right away
560 self._unitValue.grab_focus()
561 self._unitValue.select_region(0, -1)
563 _moduleLogger.exception("")
565 def _on_unit_value_changed(self, *args):
567 if self._unitName.get_text() == '':
569 if not self._unitValue.is_focus():
572 #retrieve the conversion function and value from the selected unit
573 value = self._sanitize_value(self._unitValue.get_text())
574 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
575 base = func.to_base(value, arg)
577 #point to the first row
578 for row in self._unitModel:
579 func, arg = self._unitDataInCategory[row[0]][0]
580 row[1] = str(func.from_base(base, arg))
582 # Update the secondary unit entry
583 if self._previousUnitName.get_text() != '':
584 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
585 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
587 _moduleLogger.exception("")
589 def _on_previous_unit_value_changed(self, *args):
591 if self._previousUnitName.get_text() == '':
593 if not self._previousUnitValue.is_focus():
596 #retrieve the conversion function and value from the selected unit
597 value = self._sanitize_value(self._previousUnitValue.get_text())
598 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
599 base = func.to_base(value, arg)
601 #point to the first row
602 for row in self._unitModel:
603 func, arg = self._unitDataInCategory[row[0]][0]
604 row[1] = str(func.from_base(base, arg))
606 # Update the primary unit entry
607 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
608 self._unitValue.set_text(str(func.from_base(base, arg, )))
610 _moduleLogger.exception("")
612 def _on_about_clicked(self, a):
613 dlg = gtk.AboutDialog()
614 dlg.set_name(constants.__pretty_app_name__)
615 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
616 dlg.set_copyright("Copyright 2009 - GPL")
618 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
619 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
623 def _on_user_exit(self, *args):
625 self._save_settings()
627 _moduleLogger.exception("")
633 logging.basicConfig(level = logging.DEBUG)
635 os.makedirs(constants._data_path_)
641 if not PROFILE_STARTUP:
645 if __name__ == "__main__":