Favorites support
[gonvert] / src / gonvert_glade.py
1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
3
4 from __future__ import with_statement
5
6 import os
7 import math
8 import pickle
9 import logging
10
11 import pango
12 import gobject
13 import gtk
14 import gtk.glade
15 import gtk.gdk
16
17 import constants
18 import hildonize
19 import gtk_toolbox
20 import unit_data
21
22 try:
23         import gettext
24 except ImportError:
25         _ = lambda x: x
26         gettext = None
27 else:
28         _ = gettext.gettext
29
30
31 _moduleLogger = logging.getLogger("gonvert_glade")
32
33 if gettext is not None:
34         gettext.bindtextdomain('gonvert', '/usr/share/locale')
35         gettext.textdomain('gonvert')
36
37
38 def change_menu_label(widgets, labelname, newtext):
39         item_label = widgets.get_widget(labelname).get_children()[0]
40         item_label.set_text(newtext)
41
42
43 def split_number(number):
44         try:
45                 fractional, integer = math.modf(number)
46         except TypeError:
47                 integerDisplay = number
48                 fractionalDisplay = ""
49         else:
50                 integerDisplay = str(integer)
51                 fractionalDisplay = str(fractional)
52                 if "e+" in integerDisplay:
53                         integerDisplay = number
54                         fractionalDisplay = ""
55                 elif "e-" in fractionalDisplay and 0.0 < integer:
56                         integerDisplay = number
57                         fractionalDisplay = ""
58                 elif "e-" in fractionalDisplay:
59                         integerDisplay = ""
60                         fractionalDisplay = number
61                 else:
62                         integerDisplay = integerDisplay.split(".", 1)[0] + "."
63                         fractionalDisplay = fractionalDisplay.rsplit(".", 1)[-1]
64
65         return integerDisplay, fractionalDisplay
66
67
68 class Gonvert(object):
69
70         _glade_files = [
71                 os.path.join(os.path.dirname(__file__), "gonvert.glade"),
72                 os.path.join(os.path.dirname(__file__), "../data/gonvert.glade"),
73                 os.path.join(os.path.dirname(__file__), "../lib/gonvert.glade"),
74                 '/usr/share/gonvert/gonvert.glade',
75                 '/usr/lib/gonvert/gonvert.glade',
76         ]
77
78         UNITS_NAME_IDX = 0
79         UNITS_VALUE_IDX = 1
80         UNITS_SYMBOL_IDX = 2
81         UNITS_INTEGER_IDX = 3
82         UNITS_FRACTION_IDX = 4
83
84         def __init__(self):
85                 self._unitDataInCategory = None
86                 self._unit_sort_direction = False
87                 self._value_sort_direction = False
88                 self._units_sort_direction = False
89                 self.__isPortrait = False
90                 self._isFullScreen = False
91                 self._clipboard = gtk.clipboard_get()
92
93                 self._find_result = [] # empty find result list
94                 self._findIndex = 0 # default to find result number zero
95
96                 self._selectedCategoryName = '' # preset to no selected category
97                 self._defaultUnitForCategory = {} # empty dictionary for later use
98
99                 #check to see if glade file is in current directory (user must be
100                 # running from download untar directory)
101                 for gladePath in self._glade_files:
102                         if os.path.isfile(gladePath):
103                                 homepath = os.path.dirname(gladePath)
104                                 pixmapspath = "/".join((homepath, "pixmaps"))
105                                 widgets = gtk.glade.XML(gladePath)
106                                 break
107                 else:
108                         _moduleLogger.error("UI Descriptor not found!")
109                         gtk.main_quit()
110                         return
111
112                 self._mainWindow = widgets.get_widget('mainWindow')
113                 self._app = hildonize.get_app_class()()
114                 self._mainWindow = hildonize.hildonize_window(self._app, self._mainWindow)
115
116                 change_menu_label(widgets, 'fileMenuItem', _('File'))
117                 change_menu_label(widgets, 'exitMenuItem', _('Exit'))
118                 change_menu_label(widgets, 'helpMenuItem', _('Help'))
119                 change_menu_label(widgets, 'aboutMenuItem', _('About'))
120
121                 self._categorySelectionButton = widgets.get_widget("categorySelectionButton")
122                 self._categoryView = widgets.get_widget('categoryView')
123
124                 self._unitsView = widgets.get_widget('unitsView')
125                 self._unitsView.set_property('rules_hint', 1)
126                 self._unitsView_selection = self._unitsView.get_selection()
127
128                 self._unitName = widgets.get_widget('unitName')
129                 self._unitValue = widgets.get_widget('unitValue')
130                 self._previousUnitName = widgets.get_widget('previousUnitName')
131                 self._previousUnitValue = widgets.get_widget('previousUnitValue')
132
133                 self._unitSymbol = widgets.get_widget('unitSymbol')
134                 self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
135
136                 self._unitDescription = widgets.get_widget('unitDescription')
137
138                 self._searchLayout = widgets.get_widget('searchLayout')
139                 self._searchLayout.hide()
140                 self._findEntry = widgets.get_widget('findEntry')
141                 self._findLabel = widgets.get_widget('findLabel')
142                 self._findButton = widgets.get_widget('findButton')
143                 self._closeSearchButton = widgets.get_widget('closeSearchButton')
144
145                 self._unitsNameRenderer = gtk.CellRendererText()
146                 self._unitsNameRenderer.set_property("scale", 0.75)
147                 if constants.FORCE_HILDON_LIKE:
148                         self._unitsNameRenderer.set_property("ellipsize", pango.ELLIPSIZE_END)
149                         self._unitsNameRenderer.set_property("width-chars", 5)
150                 self._unitNameColumn = gtk.TreeViewColumn(_('Name'), self._unitsNameRenderer)
151                 self._unitNameColumn.set_property('resizable', True)
152                 self._unitNameColumn.add_attribute(self._unitsNameRenderer, 'text', self.UNITS_NAME_IDX)
153                 self._unitNameColumn.set_clickable(True)
154                 self._unitNameColumn.connect("clicked", self._on_click_unit_column)
155                 self._unitsView.append_column(self._unitNameColumn)
156
157                 renderer = gtk.CellRendererText()
158                 renderer.set_property("xalign", 1.0)
159                 renderer.set_property("alignment", pango.ALIGN_RIGHT)
160                 hildonize.set_cell_thumb_selectable(renderer)
161                 self._unitIntegerColumn = gtk.TreeViewColumn(_('Value'), renderer)
162                 self._unitIntegerColumn.set_property('resizable', True)
163                 self._unitIntegerColumn.add_attribute(renderer, 'text', self.UNITS_INTEGER_IDX)
164                 self._unitIntegerColumn.set_clickable(True)
165                 self._unitIntegerColumn.connect("clicked", self._on_click_unit_column)
166                 self._unitsView.append_column(self._unitIntegerColumn)
167
168                 renderer = gtk.CellRendererText()
169                 renderer.set_property("xalign", 0.0)
170                 renderer.set_property("alignment", pango.ALIGN_LEFT)
171                 renderer.set_property("scale", 0.75)
172                 self._unitFractionalColumn = gtk.TreeViewColumn(_(''), renderer)
173                 self._unitFractionalColumn.set_property('resizable', True)
174                 self._unitFractionalColumn.add_attribute(renderer, 'text', self.UNITS_FRACTION_IDX)
175                 self._unitFractionalColumn.set_clickable(True)
176                 self._unitFractionalColumn.connect("clicked", self._on_click_unit_column)
177                 self._unitsView.append_column(self._unitFractionalColumn)
178
179                 renderer = gtk.CellRendererText()
180                 renderer.set_property("ellipsize", pango.ELLIPSIZE_END)
181                 #renderer.set_property("scale", 0.5)
182                 self._unitSymbolColumn = gtk.TreeViewColumn(_('Units'), renderer)
183                 self._unitSymbolColumn.set_property('resizable', True)
184                 self._unitSymbolColumn.add_attribute(renderer, 'text', self.UNITS_SYMBOL_IDX)
185                 self._unitSymbolColumn.set_clickable(True)
186                 self._unitSymbolColumn.connect("clicked", self._on_click_unit_column)
187                 self._unitsView.append_column(self._unitSymbolColumn)
188
189                 self._unitModel = gtk.ListStore(
190                         gobject.TYPE_STRING, # UNITS_NAME_IDX
191                         gobject.TYPE_STRING, # UNITS_VALUE_IDX
192                         gobject.TYPE_STRING, # UNITS_SYMBOL_IDX
193                         gobject.TYPE_STRING, # UNITS_INTEGER_IDX
194                         gobject.TYPE_STRING, # UNITS_FRACTION_IDX
195                 )
196                 self._sortedUnitModel = gtk.TreeModelSort(self._unitModel)
197                 columns = self._get_column_sort_stuff()
198                 for columnIndex, (column, sortDirection, col_cmp) in enumerate(columns):
199                         self._sortedUnitModel.set_sort_func(columnIndex, col_cmp)
200                 self._unitsView.set_model(self._sortedUnitModel)
201
202                 #Insert a column into the category list even though the heading will not be seen
203                 renderer = gtk.CellRendererText()
204                 self._categoryColumn = gtk.TreeViewColumn('Title', renderer)
205                 self._categoryColumn.set_property('resizable', 1)
206                 self._categoryColumn.add_attribute(renderer, 'text', 0)
207                 self._categoryView.append_column(self._categoryColumn)
208
209                 self._categoryModel = gtk.ListStore(gobject.TYPE_STRING)
210                 self._categoryView.set_model(self._categoryModel)
211                 #colourize each row differently for easier reading
212                 self._categoryView.set_property('rules_hint', 1)
213
214                 #Populate the catagories list
215                 for key in unit_data.UNIT_CATEGORIES:
216                         row = (key, )
217                         self._categoryModel.append(row)
218
219                 #--------- connections to GUI ----------------
220                 self._mainWindow.connect("destroy", self._on_user_exit)
221                 self._mainWindow.connect("key-press-event", self._on_key_press)
222                 self._mainWindow.connect("window-state-event", self._on_window_state_change)
223                 self._categorySelectionButton.connect("clicked", self._on_category_selector_clicked)
224                 self._categoryView.connect("cursor-changed", self._on_click_category)
225                 self._findButton.connect("clicked", self._on_find_activate)
226                 self._findEntry.connect("activate", self._on_find_activate)
227                 self._findEntry.connect("changed", self._on_findEntry_changed)
228                 self._closeSearchButton.connect("clicked", self._on_toggle_search)
229                 self._previousUnitValue.connect("changed", self._on_previous_unit_value_changed)
230                 self._unitValue.connect("changed", self._on_unit_value_changed)
231                 self._unitValue.connect("key-press-event", self._on_browse_key_press)
232                 self._unitsView.connect("cursor-changed", self._on_click_unit)
233                 self._unitsView.connect("key-press-event", self._on_browse_key_press)
234                 if hildonize.GTK_MENU_USED:
235                         widgets.get_widget("aboutMenuItem").connect("activate", self._on_about_clicked)
236                         widgets.get_widget("searchMenuItem").connect("activate", self._on_toggle_search)
237                         widgets.get_widget("exitMenuItem").connect("activate", self._on_user_exit)
238
239                 for scrollingWidgetName in (
240                         "unitsViewScrolledWindow",
241                 ):
242                         scrollingWidget = widgets.get_widget(scrollingWidgetName)
243                         assert scrollingWidget is not None, scrollingWidgetName
244                         scroller = hildonize.hildonize_scrollwindow(scrollingWidget)
245                         scroller.show_all()
246
247                 # Simplify the UI
248                 if hildonize.IS_HILDON_SUPPORTED or constants.FORCE_HILDON_LIKE:
249                         self._categoryView.get_parent().hide()
250                         self._unitsView.set_headers_visible(False)
251                         self._previousUnitName.get_parent().hide()
252                         self._unitDescription.get_parent().get_parent().hide()
253                 else:
254                         self._categorySelectionButton.hide()
255
256                 menu = hildonize.hildonize_menu(
257                         self._mainWindow,
258                         widgets.get_widget("mainMenuBar"),
259                 )
260                 if not hildonize.GTK_MENU_USED:
261                         button = gtk.Button("Search")
262                         button.connect("clicked", self._on_toggle_search)
263                         menu.append(button)
264
265                         button = hildonize.hildon.GtkRadioButton(gtk.HILDON_SIZE_AUTO, None)
266                         button.set_label("Name")
267                         menu.add_filter(button)
268                         button.connect("clicked", self._on_click_menu_filter, self._unitNameColumn)
269                         button.set_mode(False)
270                         filterGroup = button
271
272                         button = hildonize.hildon.GtkRadioButton(gtk.HILDON_SIZE_AUTO, filterGroup)
273                         button.set_label("Value")
274                         menu.add_filter(button)
275                         button.connect("clicked", self._on_click_menu_filter, self._unitIntegerColumn)
276                         button.set_mode(False)
277
278                         button = hildonize.hildon.GtkRadioButton(gtk.HILDON_SIZE_AUTO, filterGroup)
279                         button.set_label("Unit")
280                         menu.add_filter(button)
281                         button.connect("clicked", self._on_click_menu_filter, self._unitSymbolColumn)
282                         button.set_mode(False)
283
284                         menu.show_all()
285
286                 if not hildonize.IS_HILDON_SUPPORTED:
287                         _moduleLogger.info("No hildonization support")
288
289                 hildonize.set_application_name(
290                         "%s - Unit Conversion Utility" % constants.__pretty_app_name__
291                 )
292                 iconPath = pixmapspath + '/gonvert.png'
293                 if os.path.exists(iconPath):
294                         self._mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
295                 else:
296                         _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
297
298                 self._load_settings()
299                 self._mainWindow.show()
300
301         def _load_settings(self):
302                 #Restore window size from previously saved settings if it exists and is valid.
303                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
304                 if os.path.exists(windowDatPath):
305                         saved_window = pickle.load(open(windowDatPath, "r"))
306                         try:
307                                 a, b = saved_window['size']
308                         except KeyError:
309                                 pass
310                         else:
311                                 self._mainWindow.resize(a, b)
312                         try:
313                                 isFullscreen = saved_window["isFullscreen"]
314                         except KeyError:
315                                 pass
316                         else:
317                                 if isFullscreen:
318                                         self._mainWindow.fullscreen()
319                         try:
320                                 isPortrait = saved_window["isPortrait"]
321                         except KeyError:
322                                 pass
323                         else:
324                                 if isPortrait ^ self.__isPortrait:
325                                         if isPortrait:
326                                                 orientation = gtk.ORIENTATION_VERTICAL
327                                         else:
328                                                 orientation = gtk.ORIENTATION_HORIZONTAL
329                                         self.set_orientation(orientation)
330
331                 #Restore selections from previously saved settings if it exists and is valid.
332                 categoryIndex = 0
333                 selectedCategoryName = unit_data.UNIT_CATEGORIES[0]
334                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
335                 if os.path.exists(selectionsDatPath):
336                         selections = pickle.load(open(selectionsDatPath, 'r'))
337                         try:
338                                 self._defaultUnitForCategory = selections['selected_units']
339                         except KeyError:
340                                 pass
341
342                         try:
343                                 selectedCategoryName = selections['selected_category']
344                         except KeyError:
345                                 pass
346                         else:
347                                 try:
348                                         categoryIndex = unit_data.UNIT_CATEGORIES.index(selectedCategoryName)
349                                 except ValueError:
350                                         _moduleLogger.warn("Unknown category: %s" % selectedCategoryName)
351
352                 self._categorySelectionButton.get_child().set_markup("<big>%s</big>" % selectedCategoryName)
353                 self._categoryView.set_cursor(categoryIndex, self._categoryColumn, False)
354                 self._categoryView.grab_focus()
355
356                 self._select_default_unit()
357
358         def _save_settings(self):
359                 """
360                 This routine saves the selections to a file, and
361                 should therefore only be called when exiting the program.
362
363                 Update selections dictionary which consists of the following keys:
364                 'self._selectedCategoryName': full name of selected category
365                 'self._defaultUnitForCategory': self._defaultUnitForCategory dictionary which contains:
366                 [categoryname: #1 displayed unit, #2 displayed unit]
367                 """
368                 #Determine the contents of the selected category row
369                 selected, iter = self._categoryView.get_selection().get_selected()
370                 self._selectedCategoryName = self._categoryModel.get_value(iter, 0)
371
372                 selections = {
373                         'selected_category': self._selectedCategoryName,
374                         'selected_units': self._defaultUnitForCategory
375                 }
376                 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
377                 pickle.dump(selections, open(selectionsDatPath, 'w'))
378
379                 #Get last size of app and save it
380                 window_settings = {
381                         'size': self._mainWindow.get_size(),
382                         "isFullscreen": self._isFullScreen,
383                         "isPortrait": self.__isPortrait,
384                 }
385                 windowDatPath = "/".join((constants._data_path_, "window.dat"))
386                 pickle.dump(window_settings, open(windowDatPath, 'w'))
387
388         def _refresh_columns(self):
389                 self._unitsView.remove_column(self._unitNameColumn)
390                 self._unitsView.remove_column(self._unitIntegerColumn)
391                 self._unitsView.remove_column(self._unitFractionalColumn)
392                 self._unitsView.remove_column(self._unitSymbolColumn)
393
394                 self._unitsView.append_column(self._unitNameColumn)
395                 self._unitsView.append_column(self._unitIntegerColumn)
396                 self._unitsView.append_column(self._unitFractionalColumn)
397                 self._unitsView.append_column(self._unitSymbolColumn)
398
399         def _clear_find(self):
400                 # switch to "new find" state
401                 self._find_result = []
402                 self._findIndex = 0
403
404                 # Clear our user message
405                 self._findLabel.set_text('')
406
407         def _find_first(self):
408                 assert len(self._find_result) == 0
409                 assert self._findIndex == 0
410                 findString = self._findEntry.get_text().strip().lower()
411                 if not findString:
412                         return
413
414                 # Gather info on all the matching units from all categories
415                 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
416                         units = unit_data.get_units(category)
417                         for unitIndex, unit in enumerate(units):
418                                 loweredUnit = unit.lower()
419                                 if loweredUnit in findString or findString in loweredUnit:
420                                         self._find_result.append((category, unit, catIndex, unitIndex))
421
422         def _update_find_selection(self):
423                 assert 0 < len(self._find_result)
424
425                 #check if next find is in a new category (prevent category changes when unnecessary
426                 searchCategoryName = self._find_result[self._findIndex][0]
427                 if self._selectedCategoryName != searchCategoryName:
428                         self._categorySelectionButton.get_child().set_markup("<big>%s</big>" % searchCategoryName)
429                         self._categoryView.set_cursor(
430                                 self._find_result[self._findIndex][2], self._categoryColumn, False
431                         )
432
433                 self._unitsView.set_cursor(
434                         self._find_result[self._findIndex][3], self._unitNameColumn, True
435                 )
436
437         def _find_next(self):
438                 if len(self._find_result) == 0:
439                         self._find_first()
440                 else:
441                         if self._findIndex == len(self._find_result)-1:
442                                 self._findIndex = 0
443                         else:
444                                 self._findIndex += 1
445
446                 if not self._find_result:
447                         self._findLabel.set_text('Text not found')
448                 else:
449                         self._update_find_selection()
450                         resultsLeft = len(self._find_result) - self._findIndex - 1
451                         self._findLabel.set_text(
452                                 '%s result(s) left' % (resultsLeft, )
453                         )
454
455         def _find_previous(self):
456                 if len(self._find_result) == 0:
457                         self._find_first()
458                 else:
459                         if self._findIndex == 0:
460                                 self._findIndex = len(self._find_result)-1
461                         else:
462                                 self._findIndex -= 1
463
464                 if not self._find_result:
465                         self._findLabel.set_text('Text not found')
466                 else:
467                         self._update_find_selection()
468                         resultsLeft = len(self._find_result) - self._findIndex - 1
469                         self._findLabel.set_text(
470                                 '%s result(s) left' % (resultsLeft, )
471                         )
472
473         def _toggle_find(self):
474                 if self._searchLayout.get_property("visible"):
475                         self._searchLayout.hide()
476                         self._unitsView.grab_focus()
477                 else:
478                         self._searchLayout.show()
479                         self._findEntry.grab_focus()
480
481         def _unit_model_cmp(self, sortedModel, leftItr, rightItr):
482                 leftUnitText = self._unitModel.get_value(leftItr, self.UNITS_NAME_IDX)
483                 rightUnitText = self._unitModel.get_value(rightItr, self.UNITS_NAME_IDX)
484                 return cmp(leftUnitText, rightUnitText)
485
486         def _symbol_model_cmp(self, sortedModel, leftItr, rightItr):
487                 leftSymbolText = self._unitModel.get_value(leftItr, self.UNITS_SYMBOL_IDX)
488                 rightSymbolText = self._unitModel.get_value(rightItr, self.UNITS_SYMBOL_IDX)
489                 return cmp(leftSymbolText, rightSymbolText)
490
491         def _value_model_cmp(self, sortedModel, leftItr, rightItr):
492                 #special sorting exceptions for ascii values (instead of float values)
493                 if self._selectedCategoryName == "Computer Numbers":
494                         leftValue = self._unitModel.get_value(leftItr, self.UNITS_VALUE_IDX)
495                         rightValue = self._unitModel.get_value(rightItr, self.UNITS_VALUE_IDX)
496                 else:
497                         leftValueText = self._unitModel.get_value(leftItr, self.UNITS_VALUE_IDX)
498                         leftValue = float(leftValueText) if leftValueText else 0.0
499
500                         rightValueText = self._unitModel.get_value(rightItr, self.UNITS_VALUE_IDX)
501                         rightValue = float(rightValueText) if rightValueText else 0.0
502                 return cmp(leftValue, rightValue)
503
504         def _get_column_sort_stuff(self):
505                 columns = (
506                         (self._unitNameColumn, "_unit_sort_direction", self._unit_model_cmp),
507                         (self._unitIntegerColumn, "_value_sort_direction", self._value_model_cmp),
508                         (self._unitFractionalColumn, "_value_sort_direction", self._value_model_cmp),
509                         (self._unitSymbolColumn, "_units_sort_direction", self._symbol_model_cmp),
510                 )
511                 return columns
512
513         def _switch_category(self, category):
514                 self._selectedCategoryName = category
515                 self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[self._selectedCategoryName]
516
517                 #Fill up the units descriptions and clear the value cells
518                 self._clear_visible_unit_data()
519                 nameLength = 0
520                 for key in unit_data.get_units(self._selectedCategoryName):
521                         row = key, '0.0', self._unitDataInCategory[key][1], '0.', '0'
522                         self._unitModel.append(row)
523                         nameLength = max(nameLength, len(key))
524                 self._sortedUnitModel.sort_column_changed()
525
526                 if constants.FORCE_HILDON_LIKE:
527                         maxCatCharWidth = int(nameLength * 0.75)
528                         maxCharWidth = int(len("nibble | hexit | quadbit") * 0.75)
529                         charWidth = min(maxCatCharWidth, maxCharWidth)
530                         self._unitsNameRenderer.set_property("width-chars", charWidth)
531
532                 self._select_default_unit()
533
534         def _clear_visible_unit_data(self):
535                 self._unitDescription.get_buffer().set_text("")
536                 self._unitName.set_text('')
537                 self._unitValue.set_text('')
538                 self._unitSymbol.set_text('')
539
540                 self._previousUnitName.set_text('')
541                 self._previousUnitValue.set_text('')
542                 self._previousUnitSymbol.set_text('')
543
544                 self._unitModel.clear()
545
546         def _select_default_unit(self):
547                 # Restore the previous historical settings of previously selected units
548                 # in this newly selected category
549                 defaultPrimary = unit_data.get_base_unit(self._selectedCategoryName)
550                 defaultSecondary = ""
551                 if self._selectedCategoryName in self._defaultUnitForCategory:
552                         if self._defaultUnitForCategory[self._selectedCategoryName][0]:
553                                 defaultPrimary = self._defaultUnitForCategory[self._selectedCategoryName][0]
554                         if self._defaultUnitForCategory[self._selectedCategoryName][1]:
555                                 defaultSecondary = self._defaultUnitForCategory[self._selectedCategoryName][1]
556
557                 units = unit_data.get_units(self._selectedCategoryName)
558
559                 #Restore oldest selection first.
560                 if defaultPrimary:
561                         try:
562                                 unitIndex = units.index(defaultPrimary)
563                         except ValueError:
564                                 unitIndex = 0
565                         self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
566
567                 #Restore newest selection second.
568                 if defaultSecondary:
569                         try:
570                                 unitIndex = units.index(defaultSecondary)
571                         except ValueError:
572                                 unitIndex = 0
573                         self._unitsView.set_cursor(unitIndex, self._unitNameColumn, True)
574
575                 # select the text so user can start typing right away
576                 self._unitValue.grab_focus()
577                 self._unitValue.select_region(0, -1)
578
579         def _sanitize_value(self, userEntry):
580                 if self._selectedCategoryName == "Computer Numbers":
581                         if userEntry == '':
582                                 value = '0'
583                         else:
584                                 value = userEntry
585                 else:
586                         if userEntry == '':
587                                 value = 0.0
588                         else:
589                                 value = float(userEntry)
590                 return value
591
592         def _select_sort_column(self, col):
593                 #Determine which column requires sorting
594                 columns = self._get_column_sort_stuff()
595                 for columnIndex, (maybeCol, directionName, col_cmp) in enumerate(columns):
596                         if col is maybeCol:
597                                 direction = getattr(self, directionName)
598                                 gtkDirection = gtk.SORT_ASCENDING if direction else gtk.SORT_DESCENDING
599
600                                 # cause a sort
601                                 self._sortedUnitModel.set_sort_column_id(columnIndex, gtkDirection)
602
603                                 # set the visual for sorting
604                                 col.set_sort_indicator(True)
605                                 col.set_sort_order(not direction)
606
607                                 setattr(self, directionName, not direction)
608                                 break
609                         else:
610                                 maybeCol.set_sort_indicator(False)
611                 else:
612                         assert False, "Unknown column: %s" % (col.get_title(), )
613
614         def set_orientation(self, orientation):
615                 if orientation == gtk.ORIENTATION_VERTICAL:
616                         hildonize.window_to_portrait(self._mainWindow)
617                         self.__isPortrait = True
618                 elif orientation == gtk.ORIENTATION_HORIZONTAL:
619                         hildonize.window_to_landscape(self._mainWindow)
620                         self.__isPortrait = False
621                 else:
622                         raise NotImplementedError(orientation)
623
624         def get_orientation(self):
625                 return gtk.ORIENTATION_VERTICAL if self.__isPortrait else gtk.ORIENTATION_HORIZONTAL
626
627         def _toggle_rotate(self):
628                 if self.__isPortrait:
629                         self.set_orientation(gtk.ORIENTATION_HORIZONTAL)
630                 else:
631                         self.set_orientation(gtk.ORIENTATION_VERTICAL)
632
633         @gtk_toolbox.log_exception(_moduleLogger)
634         def _on_key_press(self, widget, event, *args):
635                 """
636                 @note Hildon specific
637                 """
638                 RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
639                 if (
640                         event.keyval == gtk.keysyms.F6 or
641                         event.keyval in RETURN_TYPES and event.get_state() & gtk.gdk.CONTROL_MASK
642                 ):
643                         if self._isFullScreen:
644                                 self._mainWindow.unfullscreen()
645                         else:
646                                 self._mainWindow.fullscreen()
647                 elif event.keyval == gtk.keysyms.f and event.get_state() & gtk.gdk.CONTROL_MASK:
648                         if not hildonize.GTK_MENU_USED:
649                                 self._toggle_find()
650                 elif event.keyval == gtk.keysyms.p and event.get_state() & gtk.gdk.CONTROL_MASK:
651                         self._find_previous()
652                 elif event.keyval == gtk.keysyms.n and event.get_state() & gtk.gdk.CONTROL_MASK:
653                         self._find_next()
654                 elif event.keyval == gtk.keysyms.o and event.get_state() & gtk.gdk.CONTROL_MASK:
655                         self._toggle_rotate()
656                 elif (
657                         event.keyval in (gtk.keysyms.w, gtk.keysyms.q) and
658                         event.get_state() & gtk.gdk.CONTROL_MASK
659                 ):
660                         self._mainWindow.destroy()
661                 elif event.keyval == gtk.keysyms.l and event.get_state() & gtk.gdk.CONTROL_MASK:
662                         with open(constants._user_logpath_, "r") as f:
663                                 logLines = f.xreadlines()
664                                 log = "".join(logLines)
665                                 self._clipboard.set_text(str(log))
666
667         @gtk_toolbox.log_exception(_moduleLogger)
668         def _on_toggle_search(self, *args):
669                 self._toggle_find()
670
671         @gtk_toolbox.log_exception(_moduleLogger)
672         def _on_browse_key_press(self, widget, event, *args):
673                 if event.keyval == gtk.keysyms.uparrow or event.keyval == gtk.keysyms.Up:
674                         index, column = self._unitsView.get_cursor()
675                         newIndex = max(index[0]-1, 0)
676                         path = (newIndex, )
677                         self._unitsView.set_cursor(path, column, True)
678                         self._unitsView.scroll_to_cell(path, column, False, 0, 0)
679                         return True # override default behavior
680                 elif event.keyval == gtk.keysyms.downarrow or event.keyval == gtk.keysyms.Down:
681                         index, column = self._unitsView.get_cursor()
682                         newIndex = min(index[0]+1, len(self._unitModel)-1)
683                         path = (newIndex, )
684                         self._unitsView.set_cursor(path, column, True)
685                         self._unitsView.scroll_to_cell(path, column, False, 0, 0)
686                         return True # override default behavior
687
688         @gtk_toolbox.log_exception(_moduleLogger)
689         def _on_window_state_change(self, widget, event, *args):
690                 """
691                 @note Hildon specific
692                 """
693                 if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
694                         self._isFullScreen = True
695                 else:
696                         self._isFullScreen = False
697
698         @gtk_toolbox.log_exception(_moduleLogger)
699         def _on_findEntry_changed(self, *args):
700                 """
701                 Clear out find results since the user wants to look for something new
702                 """
703                 self._clear_find()
704
705         @gtk_toolbox.log_exception(_moduleLogger)
706         def _on_find_activate(self, *args):
707                 self._find_next()
708                 self._findButton.grab_focus()
709
710         @gtk_toolbox.log_exception(_moduleLogger)
711         def _on_click_menu_filter(self, button, col):
712                 self._select_sort_column(col)
713
714         @gtk_toolbox.log_exception(_moduleLogger)
715         def _on_click_unit_column(self, col):
716                 """
717                 Sort the contents of the col when the user clicks on the title.
718                 """
719                 self._select_sort_column(col)
720
721         @gtk_toolbox.log_exception(_moduleLogger)
722         def _on_category_selector_clicked(self, *args):
723                 currenntIndex = unit_data.UNIT_CATEGORIES.index(self._selectedCategoryName)
724                 newIndex = hildonize.touch_selector(
725                         self._mainWindow,
726                         "Categories",
727                         unit_data.UNIT_CATEGORIES,
728                         currenntIndex,
729                 )
730
731                 selectedCategoryName = unit_data.UNIT_CATEGORIES[newIndex]
732                 self._categorySelectionButton.get_child().set_markup("<big>%s</big>" % selectedCategoryName)
733                 self._switch_category(selectedCategoryName)
734
735         @gtk_toolbox.log_exception(_moduleLogger)
736         def _on_click_category(self, *args):
737                 selected, iter = self._categoryView.get_selection().get_selected()
738                 if iter is None:
739                         # User is typing in an invalid string, not selecting any category
740                         return
741                 selectedCategory = self._categoryModel.get_value(iter, 0)
742                 self._switch_category(selectedCategory)
743
744         @gtk_toolbox.log_exception(_moduleLogger)
745         def _on_click_unit(self, *args):
746                 selected, iter = self._unitsView.get_selection().get_selected()
747                 selected_unit = selected.get_value(iter, self.UNITS_NAME_IDX)
748                 unit_spec = self._unitDataInCategory[selected_unit]
749
750                 showSymbol = False
751
752                 if self._unitName.get_text() != selected_unit:
753                         self._previousUnitName.set_text(self._unitName.get_text())
754                         self._previousUnitValue.set_text(self._unitValue.get_text())
755                         self._previousUnitSymbol.set_text(self._unitSymbol.get_text())
756                         if self._unitSymbol.get_text():
757                                 showSymbol = True
758
759                 self._unitName.set_text(selected_unit)
760                 self._unitValue.set_text(selected.get_value(iter, self.UNITS_VALUE_IDX))
761                 buffer = self._unitDescription.get_buffer()
762                 buffer.set_text(unit_spec[2])
763                 self._unitSymbol.set_text(unit_spec[1]) # put units into label text
764                 if unit_spec[1]:
765                         showSymbol = True
766                 else:
767                         showSymbol = False
768
769                 if showSymbol:
770                         self._unitSymbol.show()
771                         self._previousUnitSymbol.show()
772                 else:
773                         self._unitSymbol.hide()
774                         self._previousUnitSymbol.hide()
775
776                 if self._unitValue.get_text() == '':
777                         if self._selectedCategoryName == "Computer Numbers":
778                                 self._unitValue.set_text("0")
779                         else:
780                                 self._unitValue.set_text("0.0")
781
782                 self._defaultUnitForCategory[self._selectedCategoryName] = [
783                         self._unitName.get_text(), self._previousUnitName.get_text()
784                 ]
785
786                 # select the text so user can start typing right away
787                 self._unitValue.grab_focus()
788                 self._unitValue.select_region(0, -1)
789
790         @gtk_toolbox.log_exception(_moduleLogger)
791         def _on_unit_value_changed(self, *args):
792                 if self._unitName.get_text() == '':
793                         return
794                 if not self._unitValue.is_focus():
795                         return
796
797                 #retrieve the conversion function and value from the selected unit
798                 value = self._sanitize_value(self._unitValue.get_text())
799                 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
800                 base = func.to_base(value, arg)
801
802                 #point to the first row
803                 for row in self._unitModel:
804                         func, arg = self._unitDataInCategory[row[self.UNITS_NAME_IDX]][0]
805                         newValue = func.from_base(base, arg)
806
807                         newValueDisplay = str(newValue)
808                         integerDisplay, fractionalDisplay = split_number(newValue)
809
810                         row[self.UNITS_VALUE_IDX] = newValueDisplay
811                         row[self.UNITS_INTEGER_IDX] = integerDisplay
812                         row[self.UNITS_FRACTION_IDX] = fractionalDisplay
813
814                 # Update the secondary unit entry
815                 if self._previousUnitName.get_text() != '':
816                         func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
817                         self._previousUnitValue.set_text(str(func.from_base(base, arg, )))
818
819                 self._sortedUnitModel.sort_column_changed()
820                 self._refresh_columns()
821
822         @gtk_toolbox.log_exception(_moduleLogger)
823         def _on_previous_unit_value_changed(self, *args):
824                 if self._previousUnitName.get_text() == '':
825                         return
826                 if not self._previousUnitValue.is_focus():
827                         return
828
829                 #retrieve the conversion function and value from the selected unit
830                 value = self._sanitize_value(self._previousUnitValue.get_text())
831                 func, arg = self._unitDataInCategory[self._previousUnitName.get_text()][0]
832                 base = func.to_base(value, arg)
833
834                 #point to the first row
835                 for row in self._unitModel:
836                         func, arg = self._unitDataInCategory[row[self.UNITS_NAME_IDX]][0]
837                         newValue = func.from_base(base, arg)
838
839                         newValueDisplay = str(newValue)
840                         integerDisplay, fractionalDisplay = split_number(newValue)
841
842                         row[self.UNITS_VALUE_IDX] = newValueDisplay
843                         row[self.UNITS_INTEGER_IDX] = integerDisplay
844                         row[self.UNITS_FRACTION_IDX] = fractionalDisplay
845
846                 # Update the primary unit entry
847                 func, arg = self._unitDataInCategory[self._unitName.get_text()][0]
848                 self._unitValue.set_text(str(func.from_base(base, arg, )))
849
850                 self._sortedUnitModel.sort_column_changed()
851                 self._refresh_columns()
852
853         @gtk_toolbox.log_exception(_moduleLogger)
854         def _on_about_clicked(self, a):
855                 dlg = gtk.AboutDialog()
856                 dlg.set_name(constants.__pretty_app_name__)
857                 dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
858                 dlg.set_copyright("Copyright 2009 - GPL")
859                 dlg.set_comments("")
860                 dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
861                 dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <eopage@byu.net> (Blame him for the most recent bugs)"])
862                 dlg.run()
863                 dlg.destroy()
864
865         @gtk_toolbox.log_exception(_moduleLogger)
866         def _on_user_exit(self, *args):
867                 try:
868                         self._save_settings()
869                 except Exception:
870                         pass
871                 finally:
872                         gtk.main_quit()
873
874
875 def run_gonvert():
876         gtk.gdk.threads_init()
877         if hildonize.IS_HILDON_SUPPORTED:
878                 gtk.set_application_name(constants.__pretty_app_name__)
879         handle = Gonvert()
880         if not constants.PROFILE_STARTUP:
881                 gtk.main()
882
883
884 if __name__ == "__main__":
885         logging.basicConfig(level = logging.DEBUG)
886         try:
887                 os.makedirs(constants._data_path_)
888         except OSError, e:
889                 if e.errno != 17:
890                         raise
891
892         run_gonvert()