19 _moduleLogger = logging.getLogger("gonvert_glade")
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 #Maximize if no previous size was found
191 #self._mainWindow.maximize()
194 #Maximize if no previous window.dat file was found
195 #self._mainWindow.maximize()
198 #Restore selections from previously saved settings if it exists and is valid.
199 historical_catergory_found = False
200 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
201 if os.path.exists(selectionsDatPath):
202 #Retrieving previous selections from ~/.gonvert/selections.dat
203 selections = pickle.load(open(selectionsDatPath, 'r'))
204 #Restoring previous selections.
205 #If the 'selected_unts' has been stored, then extract self._defaultUnitForCategory from selections.
206 if 'selected_units' in selections:
207 self._defaultUnitForCategory = selections['selected_units']
208 #Make sure that the 'self._selectedCategoryName' has been stored.
209 if 'selected_category' in selections:
210 #Match an available category to the previously selected category.
211 for counter in range(len(unit_data.UNIT_CATEGORIES)):
212 if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
213 # Restore the previously selected category.
214 self._categoryView.set_cursor(counter, self._categoryColumn, False)
215 self._categoryView.grab_focus()
216 historical_catergory_found = True
218 if not historical_catergory_found:
219 print "Couldn't find saved category, using default."
220 #If historical records were not kept then default to
221 # put the focus on the first category
222 self._categoryView.set_cursor(0, self._categoryColumn, False)
223 self._categoryView.grab_focus()
225 self._select_default_unit()
227 def _save_settings(self):
229 This routine saves the selections to a file, and
230 should therefore only be called when exiting the program.
232 Update selections dictionary which consists of the following keys:
233 'self._selectedCategoryName': full name of selected category
234 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
235 [categoryname: #1 displayed unit, #2 displayed unit]
237 #Determine the contents of the selected category row
238 selected, iter = self._categoryView.get_selection().get_selected()
239 self._selectedCategoryName = self._categoryModel.get_value(iter, 0)
242 'selected_category': self._selectedCategoryName,
243 'selected_units': self._defaultUnitForCategory
245 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
246 pickle.dump(selections, open(selectionsDatPath, 'w'))
248 #Get last size of app and save it
250 'size': self._mainWindow.get_size()
252 windowDatPath = "/".join((constants._data_path_, "window.dat"))
253 pickle.dump(window_settings, open(windowDatPath, 'w'))
255 def _clear_find(self):
256 # switch to "new find" state
257 self._find_result = []
260 # Clear our user message
261 self._findLabel.set_text('')
263 def _find_first(self):
264 assert len(self._find_result) == 0
265 assert self._findIndex == 0
266 findString = string.lower(string.strip(self._findEntry.get_text()))
270 # Gather info on all the matching units from all categories
271 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
272 units = unit_data.get_units(category)
273 for unitIndex, unit in enumerate(units):
274 loweredUnit = unit.lower()
275 if loweredUnit in findString or findString in loweredUnit:
276 self._find_result.append((category, unit, catIndex, unitIndex))
278 def _update_find_selection(self):
279 assert 0 < len(self._find_result)
281 #check if next find is in a new category (prevent category changes when unnecessary
282 if self._selectedCategoryName != self._find_result[self._findIndex][0]:
283 self._categoryView.set_cursor(
284 self._find_result[self._findIndex][2], self._categoryColumn, False
287 self._unitsView.set_cursor(
288 self._find_result[self._findIndex][3], self._unitNameColumn, True
291 def _find_next(self):
293 check if 'new find' or 'last find' or 'next-find'
295 new-find = run the find algorithm which also selects the first found unit
296 = self._findIndex = 0 and self._find_result = []
298 last-find = restart from top again
299 = self._findIndex = len(self._find_result)
301 next-find = continue to next found location
302 = self._findIndex = 0 and len(self._find_result)>0
304 if len(self._find_result) == 0:
307 if self._findIndex == len(self._find_result)-1:
312 if not self._find_result:
313 self._findLabel.set_text('Text not found')
315 self._update_find_selection()
316 resultsLeft = len(self._find_result) - self._findIndex - 1
317 self._findLabel.set_text(
318 '%s result(s) left' % (resultsLeft, )
321 def _find_previous(self):
323 check if 'new find' or 'last find' or 'next-find'
325 new-find = run the find algorithm which also selects the first found unit
326 = self._findIndex = 0 and self._find_result = []
328 last-find = restart from top again
329 = self._findIndex = len(self._find_result)
331 next-find = continue to next found location
332 = self._findIndex = 0 and len(self._find_result)>0
334 if len(self._find_result) == 0:
337 if self._findIndex == 0:
338 self._findIndex = len(self._find_result)-1
342 if not self._find_result:
343 self._findLabel.set_text('Text not found')
345 self._update_find_selection()
346 resultsLeft = len(self._find_result) - self._findIndex - 1
347 self._findLabel.set_text(
348 '%s result(s) left' % (resultsLeft, )
351 def _toggle_find(self):
352 if self._searchLayout.get_property("visible"):
353 self._searchLayout.hide()
355 self._searchLayout.show()
357 def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
358 leftUnitText = self._unitModel.get_value(leftItr, 0)
359 rightUnitText = self._unitModel.get_value(rightItr, 0)
360 return cmp(leftUnitText, rightUnitText)
362 def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
363 leftSymbolText = self._unitModel.get_value(leftItr, 2)
364 rightSymbolText = self._unitModel.get_value(rightItr, 2)
365 return cmp(leftSymbolText, rightSymbolText)
367 def _value_model_cmp(self, sortedModel, leftItr, rightItr):
368 #special sorting exceptions for ascii values (instead of float values)
369 if self._selectedCategoryName == "Computer Numbers":
370 leftValue = self._unitModel.get_value(leftItr, 1)
371 rightValue = self._unitModel.get_value(rightItr, 1)
373 leftValueText = self._unitModel.get_value(leftItr, 1)
374 leftValue = float(leftValueText) if leftValueText else 0.0
376 rightValueText = self._unitModel.get_value(rightItr, 1)
377 rightValue = float(rightValueText) if rightValueText else 0.0
378 return cmp(leftValue, rightValue)
380 def _get_column_sort_stuff(self):
382 (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
383 (self._unitValueColumn, "_value_sort_direction", self._value_model_cmp),
384 (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
388 def _switch_category(self, category):
389 self._selectedCategoryName = category
390 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategoryName]
392 #Fill up the units descriptions and clear the value cells
393 self._clear_visible_unit_data()
394 for key in unit_data.get_units(self._selectedCategoryName):
395 iter = self._unitModel.append()
396 self._unitModel.set(iter, 0, key, 1, '', 2, self._unitDataInCategory[key][1])
397 self._sortedUnitModel.sort_column_changed()
399 self._select_default_unit()
401 def _clear_visible_unit_data(self):
402 self._unitDescription.get_buffer().set_text("")
403 self._unitName.set_text('')
404 self._unitValue.set_text('')
405 self._unitSymbol.set_text('')
407 self._previousUnitName.set_text('')
408 self._previousUnitValue.set_text('')
409 self._previousUnitSymbol.set_text('')
411 self._unitModel.clear()
413 def _select_default_unit(self):
414 # Restore the previous historical settings of previously selected units
415 # in this newly selected category
416 defaultPrimary = unit_data.get_base_unit(self._selectedCategoryName)
417 defaultSecondary = ""
418 if self._selectedCategoryName in self._defaultUnitForCategory:
419 if self._defaultUnitForCategory[self._selectedCategoryName][0]:
420 defaultPrimary = self._defaultUnitForCategory[self._selectedCategoryName][0]
421 if self._defaultUnitForCategory[self._selectedCategoryName][1]:
422 defaultSecondary = self._defaultUnitForCategory[self._selectedCategoryName][1]
424 units = unit_data.get_units(self._selectedCategoryName)
426 #Restore oldest selection first.
428 unitIndex = units.index(defaultPrimary)
429 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
431 #Restore newest selection second.
433 unitIndex = units.index(defaultSecondary)
434 self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
436 # select the text so user can start typing right away
437 self._unitValue.grab_focus()
438 self._unitValue.select_region(0, -1)
440 def _sanitize_value(self, userEntry):
441 if self._selectedCategoryName == "Computer Numbers":
450 value = float(userEntry)
453 def _on_shortlist_changed(self, *args):
455 raise NotImplementedError("%s" % self._shortlistcheck.get_active())
457 _moduleLogger.exception("")
459 def _on_edit_shortlist(self, *args):
461 raise NotImplementedError("%s" % self._toggleShortList.get_active())
463 _moduleLogger.exception("")
465 def _on_user_clear_selections(self, *args):
467 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
468 os.remove(selectionsDatPath)
469 self._defaultUnitForCategory = {}
471 _moduleLogger.exception("")
473 def _on_key_press(self, widget, event, *args):
475 @note Hildon specific
477 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
480 event.keyval == gtk.keysyms.F6 or
481 event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
483 if self._isFullScreen:
484 self._mainWindow.unfullscreen()
486 self._mainWindow.fullscreen()
487 elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
489 elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
490 self._find_previous()
491 elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
494 _moduleLogger.exception("")
496 def _on_window_state_change(self, widget, event, *args):
498 @note Hildon specific
501 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
502 self._isFullScreen = True
504 self._isFullScreen = False
506 _moduleLogger.exception("")
508 def _on_findEntry_changed(self, *args):
510 Clear out find results since the user wants to look for something new
515 _moduleLogger.exception("")
517 def _on_find_activate(self, *args):
520 self._findButton.grab_focus()
522 _moduleLogger.exception("")
524 def _on_click_unit_column(self, col):
526 Sort the contents of the col when the user clicks on the title.
529 #Determine which column requires sorting
530 columns = self._get_column_sort_stuff()
531 for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
533 direction = getattr(self, directionName)
534 gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
537 self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
539 # set the visual for sorting
540 col.set_sort_indicator(True)
541 col.set_sort_order(not direction)
543 setattr(self, directionName, not direction)
546 maybeCol.set_sort_indicator(False)
548 assert False, "Unknown column: %s" % (col.get_title(), )
550 _moduleLogger.exception("")
552 def _on_click_category(self, *args):
554 selected, iter = self._categoryView.get_selection().get_selected()
556 # User is typing in an invalid string, not selecting any category
558 selectedCategory = self._categoryModel.get_value(iter, 0)
559 self._switch_category(selectedCategory)
561 _moduleLogger.exception("")
563 def _on_click_unit(self, *args):
565 selected, iter = self._unitsView.get_selection().get_selected()
566 selected_unit = selected.get_value(iter, 0)
567 unit_spec = self._unitDataInCategory[selected_unit]
569 if self._unitName.get_text() != selected_unit:
570 self._previousUnitName.set_text(self._unitName.get_text())
571 self._previousUnitValue.set_text(self._unitValue.get_text())
572 self._previousUnitSymbol.set_text(self._unitSymbol.get())
574 self._unitName.set_text(selected_unit)
575 self._unitValue.set_text(selected.get_value(iter, 1))
576 buffer = self._unitDescription.get_buffer()
577 buffer.set_text(unit_spec[2])
578 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
580 if self._unitValue.get_text() == '':
581 if self._selectedCategoryName == "Computer Numbers":
582 self._unitValue.set_text("0")
584 self._unitValue.set_text("0.0")
586 self._defaultUnitForCategory[self._selectedCategoryName] = [
587 self._unitName.get_text(), self._previousUnitName.get_text()
590 # select the text so user can start typing right away
591 self._unitValue.grab_focus()
592 self._unitValue.select_region(0, -1)
594 _moduleLogger.exception("")
596 def _on_unit_value_changed(self, *args):
598 if self._unitName.get_text() == '':
600 if not self._unitValue.is_focus():
603 #retrieve the conversion function and value from the selected unit
604 value = self._sanitize_value(self._unitValue.get_text())
605 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
606 base = func.to_base(value, arg)
608 #point to the first row
609 for row in self._unitModel:
610 func, arg = self._unitDataInCategory[row[0]][0]
611 row[1] = str(func.from_base(base, arg))
613 # Update the secondary unit entry
614 if self._previousUnitName.get_text() != '':
615 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
616 self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
618 _moduleLogger.exception("")
620 def _on_previous_unit_value_changed(self, *args):
622 if self._previousUnitName.get_text() == '':
624 if not self._previousUnitValue.is_focus():
627 #retrieve the conversion function and value from the selected unit
628 value = self._sanitize_value(self._previousUnitValue.get_text())
629 func, arg = self._unitDataInCategory[self._previousUnitName.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 primary unit entry
638 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
639 self._unitValue.set_text(str(func.from_base(base, arg, )))
641 _moduleLogger.exception("")
643 def _on_about_clicked(self, a):
644 dlg = gtk.AboutDialog()
645 dlg.set_name(constants.__pretty_app_name__)
646 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
647 dlg.set_copyright("Copyright 2009 - GPL")
649 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
650 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
654 def _on_user_exit(self, *args):
656 self._save_settings()
658 _moduleLogger.exception("")
664 logging.basicConfig(level = logging.DEBUG)
666 os.makedirs(constants._data_path_)
675 if __name__ == "__main__":