d1389314dcf68efe463f63ddd6590344d8d6d541
[gonvert] / src / gonvert_qt.py
1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
3
4 from __future__ import with_statement
5
6 import sys
7 import os
8 import math
9 import simplejson
10 import logging
11
12 from PyQt4 import QtGui
13 from PyQt4 import QtCore
14
15 import constants
16 import maeqt
17 from util import misc as misc_utils
18 import unit_data
19
20
21 _moduleLogger = logging.getLogger("gonvert_glade")
22
23
24 IS_MAEMO = True
25
26
27 def change_menu_label(widgets, labelname, newtext):
28         item_label = widgets.get_widget(labelname).get_children()[0]
29         item_label.set_text(newtext)
30
31
32 def split_number(number):
33         try:
34                 fractional, integer = math.modf(number)
35         except TypeError:
36                 integerDisplay = number
37                 fractionalDisplay = ""
38         else:
39                 integerDisplay = str(integer)
40                 fractionalDisplay = str(fractional)
41                 if "e+" in integerDisplay:
42                         integerDisplay = number
43                         fractionalDisplay = ""
44                 elif "e-" in fractionalDisplay and 0.0 < integer:
45                         integerDisplay = number
46                         fractionalDisplay = ""
47                 elif "e-" in fractionalDisplay:
48                         integerDisplay = ""
49                         fractionalDisplay = number
50                 else:
51                         integerDisplay = integerDisplay.split(".", 1)[0] + "."
52                         fractionalDisplay = fractionalDisplay.rsplit(".", 1)[-1]
53
54         return integerDisplay, fractionalDisplay
55
56
57 class Gonvert(object):
58
59         _DATA_PATHS = [
60                 os.path.dirname(__file__),
61                 os.path.join(os.path.dirname(__file__), "../share"),
62                 os.path.join(os.path.dirname(__file__), "../data"),
63                 '/usr/share/gonvert',
64                 '/opt/gonvert/share',
65         ]
66
67         def __init__(self, app):
68                 self._dataPath = ""
69                 for dataPath in self._DATA_PATHS:
70                         appIconPath = os.path.join(dataPath, "pixmaps", "gonvert.png")
71                         if os.path.isfile(appIconPath):
72                                 self._dataPath = dataPath
73                                 break
74                 else:
75                         raise RuntimeError("UI Descriptor not found!")
76                 self._app = app
77                 self._appIconPath = appIconPath
78                 self._recent = []
79                 self._hiddenCategories = set()
80                 self._hiddenUnits = {}
81                 self._clipboard = QtGui.QApplication.clipboard()
82
83                 self._jumpWindow = None
84                 self._recentWindow = None
85                 self._mainWindow = None
86                 self._catWindow = None
87                 self._quickWindow = None
88
89                 self._on_jump_close = lambda obj = None: self._on_child_close("_jumpWindow", obj)
90                 self._on_recent_close = lambda obj = None: self._on_child_close("_recentWindow", obj)
91                 self._on_cat_close = lambda obj = None: self._on_child_close("_catWindow", obj)
92                 self._on_quick_close = lambda obj = None: self._on_child_close("_quickWindow", obj)
93
94                 self._condensedAction = QtGui.QAction(None)
95                 self._condensedAction.setText("Condensed View")
96                 self._condensedAction.setCheckable(True)
97                 self._condensedAction.triggered.connect(self._on_condensed_start)
98
99                 self._jumpAction = QtGui.QAction(None)
100                 self._jumpAction.setText("Quick Jump")
101                 self._jumpAction.setStatusTip("Search for a unit and jump straight to it")
102                 self._jumpAction.setToolTip("Search for a unit and jump straight to it")
103                 self._jumpAction.setShortcut(QtGui.QKeySequence("CTRL+j"))
104                 self._jumpAction.triggered.connect(self._on_jump_start)
105
106                 self._recentAction = QtGui.QAction(None)
107                 self._recentAction.setText("Recent Units")
108                 self._recentAction.setStatusTip("View the recent units")
109                 self._recentAction.setToolTip("View the recent units")
110                 self._recentAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
111                 self._recentAction.triggered.connect(self._on_recent_start)
112
113                 self._fullscreenAction = QtGui.QAction(None)
114                 self._fullscreenAction.setText("Fullscreen")
115                 self._fullscreenAction.setCheckable(True)
116                 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
117                 self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
118
119                 self._showFavoritesAction = QtGui.QAction(None)
120                 self._showFavoritesAction.setCheckable(True)
121                 self._showFavoritesAction.setText("Favorites Only")
122
123                 self._sortActionGroup = QtGui.QActionGroup(None)
124                 self._sortByNameAction = QtGui.QAction(self._sortActionGroup)
125                 self._sortByNameAction.setText("Sort By Name")
126                 self._sortByNameAction.setStatusTip("Sort the units by name")
127                 self._sortByNameAction.setToolTip("Sort the units by name")
128                 self._sortByNameAction.setCheckable(True)
129                 self._sortByValueAction = QtGui.QAction(self._sortActionGroup)
130                 self._sortByValueAction.setText("Sort By Value")
131                 self._sortByValueAction.setStatusTip("Sort the units by value")
132                 self._sortByValueAction.setToolTip("Sort the units by value")
133                 self._sortByValueAction.setCheckable(True)
134                 self._sortByUnitAction = QtGui.QAction(self._sortActionGroup)
135                 self._sortByUnitAction.setText("Sort By Unit")
136                 self._sortByUnitAction.setStatusTip("Sort the units by unit")
137                 self._sortByUnitAction.setToolTip("Sort the units by unit")
138                 self._sortByUnitAction.setCheckable(True)
139
140                 self._sortByNameAction.setChecked(True)
141
142                 self._logAction = QtGui.QAction(None)
143                 self._logAction.setText("Log")
144                 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
145                 self._logAction.triggered.connect(self._on_log)
146
147                 self._quitAction = QtGui.QAction(None)
148                 self._quitAction.setText("Quit")
149                 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
150                 self._quitAction.triggered.connect(self._on_quit)
151
152                 self._app.lastWindowClosed.connect(self._on_app_quit)
153                 self.load_settings()
154
155                 self.request_category()
156                 if self._recent:
157                         self._mainWindow.select_category(self._recent[-1][0])
158
159         def request_category(self):
160
161                 if self._condensedAction.isChecked():
162                         if self._catWindow is not None:
163                                 self._catWindow.hide()
164
165                         if self._quickWindow is None:
166                                 self._quickWindow = QuickConvert(None, self)
167                                 self._quickWindow.window.destroyed.connect(self._on_quick_close)
168                         else:
169                                 self._quickWindow.show()
170
171                         self._mainWindow = self._quickWindow
172                 else:
173                         if self._quickWindow is not None:
174                                 self._quickWindow.hide()
175
176                         if self._catWindow is None:
177                                 self._catWindow = CategoryWindow(None, self)
178                                 self._catWindow.window.destroyed.connect(self._on_cat_close)
179                         else:
180                                 self._catWindow.window.show()
181
182                         self._mainWindow = self._catWindow
183
184                 return self._mainWindow
185
186         def search_units(self):
187                 jumpWindow = QuickJump(None, self)
188                 jumpWindow.window.destroyed.connect(self._on_jump_close)
189                 self._jumpWindow = jumpWindow
190                 return self._jumpWindow
191
192         def show_recent(self):
193                 recentWindow = Recent(None, self)
194                 recentWindow.window.destroyed.connect(self._on_recent_close)
195                 self._recentWindow = recentWindow
196                 return self._recentWindow
197
198         def add_recent(self, categoryName, unitName):
199                 catUnit = categoryName, unitName
200                 try:
201                         self._recent.remove(catUnit)
202                 except ValueError:
203                         pass # ignore if its not already in the recent history
204                 assert catUnit not in self._recent
205                 self._recent.append(catUnit)
206
207         def get_recent_unit(self, categoryName, fromMostRecent = 0):
208                 recentUnitName = ""
209                 for catName, unitName in reversed(self._recent):
210                         if catName == categoryName:
211                                 recentUnitName = unitName
212                                 if fromMostRecent <= 0:
213                                         break
214                                 else:
215                                         fromMostRecent -= 1
216                 return recentUnitName
217
218         def get_recent(self):
219                 return reversed(self._recent)
220
221         @property
222         def hiddenCategories(self):
223                 return self._hiddenCategories
224
225         def get_hidden_units(self, categoryName):
226                 try:
227                         return self._hiddenUnits[categoryName]
228                 except KeyError:
229                         self._hiddenUnits[categoryName] = set()
230                         return self._hiddenUnits[categoryName]
231
232         def load_settings(self):
233                 try:
234                         with open(constants._user_settings_, "r") as settingsFile:
235                                 settings = simplejson.load(settingsFile)
236                 except IOError, e:
237                         _moduleLogger.info("No settings")
238                         settings = {}
239                 except ValueError:
240                         _moduleLogger.info("Settings were corrupt")
241                         settings = {}
242
243                 self._fullscreenAction.setChecked(settings.get("isFullScreen", False))
244
245                 sortBy = settings.get("sortBy", "name")
246                 if sortBy not in ["name", "value", "unit"]:
247                         _moduleLogger.info("Setting sortBy is not a valid value: %s" % sortBy)
248                         sortBy = "name"
249                 if sortBy == "name":
250                         self._sortByNameAction.setChecked(True)
251                         self._sortByValueAction.setChecked(False)
252                         self._sortByUnitAction.setChecked(False)
253                 elif sortBy == "value":
254                         self._sortByNameAction.setChecked(False)
255                         self._sortByValueAction.setChecked(True)
256                         self._sortByUnitAction.setChecked(False)
257                 elif sortBy == "unit":
258                         self._sortByNameAction.setChecked(False)
259                         self._sortByValueAction.setChecked(False)
260                         self._sortByUnitAction.setChecked(True)
261                 else:
262                         raise RuntimeError("How did this sortBy come about? %s" % sortBy)
263
264                 recent = settings.get("recent", self._recent)
265                 for category, unit in recent:
266                         self.add_recent(category, unit)
267
268                 self._hiddenCategories = set(settings.get("hiddenCategories", set()))
269                 self._hiddenUnits = dict(
270                         (catName, set(units))
271                         for (catName, units) in settings.get("hiddenUnits", {}).iteritems()
272                 )
273
274                 self._showFavoritesAction.setChecked(settings.get("showFavorites", True))
275
276                 self._condensedAction.setChecked(settings.get("useQuick", self._condensedAction.isChecked()))
277
278         def save_settings(self):
279                 if self._sortByNameAction.isChecked():
280                         sortBy = "name"
281                 elif self._sortByValueAction.isChecked():
282                         sortBy = "value"
283                 elif self._sortByUnitAction.isChecked():
284                         sortBy = "unit"
285                 else:
286                         raise RuntimeError("Unknown sorting value")
287                 settings = {
288                         "isFullScreen": self._fullscreenAction.isChecked(),
289                         "recent": self._recent,
290                         "hiddenCategories": list(self._hiddenCategories),
291                         "hiddenUnits": dict(
292                                 (catName, list(units))
293                                 for (catName, units) in self._hiddenUnits.iteritems()
294                         ),
295                         "showFavorites": self._showFavoritesAction.isChecked(),
296                         "useQuick": self._condensedAction.isChecked(),
297                         "sortBy": sortBy,
298                 }
299                 with open(constants._user_settings_, "w") as settingsFile:
300                         simplejson.dump(settings, settingsFile)
301
302         @property
303         def appIconPath(self):
304                 return self._appIconPath
305
306         @property
307         def jumpAction(self):
308                 return self._jumpAction
309
310         @property
311         def recentAction(self):
312                 return self._recentAction
313
314         @property
315         def fullscreenAction(self):
316                 return self._fullscreenAction
317
318         @property
319         def condensedAction(self):
320                 return self._condensedAction
321
322         @property
323         def sortByNameAction(self):
324                 return self._sortByNameAction
325
326         @property
327         def sortByValueAction(self):
328                 return self._sortByValueAction
329
330         @property
331         def sortByUnitAction(self):
332                 return self._sortByUnitAction
333
334         @property
335         def logAction(self):
336                 return self._logAction
337
338         @property
339         def quitAction(self):
340                 return self._quitAction
341
342         @property
343         def showFavoritesAction(self):
344                 return self._showFavoritesAction
345
346         def _walk_children(self):
347                 if self._catWindow is not None:
348                         yield self._catWindow
349                 if self._quickWindow is not None:
350                         yield self._quickWindow
351                 if self._jumpWindow is not None:
352                         yield self._jumpWindow
353                 if self._recentWindow is not None:
354                         yield self._recentWindow
355
356         def _close_windows(self):
357                 if self._catWindow is not None:
358                         self._catWindow.window.destroyed.disconnect(self._on_cat_close)
359                         self._catWindow.close()
360                         self._catWindow = None
361                 if self._quickWindow is not None:
362                         self._quickWindow.window.destroyed.disconnect(self._on_quick_close)
363                         self._quickWindow.close()
364                         self._quickWindow = None
365                 if self._jumpWindow is not None:
366                         self._jumpWindow.window.destroyed.disconnect(self._on_jump_close)
367                         self._jumpWindow.close()
368                         self._jumpWindow = None
369                 if self._recentWindow is not None:
370                         self._recentWindow.window.destroyed.disconnect(self._on_recent_close)
371                         self._recentWindow.close()
372                         self._recentWindow = None
373
374         @misc_utils.log_exception(_moduleLogger)
375         def _on_app_quit(self, checked = False):
376                 self.save_settings()
377
378         @misc_utils.log_exception(_moduleLogger)
379         def _on_child_close(self, name, obj = None):
380                 if not hasattr(self, name):
381                         _moduleLogger.info("Something weird going on when we don't have a %s" % name)
382                         return
383                 setattr(self, name, None)
384
385         @misc_utils.log_exception(_moduleLogger)
386         def _on_toggle_fullscreen(self, checked = False):
387                 for window in self._walk_children():
388                         window.set_fullscreen(checked)
389
390         @misc_utils.log_exception(_moduleLogger)
391         def _on_condensed_start(self, checked = False):
392                 self.request_category()
393                 if self._recent:
394                         self._mainWindow.select_category(self._recent[-1][0])
395
396         @misc_utils.log_exception(_moduleLogger)
397         def _on_jump_start(self, checked = False):
398                 self.search_units()
399
400         @misc_utils.log_exception(_moduleLogger)
401         def _on_recent_start(self, checked = False):
402                 self.show_recent()
403
404         @misc_utils.log_exception(_moduleLogger)
405         def _on_log(self, checked = False):
406                 with open(constants._user_logpath_, "r") as f:
407                         logLines = f.xreadlines()
408                         log = "".join(logLines)
409                         self._clipboard.setText(log)
410
411         @misc_utils.log_exception(_moduleLogger)
412         def _on_quit(self, checked = False):
413                 self._close_windows()
414
415
416 class QuickJump(object):
417
418         MINIMAL_ENTRY = 3
419
420         def __init__(self, parent, app):
421                 self._app = app
422
423                 self._searchLabel = QtGui.QLabel("Search:")
424                 self._searchEntry = QtGui.QLineEdit("")
425                 self._searchEntry.textEdited.connect(self._on_search_edited)
426
427                 self._entryLayout = QtGui.QHBoxLayout()
428                 self._entryLayout.addWidget(self._searchLabel)
429                 self._entryLayout.addWidget(self._searchEntry)
430
431                 self._resultsBox = QtGui.QTreeWidget()
432                 self._resultsBox.setHeaderLabels(["Categories", "Units"])
433                 self._resultsBox.setHeaderHidden(True)
434                 if not IS_MAEMO:
435                         self._resultsBox.setAlternatingRowColors(True)
436                 self._resultsBox.itemClicked.connect(self._on_result_clicked)
437
438                 self._layout = QtGui.QVBoxLayout()
439                 self._layout.addLayout(self._entryLayout)
440                 self._layout.addWidget(self._resultsBox)
441
442                 centralWidget = QtGui.QWidget()
443                 centralWidget.setLayout(self._layout)
444
445                 self._window = QtGui.QMainWindow(parent)
446                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
447                 maeqt.set_autorient(self._window, True)
448                 maeqt.set_stackable(self._window, True)
449                 self._window.setWindowTitle("%s - Quick Jump" % constants.__pretty_app_name__)
450                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
451                 self._window.setCentralWidget(centralWidget)
452
453                 self._closeWindowAction = QtGui.QAction(None)
454                 self._closeWindowAction.setText("Close")
455                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
456                 self._closeWindowAction.triggered.connect(self._on_close_window)
457
458                 if IS_MAEMO:
459                         self._window.addAction(self._closeWindowAction)
460                         self._window.addAction(self._app.quitAction)
461                         self._window.addAction(self._app.fullscreenAction)
462                 else:
463                         fileMenu = self._window.menuBar().addMenu("&Units")
464                         fileMenu.addAction(self._closeWindowAction)
465                         fileMenu.addAction(self._app.quitAction)
466
467                         viewMenu = self._window.menuBar().addMenu("&View")
468                         viewMenu.addAction(self._app.fullscreenAction)
469
470                 self._window.addAction(self._app.logAction)
471
472                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
473                 self._window.show()
474
475         @property
476         def window(self):
477                 return self._window
478
479         def show(self):
480                 self._window.show()
481
482         def hide(self):
483                 self._window.hide()
484
485         def close(self):
486                 self._window.close()
487
488         def set_fullscreen(self, isFullscreen):
489                 if isFullscreen:
490                         self._window.showFullScreen()
491                 else:
492                         self._window.showNormal()
493
494         @misc_utils.log_exception(_moduleLogger)
495         def _on_close_window(self, checked = True):
496                 self.close()
497
498         @misc_utils.log_exception(_moduleLogger)
499         def _on_result_clicked(self, item, columnIndex):
500                 categoryName = unicode(item.text(0))
501                 unitName = unicode(item.text(1))
502                 catWindow = self._app.request_category()
503                 unitsWindow = catWindow.select_category(categoryName)
504                 unitsWindow.select_unit(unitName)
505                 self.close()
506
507         @misc_utils.log_exception(_moduleLogger)
508         def _on_search_edited(self, *args):
509                 userInput = self._searchEntry.text()
510                 if len(userInput) <  self.MINIMAL_ENTRY:
511                         return
512
513                 self._resultsBox.clear()
514                 lowerInput = str(userInput).lower()
515                 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
516                         units = unit_data.get_units(category)
517                         for unitIndex, unit in enumerate(units):
518                                 loweredUnit = unit.lower()
519                                 if lowerInput in loweredUnit:
520                                         twi = QtGui.QTreeWidgetItem(self._resultsBox)
521                                         twi.setText(0, category)
522                                         twi.setText(1, unit)
523
524
525 class Recent(object):
526
527         def __init__(self, parent, app):
528                 self._app = app
529
530                 self._resultsBox = QtGui.QTreeWidget()
531                 self._resultsBox.setHeaderLabels(["Categories", "Units"])
532                 self._resultsBox.setHeaderHidden(True)
533                 if not IS_MAEMO:
534                         self._resultsBox.setAlternatingRowColors(True)
535                 self._resultsBox.itemClicked.connect(self._on_result_clicked)
536
537                 self._layout = QtGui.QVBoxLayout()
538                 self._layout.addWidget(self._resultsBox)
539
540                 centralWidget = QtGui.QWidget()
541                 centralWidget.setLayout(self._layout)
542
543                 self._window = QtGui.QMainWindow(parent)
544                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
545                 maeqt.set_autorient(self._window, True)
546                 maeqt.set_stackable(self._window, True)
547                 self._window.setWindowTitle("%s - Recent" % constants.__pretty_app_name__)
548                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
549                 self._window.setCentralWidget(centralWidget)
550
551                 for cat, unit in self._app.get_recent():
552                         twi = QtGui.QTreeWidgetItem(self._resultsBox)
553                         twi.setText(0, cat)
554                         twi.setText(1, unit)
555
556                 self._closeWindowAction = QtGui.QAction(None)
557                 self._closeWindowAction.setText("Close")
558                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
559                 self._closeWindowAction.triggered.connect(self._on_close_window)
560
561                 if IS_MAEMO:
562                         self._window.addAction(self._closeWindowAction)
563                         self._window.addAction(self._app.quitAction)
564                         self._window.addAction(self._app.fullscreenAction)
565                 else:
566                         fileMenu = self._window.menuBar().addMenu("&Units")
567                         fileMenu.addAction(self._closeWindowAction)
568                         fileMenu.addAction(self._app.quitAction)
569
570                         viewMenu = self._window.menuBar().addMenu("&View")
571                         viewMenu.addAction(self._app.fullscreenAction)
572
573                 self._window.addAction(self._app.logAction)
574
575                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
576                 self._window.show()
577
578         @property
579         def window(self):
580                 return self._window
581
582         def show(self):
583                 self._window.show()
584
585         def hide(self):
586                 self._window.hide()
587
588         def close(self):
589                 self._window.close()
590
591         def set_fullscreen(self, isFullscreen):
592                 if isFullscreen:
593                         self._window.showFullScreen()
594                 else:
595                         self._window.showNormal()
596
597         @misc_utils.log_exception(_moduleLogger)
598         def _on_close_window(self, checked = True):
599                 self.close()
600
601         @misc_utils.log_exception(_moduleLogger)
602         def _on_result_clicked(self, item, columnIndex):
603                 categoryName = unicode(item.text(0))
604                 unitName = unicode(item.text(1))
605                 catWindow = self._app.request_category()
606                 unitsWindow = catWindow.select_category(categoryName)
607                 unitsWindow.select_unit(unitName)
608                 self.close()
609
610
611 class QuickConvert(object):
612
613         def __init__(self, parent, app):
614                 self._app = app
615                 self._categoryName = ""
616                 self._inputUnitName = ""
617                 self._outputUnitName = ""
618                 self._unitNames = []
619                 self._favoritesWindow = None
620
621                 self._inputUnitValue = QtGui.QLineEdit()
622                 self._inputUnitValue.setInputMethodHints(QtCore.Qt.ImhPreferNumbers)
623                 self._inputUnitValue.textEdited.connect(self._on_value_edited)
624                 self._inputUnitSymbol = QtGui.QLabel()
625
626                 self._outputUnitValue = QtGui.QLabel()
627                 self._outputUnitSymbol = QtGui.QLabel()
628
629                 self._conversionLayout = QtGui.QHBoxLayout()
630                 self._conversionLayout.addWidget(self._inputUnitValue)
631                 self._conversionLayout.addWidget(self._inputUnitSymbol)
632                 self._conversionLayout.addWidget(self._outputUnitValue)
633                 self._conversionLayout.addWidget(self._outputUnitSymbol)
634
635                 self._categoryView = QtGui.QTreeWidget()
636                 self._categoryView.setHeaderLabels(["Categories"])
637                 self._categoryView.setHeaderHidden(False)
638                 if not IS_MAEMO:
639                         self._categoryView.setAlternatingRowColors(True)
640                 self._categoryView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
641                 self._categoryView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
642                 for catName in unit_data.UNIT_CATEGORIES:
643                         twi = QtGui.QTreeWidgetItem(self._categoryView)
644                         twi.setText(0, catName)
645                 self._categorySelection = self._categoryView.selectionModel()
646                 self._categorySelection.selectionChanged.connect(self._on_category_selection_changed)
647
648                 self._inputView = QtGui.QTreeWidget()
649                 self._inputView.setHeaderLabels(["From", "Name"])
650                 self._inputView.setHeaderHidden(False)
651                 self._inputView.header().hideSection(1)
652                 if not IS_MAEMO:
653                         self._inputView.setAlternatingRowColors(True)
654                 self._inputView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
655                 self._inputView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
656                 self._inputSelection = self._inputView.selectionModel()
657                 self._inputSelection.selectionChanged.connect(self._on_input_selection_changed)
658
659                 self._outputView = QtGui.QTreeWidget()
660                 self._outputView.setHeaderLabels(["To", "Name"])
661                 self._outputView.setHeaderHidden(False)
662                 self._outputView.header().hideSection(1)
663                 if not IS_MAEMO:
664                         self._outputView.setAlternatingRowColors(True)
665                 self._outputView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
666                 self._outputView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
667                 self._outputWidgets = []
668                 self._outputSelection = self._outputView.selectionModel()
669                 self._outputSelection.selectionChanged.connect(self._on_output_selection_changed)
670
671                 self._selectionLayout = QtGui.QHBoxLayout()
672                 self._selectionLayout.addWidget(self._categoryView)
673                 self._selectionLayout.addWidget(self._inputView)
674                 self._selectionLayout.addWidget(self._outputView)
675
676                 self._layout = QtGui.QVBoxLayout()
677                 self._layout.addLayout(self._conversionLayout)
678                 self._layout.addLayout(self._selectionLayout)
679
680                 centralWidget = QtGui.QWidget()
681                 centralWidget.setLayout(self._layout)
682
683                 self._window = QtGui.QMainWindow(parent)
684                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
685                 maeqt.set_autorient(self._window, True)
686                 maeqt.set_stackable(self._window, True)
687                 self._window.setWindowTitle("%s - Quick Convert" % (constants.__pretty_app_name__, ))
688                 self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
689                 self._window.setCentralWidget(centralWidget)
690
691                 self._chooseCatFavoritesAction = QtGui.QAction(None)
692                 self._chooseCatFavoritesAction.setText("Select Categories")
693                 self._chooseCatFavoritesAction.triggered.connect(self._on_choose_category_favorites)
694
695                 self._chooseUnitFavoritesAction = QtGui.QAction(None)
696                 self._chooseUnitFavoritesAction.setText("Select Units")
697                 self._chooseUnitFavoritesAction.triggered.connect(self._on_choose_unit_favorites)
698                 self._chooseUnitFavoritesAction.setEnabled(False)
699
700                 self._app.showFavoritesAction.toggled.connect(self._on_show_favorites)
701
702                 self._closeWindowAction = QtGui.QAction(None)
703                 self._closeWindowAction.setText("Close Window")
704                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
705                 self._closeWindowAction.triggered.connect(self._on_close_window)
706
707                 if IS_MAEMO:
708                         self._window.addAction(self._closeWindowAction)
709                         self._window.addAction(self._app.quitAction)
710                         self._window.addAction(self._app.fullscreenAction)
711
712                         fileMenu = self._window.menuBar().addMenu("&Units")
713                         fileMenu.addAction(self._chooseCatFavoritesAction)
714                         fileMenu.addAction(self._chooseUnitFavoritesAction)
715
716                         viewMenu = self._window.menuBar().addMenu("&View")
717                         viewMenu.addAction(self._app.showFavoritesAction)
718                         viewMenu.addAction(self._app.condensedAction)
719                         viewMenu.addSeparator()
720                         viewMenu.addAction(self._app.jumpAction)
721                         viewMenu.addAction(self._app.recentAction)
722                 else:
723                         fileMenu = self._window.menuBar().addMenu("&Units")
724                         fileMenu.addAction(self._chooseCatFavoritesAction)
725                         fileMenu.addAction(self._chooseUnitFavoritesAction)
726                         fileMenu.addAction(self._closeWindowAction)
727                         fileMenu.addAction(self._app.quitAction)
728
729                         viewMenu = self._window.menuBar().addMenu("&View")
730                         viewMenu.addAction(self._app.showFavoritesAction)
731                         viewMenu.addAction(self._app.condensedAction)
732                         viewMenu.addSeparator()
733                         viewMenu.addAction(self._app.jumpAction)
734                         viewMenu.addAction(self._app.recentAction)
735                         viewMenu.addSeparator()
736                         viewMenu.addAction(self._app.fullscreenAction)
737
738                 self._window.addAction(self._app.logAction)
739
740                 self._update_favorites()
741                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
742                 self._window.show()
743
744         @property
745         def window(self):
746                 return self._window
747
748         def show(self):
749                 self._window.show()
750
751         def hide(self):
752                 self._window.hide()
753
754         def close(self):
755                 self._window.close()
756
757         def set_fullscreen(self, isFullscreen):
758                 if isFullscreen:
759                         self._window.showFullScreen()
760                 else:
761                         self._window.showNormal()
762
763         def select_category(self, categoryName):
764                 self._inputUnitName = ""
765                 self._outputUnitName = ""
766                 self._inputUnitValue.setText("")
767                 self._inputUnitSymbol.setText("")
768                 self._inputView.clear()
769                 self._outputUnitValue.setText("")
770                 self._outputUnitSymbol.setText("")
771                 self._outputView.clear()
772                 self._categoryName = categoryName
773                 self._chooseUnitFavoritesAction.setEnabled(True)
774
775                 unitData = unit_data.UNIT_DESCRIPTIONS[categoryName]
776                 self._unitNames = list(unit_data.get_units(categoryName))
777                 self._unitNames.sort()
778                 for key in self._unitNames:
779                         conversion, unit, description = unitData[key]
780                         if not unit:
781                                 unit = key
782
783                         twi = QtGui.QTreeWidgetItem(self._inputView)
784                         twi.setText(0, unit)
785                         twi.setText(1, key)
786
787                         twi = QtGui.QTreeWidgetItem(self._outputView)
788                         twi.setText(0, unit)
789                         twi.setText(1, key)
790
791                 i = unit_data.UNIT_CATEGORIES.index(categoryName)
792                 rootIndex = self._categoryView.rootIndex()
793                 currentIndex = self._categoryView.model().index(i, 0, rootIndex)
794                 self._categoryView.scrollTo(currentIndex)
795
796                 defaultInputUnitName = self._app.get_recent_unit(categoryName)
797                 if defaultInputUnitName:
798                         self.select_input(defaultInputUnitName)
799                         defaultOutputUnitName = self._app.get_recent_unit(categoryName, 1)
800                         assert defaultOutputUnitName
801                         self.select_output(defaultOutputUnitName)
802
803                 return self
804
805         def select_unit(self, name):
806                 self.select_input(name)
807
808         def select_input(self, name):
809                 self._app.add_recent(self._categoryName, name)
810                 self._inputUnitName = name
811
812                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
813                 conversion, unit, description = unitData[name]
814
815                 self._inputUnitSymbol.setText(unit if unit else name)
816
817                 i = self._unitNames.index(name)
818                 rootIndex = self._inputView.rootIndex()
819                 currentIndex = self._inputView.model().index(i, 0, rootIndex)
820                 self._inputView.scrollTo(currentIndex)
821
822                 if "" not in [self._categoryName, self._inputUnitName, self._outputUnitName]:
823                         self._update_conversion()
824
825         def select_output(self, name):
826                 # Add the output to recent but don't make things weird by making it the most recent
827                 self._app.add_recent(self._categoryName, name)
828                 self._app.add_recent(self._categoryName, self._inputUnitName)
829                 self._outputUnitName = name
830
831                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
832                 conversion, unit, description = unitData[name]
833
834                 self._outputUnitSymbol.setText(unit if unit else name)
835
836                 i = self._unitNames.index(name)
837                 rootIndex = self._outputView.rootIndex()
838                 currentIndex = self._outputView.model().index(i, 0, rootIndex)
839                 self._outputView.scrollTo(currentIndex)
840
841                 if "" not in [self._categoryName, self._inputUnitName, self._outputUnitName]:
842                         self._update_conversion()
843
844         def _sanitize_value(self, userEntry):
845                 if self._categoryName == "Computer Numbers":
846                         if userEntry == '':
847                                 value = '0'
848                         else:
849                                 value = userEntry
850                 else:
851                         if userEntry == '':
852                                 value = 0.0
853                         else:
854                                 value = float(userEntry)
855                 return value
856
857         def _update_conversion(self):
858                 assert self._categoryName
859                 assert self._inputUnitName
860                 assert self._outputUnitName
861
862                 userInput = str(self._inputUnitValue.text())
863                 value = self._sanitize_value(userInput)
864
865                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
866                 inputConversion, _, _ = unitData[self._inputUnitName]
867                 outputConversion, _, _ = unitData[self._outputUnitName]
868
869                 func, arg = inputConversion
870                 base = func.to_base(value, arg)
871
872                 func, arg = outputConversion
873                 newValue = func.from_base(base, arg)
874                 self._outputUnitValue.setText(str(newValue))
875
876         def _update_favorites(self):
877                 if self._app.showFavoritesAction.isChecked():
878                         assert self._categoryView.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
879                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
880                                 if catName in self._app.hiddenCategories:
881                                         self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), True)
882                                 else:
883                                         self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), False)
884
885                         for i, unitName in enumerate(self._unitNames):
886                                 if unitName in self._app.get_hidden_units(self._categoryName):
887                                         self._inputView.setRowHidden(i, self._inputView.rootIndex(), True)
888                                         self._outputView.setRowHidden(i, self._outputView.rootIndex(), True)
889                                 else:
890                                         self._inputView.setRowHidden(i, self._inputView.rootIndex(), False)
891                                         self._outputView.setRowHidden(i, self._outputView.rootIndex(), False)
892                 else:
893                         for i in xrange(self._categoryView.topLevelItemCount()):
894                                 self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), False)
895
896                         for i in xrange(len(self._unitNames)):
897                                 self._inputView.setRowHidden(i, self._inputView.rootIndex(), False)
898                                 self._outputView.setRowHidden(i, self._outputView.rootIndex(), False)
899
900         @misc_utils.log_exception(_moduleLogger)
901         def _on_close_window(self, checked = True):
902                 self.close()
903
904         @misc_utils.log_exception(_moduleLogger)
905         def _on_show_favorites(self, checked = True):
906                 if checked:
907                         assert self._categoryView.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
908                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
909                                 if catName in self._app.hiddenCategories:
910                                         self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), True)
911
912                         for i, unitName in enumerate(self._unitNames):
913                                 if unitName in self._app.get_hidden_units(self._categoryName):
914                                         self._inputView.setRowHidden(i, self._inputView.rootIndex(), True)
915                                         self._outputView.setRowHidden(i, self._outputView.rootIndex(), True)
916                 else:
917                         for i in xrange(self._categoryView.topLevelItemCount()):
918                                 self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), False)
919
920                         for i in xrange(len(self._unitNames)):
921                                 self._inputView.setRowHidden(i, self._inputView.rootIndex(), False)
922                                 self._outputView.setRowHidden(i, self._outputView.rootIndex(), False)
923
924         @misc_utils.log_exception(_moduleLogger)
925         def _on_choose_category_favorites(self, obj = None):
926                 assert self._favoritesWindow is None
927                 self._favoritesWindow = FavoritesWindow(
928                         self._window,
929                         self._app,
930                         unit_data.UNIT_CATEGORIES,
931                         self._app.hiddenCategories
932                 )
933                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
934                 return self._favoritesWindow
935
936         @misc_utils.log_exception(_moduleLogger)
937         def _on_choose_unit_favorites(self, obj = None):
938                 assert self._favoritesWindow is None
939                 self._favoritesWindow = FavoritesWindow(
940                         self._window,
941                         self._app,
942                         unit_data.get_units(self._categoryName),
943                         self._app.get_hidden_units(self._categoryName)
944                 )
945                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
946                 return self._favoritesWindow
947
948         @misc_utils.log_exception(_moduleLogger)
949         def _on_close_favorites(self, obj = None):
950                 self._favoritesWindow = None
951                 self._update_favorites()
952
953         @misc_utils.log_exception(_moduleLogger)
954         def _on_value_edited(self, *args):
955                 self._update_conversion()
956
957         @misc_utils.log_exception(_moduleLogger)
958         def _on_category_selection_changed(self, selected, deselected):
959                 selectedNames = [
960                         str(item.text(0))
961                         for item in self._categoryView.selectedItems()
962                 ]
963                 assert len(selectedNames) == 1
964                 self.select_category(selectedNames[0])
965
966         @misc_utils.log_exception(_moduleLogger)
967         def _on_input_selection_changed(self, selected, deselected):
968                 selectedNames = [
969                         str(item.text(1))
970                         for item in self._inputView.selectedItems()
971                 ]
972                 if selectedNames:
973                         assert len(selectedNames) == 1
974                         name = selectedNames[0]
975                         self.select_input(name)
976                 else:
977                         pass
978
979         @misc_utils.log_exception(_moduleLogger)
980         def _on_output_selection_changed(self, selected, deselected):
981                 selectedNames = [
982                         str(item.text(1))
983                         for item in self._outputView.selectedItems()
984                 ]
985                 if selectedNames:
986                         assert len(selectedNames) == 1
987                         name = selectedNames[0]
988                         self.select_output(name)
989                 else:
990                         pass
991
992
993 class FavoritesWindow(object):
994
995         def __init__(self, parent, app, source, hidden):
996                 self._app = app
997                 self._source = list(source)
998                 self._hidden = hidden
999
1000                 self._categories = QtGui.QTreeWidget()
1001                 self._categories.setHeaderLabels(["Categories"])
1002                 self._categories.setHeaderHidden(True)
1003                 if not IS_MAEMO:
1004                         self._categories.setAlternatingRowColors(True)
1005                 self._categories.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
1006                 self._categories.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
1007                 self._childWidgets = []
1008                 for catName in self._source:
1009                         twi = QtGui.QTreeWidgetItem(self._categories)
1010                         twi.setText(0, catName)
1011                         self._childWidgets.append(twi)
1012                         if catName not in self._hidden:
1013                                 self._categories.setItemSelected(twi, True)
1014                 self._selection = self._categories.selectionModel()
1015                 self._selection.selectionChanged.connect(self._on_selection_changed)
1016
1017                 self._allButton = QtGui.QPushButton("All")
1018                 self._allButton.clicked.connect(self._on_select_all)
1019                 self._invertButton = QtGui.QPushButton("Invert")
1020                 self._invertButton.clicked.connect(self._on_invert_selection)
1021                 self._noneButton = QtGui.QPushButton("None")
1022                 self._noneButton.clicked.connect(self._on_select_none)
1023
1024                 self._buttonLayout = QtGui.QHBoxLayout()
1025                 self._buttonLayout.addWidget(self._allButton)
1026                 self._buttonLayout.addWidget(self._invertButton)
1027                 self._buttonLayout.addWidget(self._noneButton)
1028
1029                 self._layout = QtGui.QVBoxLayout()
1030                 self._layout.addWidget(self._categories)
1031                 self._layout.addLayout(self._buttonLayout)
1032
1033                 centralWidget = QtGui.QWidget()
1034                 centralWidget.setLayout(self._layout)
1035
1036                 self._window = QtGui.QMainWindow(parent)
1037                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
1038                 maeqt.set_autorient(self._window, True)
1039                 maeqt.set_stackable(self._window, True)
1040                 self._window.setWindowTitle("%s - Favorites" % constants.__pretty_app_name__)
1041                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
1042                 self._window.setCentralWidget(centralWidget)
1043
1044                 self._closeWindowAction = QtGui.QAction(None)
1045                 self._closeWindowAction.setText("Close")
1046                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
1047                 self._closeWindowAction.triggered.connect(self._on_close_window)
1048
1049                 if IS_MAEMO:
1050                         self._window.addAction(self._closeWindowAction)
1051                         self._window.addAction(self._app.quitAction)
1052                         self._window.addAction(self._app.fullscreenAction)
1053                 else:
1054                         fileMenu = self._window.menuBar().addMenu("&Units")
1055                         fileMenu.addAction(self._closeWindowAction)
1056                         fileMenu.addAction(self._app.quitAction)
1057
1058                         viewMenu = self._window.menuBar().addMenu("&View")
1059                         viewMenu.addAction(self._app.fullscreenAction)
1060
1061                 self._window.addAction(self._app.logAction)
1062
1063                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
1064                 self._window.show()
1065
1066         @property
1067         def window(self):
1068                 return self._window
1069
1070         def show(self):
1071                 self._window.show()
1072
1073         def hide(self):
1074                 self._window.hide()
1075
1076         def close(self):
1077                 self._window.close()
1078
1079         def set_fullscreen(self, isFullscreen):
1080                 if isFullscreen:
1081                         self._window.showFullScreen()
1082                 else:
1083                         self._window.showNormal()
1084
1085         @misc_utils.log_exception(_moduleLogger)
1086         def _on_select_all(self, checked = False):
1087                 for child in self._childWidgets:
1088                         self._categories.setItemSelected(child, True)
1089
1090         @misc_utils.log_exception(_moduleLogger)
1091         def _on_invert_selection(self, checked = False):
1092                 for child in self._childWidgets:
1093                         isSelected = self._categories.isItemSelected(child)
1094                         self._categories.setItemSelected(child, not isSelected)
1095
1096         @misc_utils.log_exception(_moduleLogger)
1097         def _on_select_none(self, checked = False):
1098                 for child in self._childWidgets:
1099                         self._categories.setItemSelected(child, False)
1100
1101         @misc_utils.log_exception(_moduleLogger)
1102         def _on_selection_changed(self, selected, deselected):
1103                 self._hidden.clear()
1104                 selectedNames = set(
1105                         str(item.text(0))
1106                         for item in self._categories.selectedItems()
1107                 )
1108                 for name in self._source:
1109                         if name not in selectedNames:
1110                                 self._hidden.add(name)
1111
1112         @misc_utils.log_exception(_moduleLogger)
1113         def _on_close_window(self, checked = True):
1114                 self.close()
1115
1116
1117 class CategoryWindow(object):
1118
1119         def __init__(self, parent, app):
1120                 self._app = app
1121                 self._unitWindow = None
1122                 self._favoritesWindow = None
1123
1124                 self._categories = QtGui.QTreeWidget()
1125                 self._categories.setHeaderLabels(["Categories"])
1126                 self._categories.itemClicked.connect(self._on_category_clicked)
1127                 self._categories.setHeaderHidden(True)
1128                 self._categories.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
1129                 self._categories.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
1130                 if not IS_MAEMO:
1131                         self._categories.setAlternatingRowColors(True)
1132                 for catName in unit_data.UNIT_CATEGORIES:
1133                         twi = QtGui.QTreeWidgetItem(self._categories)
1134                         twi.setText(0, catName)
1135
1136                 self._layout = QtGui.QVBoxLayout()
1137                 self._layout.addWidget(self._categories)
1138
1139                 centralWidget = QtGui.QWidget()
1140                 centralWidget.setLayout(self._layout)
1141
1142                 self._window = QtGui.QMainWindow(parent)
1143                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
1144                 maeqt.set_autorient(self._window, True)
1145                 maeqt.set_stackable(self._window, True)
1146                 self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
1147                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
1148                 self._window.setCentralWidget(centralWidget)
1149
1150                 self._chooseFavoritesAction = QtGui.QAction(None)
1151                 self._chooseFavoritesAction.setText("Select Favorites")
1152                 self._chooseFavoritesAction.setShortcut(QtGui.QKeySequence("CTRL+f"))
1153                 self._chooseFavoritesAction.triggered.connect(self._on_choose_favorites)
1154
1155                 self._app.showFavoritesAction.toggled.connect(self._on_show_favorites)
1156
1157                 self._closeWindowAction = QtGui.QAction(None)
1158                 self._closeWindowAction.setText("Close")
1159                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
1160                 self._closeWindowAction.triggered.connect(self._on_close_window)
1161
1162                 if IS_MAEMO:
1163                         fileMenu = self._window.menuBar().addMenu("&Units")
1164                         fileMenu.addAction(self._chooseFavoritesAction)
1165
1166                         viewMenu = self._window.menuBar().addMenu("&View")
1167                         viewMenu.addAction(self._app.showFavoritesAction)
1168                         viewMenu.addAction(self._app.condensedAction)
1169                         viewMenu.addSeparator()
1170                         viewMenu.addAction(self._app.jumpAction)
1171                         viewMenu.addAction(self._app.recentAction)
1172
1173                         self._window.addAction(self._closeWindowAction)
1174                         self._window.addAction(self._app.quitAction)
1175                         self._window.addAction(self._app.fullscreenAction)
1176                 else:
1177                         fileMenu = self._window.menuBar().addMenu("&Units")
1178                         fileMenu.addAction(self._chooseFavoritesAction)
1179                         fileMenu.addAction(self._closeWindowAction)
1180                         fileMenu.addAction(self._app.quitAction)
1181
1182                         viewMenu = self._window.menuBar().addMenu("&View")
1183                         viewMenu.addAction(self._app.showFavoritesAction)
1184                         viewMenu.addAction(self._app.condensedAction)
1185                         viewMenu.addSeparator()
1186                         viewMenu.addAction(self._app.jumpAction)
1187                         viewMenu.addAction(self._app.recentAction)
1188                         viewMenu.addSeparator()
1189                         viewMenu.addAction(self._app.fullscreenAction)
1190
1191                 self._window.addAction(self._app.logAction)
1192
1193                 self._update_favorites()
1194                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
1195                 self._window.show()
1196
1197         @property
1198         def window(self):
1199                 return self._window
1200
1201         def walk_children(self):
1202                 if self._unitWindow is not None:
1203                         yield self._unitWindow
1204                 if self._favoritesWindow is not None:
1205                         yield self._favoritesWindow
1206
1207         def show(self):
1208                 self._window.show()
1209                 for child in self.walk_children():
1210                         child.show()
1211
1212         def hide(self):
1213                 for child in self.walk_children():
1214                         child.hide()
1215                 self._window.hide()
1216
1217         def close(self):
1218                 for child in self.walk_children():
1219                         child.window.destroyed.disconnect(self._on_child_close)
1220                         child.close()
1221                 self._window.close()
1222
1223         def select_category(self, categoryName):
1224                 for child in self.walk_children():
1225                         child.window.destroyed.disconnect(self._on_child_close)
1226                         child.close()
1227                 self._unitWindow = UnitWindow(self._window, categoryName, self._app)
1228                 self._unitWindow.window.destroyed.connect(self._on_child_close)
1229
1230                 i = unit_data.UNIT_CATEGORIES.index(categoryName)
1231                 rootIndex = self._categories.rootIndex()
1232                 currentIndex = self._categories.model().index(i, 0, rootIndex)
1233                 self._categories.scrollTo(currentIndex)
1234                 return self._unitWindow
1235
1236         def set_fullscreen(self, isFullscreen):
1237                 if isFullscreen:
1238                         self._window.showFullScreen()
1239                 else:
1240                         self._window.showNormal()
1241                 for child in self.walk_children():
1242                         child.set_fullscreen(isFullscreen)
1243
1244         def _update_favorites(self):
1245                 if self._app.showFavoritesAction.isChecked():
1246                         assert self._categories.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
1247                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
1248                                 if catName in self._app.hiddenCategories:
1249                                         self._categories.setRowHidden(i, self._categories.rootIndex(), True)
1250                                 else:
1251                                         self._categories.setRowHidden(i, self._categories.rootIndex(), False)
1252                 else:
1253                         for i in xrange(self._categories.topLevelItemCount()):
1254                                 self._categories.setRowHidden(i, self._categories.rootIndex(), False)
1255
1256         @misc_utils.log_exception(_moduleLogger)
1257         def _on_show_favorites(self, checked = True):
1258                 if checked:
1259                         assert self._categories.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
1260                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
1261                                 if catName in self._app.hiddenCategories:
1262                                         self._categories.setRowHidden(i, self._categories.rootIndex(), True)
1263                 else:
1264                         for i in xrange(self._categories.topLevelItemCount()):
1265                                 self._categories.setRowHidden(i, self._categories.rootIndex(), False)
1266
1267         @misc_utils.log_exception(_moduleLogger)
1268         def _on_choose_favorites(self, obj = None):
1269                 assert self._favoritesWindow is None
1270                 self._favoritesWindow = FavoritesWindow(
1271                         self._window,
1272                         self._app,
1273                         unit_data.UNIT_CATEGORIES,
1274                         self._app.hiddenCategories
1275                 )
1276                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
1277                 return self._favoritesWindow
1278
1279         @misc_utils.log_exception(_moduleLogger)
1280         def _on_close_favorites(self, obj = None):
1281                 self._favoritesWindow = None
1282                 self._update_favorites()
1283
1284         @misc_utils.log_exception(_moduleLogger)
1285         def _on_child_close(self, obj = None):
1286                 self._unitWindow = None
1287
1288         @misc_utils.log_exception(_moduleLogger)
1289         def _on_close_window(self, checked = True):
1290                 self.close()
1291
1292         @misc_utils.log_exception(_moduleLogger)
1293         def _on_category_clicked(self, item, columnIndex):
1294                 categoryName = unicode(item.text(0))
1295                 self.select_category(categoryName)
1296
1297
1298 class UnitData(object):
1299
1300         HEADERS = ["Name", "Value", "", "Unit"]
1301         ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
1302         NAME_COLUMN = 0
1303         VALUE_COLUMN_0 = 1
1304         VALUE_COLUMN_1 = 2
1305         UNIT_COLUMN = 3
1306
1307         def __init__(self, name, unit, description, conversion):
1308                 self._name = name
1309                 self._unit = unit
1310                 self._description = description
1311                 self._conversion = conversion
1312
1313                 self._value = 0.0
1314                 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
1315
1316         @property
1317         def name(self):
1318                 return self._name
1319
1320         @property
1321         def value(self):
1322                 return self._value
1323
1324         def update_value(self, newValue):
1325                 self._value = newValue
1326                 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
1327
1328         @property
1329         def unit(self):
1330                 return self._unit
1331
1332         @property
1333         def conversion(self):
1334                 return self._conversion
1335
1336         def data(self, column):
1337                 try:
1338                         return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
1339                 except IndexError:
1340                         return None
1341
1342
1343 class UnitModel(QtCore.QAbstractItemModel):
1344
1345         def __init__(self, categoryName, parent=None):
1346                 super(UnitModel, self).__init__(parent)
1347                 self._categoryName = categoryName
1348                 self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
1349
1350                 self._children = []
1351                 for key in unit_data.get_units(self._categoryName):
1352                         conversion, unit, description = self._unitData[key]
1353                         self._children.append(UnitData(key, unit, description, conversion))
1354                 self._sortSettings = None
1355
1356         @misc_utils.log_exception(_moduleLogger)
1357         def columnCount(self, parent):
1358                 if parent.isValid():
1359                         return 0
1360                 else:
1361                         return len(UnitData.HEADERS)
1362
1363         @misc_utils.log_exception(_moduleLogger)
1364         def data(self, index, role):
1365                 if not index.isValid():
1366                         return None
1367                 elif role == QtCore.Qt.TextAlignmentRole:
1368                         return UnitData.ALIGNMENT[index.column()]
1369                 elif role != QtCore.Qt.DisplayRole:
1370                         return None
1371
1372                 item = index.internalPointer()
1373                 if isinstance(item, UnitData):
1374                         return item.data(index.column())
1375                 elif item is UnitData.HEADERS:
1376                         return item[index.column()]
1377
1378         @misc_utils.log_exception(_moduleLogger)
1379         def sort(self, column, order = QtCore.Qt.AscendingOrder):
1380                 self._sortSettings = column, order
1381                 isReverse = order == QtCore.Qt.AscendingOrder
1382                 if column == UnitData.NAME_COLUMN:
1383                         key_func = lambda item: item.name
1384                 elif column in [UnitData.VALUE_COLUMN_0, UnitData.VALUE_COLUMN_1]:
1385                         key_func = lambda item: item.value
1386                 elif column == UnitData.UNIT_COLUMN:
1387                         key_func = lambda item: item.unit
1388                 self._children.sort(key=key_func, reverse = isReverse)
1389
1390                 self._all_changed()
1391
1392         @misc_utils.log_exception(_moduleLogger)
1393         def flags(self, index):
1394                 if not index.isValid():
1395                         return QtCore.Qt.NoItemFlags
1396
1397                 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
1398
1399         @misc_utils.log_exception(_moduleLogger)
1400         def headerData(self, section, orientation, role):
1401                 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
1402                         return UnitData.HEADERS[section]
1403
1404                 return None
1405
1406         @misc_utils.log_exception(_moduleLogger)
1407         def index(self, row, column, parent):
1408                 if not self.hasIndex(row, column, parent):
1409                         return QtCore.QModelIndex()
1410
1411                 if parent.isValid():
1412                         return QtCore.QModelIndex()
1413
1414                 parentItem = UnitData.HEADERS
1415                 childItem = self._children[row]
1416                 if childItem:
1417                         return self.createIndex(row, column, childItem)
1418                 else:
1419                         return QtCore.QModelIndex()
1420
1421         @misc_utils.log_exception(_moduleLogger)
1422         def parent(self, index):
1423                 if not index.isValid():
1424                         return QtCore.QModelIndex()
1425
1426                 childItem = index.internalPointer()
1427                 if isinstance(childItem, UnitData):
1428                         return QtCore.QModelIndex()
1429                 elif childItem is UnitData.HEADERS:
1430                         return None
1431
1432         @misc_utils.log_exception(_moduleLogger)
1433         def rowCount(self, parent):
1434                 if 0 < parent.column():
1435                         return 0
1436
1437                 if not parent.isValid():
1438                         return len(self._children)
1439                 else:
1440                         return len(self._children)
1441
1442         def get_unit(self, index):
1443                 assert 0 <= index
1444                 return self._children[index]
1445
1446         def get_unit_names(self):
1447                 for child in self._children:
1448                         yield child.name
1449
1450         def index_unit(self, unitName):
1451                 for i, child in enumerate(self._children):
1452                         if child.name == unitName:
1453                                 return i
1454                 else:
1455                         raise RuntimeError("Unit not found")
1456
1457         def update_values(self, fromIndex, userInput):
1458                 value = self._sanitize_value(userInput)
1459                 func, arg = self._children[fromIndex].conversion
1460                 base = func.to_base(value, arg)
1461                 for i, child in enumerate(self._children):
1462                         if i == fromIndex:
1463                                 continue
1464                         func, arg = child.conversion
1465                         newValue = func.from_base(base, arg)
1466                         child.update_value(newValue)
1467
1468                 if (
1469                         self._sortSettings is not None and
1470                         self._sortSettings[0]  in [UnitData.VALUE_COLUMN_0, UnitData.VALUE_COLUMN_1]
1471                 ):
1472                         # Sort takes care of marking everything as changed
1473                         self.sort(*self._sortSettings)
1474                 else:
1475                         self._values_changed()
1476
1477         def __len__(self):
1478                 return len(self._children)
1479
1480         def _values_changed(self):
1481                 topLeft = self.createIndex(0, UnitData.VALUE_COLUMN_0, self._children[0])
1482                 bottomRight = self.createIndex(len(self._children)-1, UnitData.VALUE_COLUMN_1, self._children[-1])
1483                 self.dataChanged.emit(topLeft, bottomRight)
1484
1485         def _all_changed(self):
1486                 topLeft = self.createIndex(0, 0, self._children[0])
1487                 bottomRight = self.createIndex(len(self._children)-1, len(UnitData.HEADERS)-1, self._children[-1])
1488                 self.dataChanged.emit(topLeft, bottomRight)
1489
1490         def _sanitize_value(self, userEntry):
1491                 if self._categoryName == "Computer Numbers":
1492                         if userEntry == '':
1493                                 value = '0'
1494                         else:
1495                                 value = userEntry
1496                 else:
1497                         if userEntry == '':
1498                                 value = 0.0
1499                         else:
1500                                 value = float(userEntry)
1501                 return value
1502
1503
1504 class UnitWindow(object):
1505
1506         def __init__(self, parent, category, app):
1507                 self._app = app
1508                 self._categoryName = category
1509                 self._selectedIndex = 0
1510                 self._favoritesWindow = None
1511
1512                 self._selectedUnitName = QtGui.QLabel()
1513                 self._selectedUnitValue = QtGui.QLineEdit()
1514                 self._selectedUnitValue.textEdited.connect(self._on_value_edited)
1515                 maeqt.mark_numbers_preferred(self._selectedUnitValue)
1516                 self._selectedUnitSymbol = QtGui.QLabel()
1517
1518                 self._selectedUnitLayout = QtGui.QHBoxLayout()
1519                 self._selectedUnitLayout.addWidget(self._selectedUnitName)
1520                 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
1521                 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
1522
1523                 self._unitsModel = UnitModel(self._categoryName)
1524                 self._unitsView = QtGui.QTreeView()
1525                 self._unitsView.setModel(self._unitsModel)
1526                 self._unitsView.clicked.connect(self._on_unit_clicked)
1527                 self._unitsView.setUniformRowHeights(True)
1528                 self._unitsView.setSortingEnabled(True)
1529                 self._unitsView.setTextElideMode(QtCore.Qt.ElideNone)
1530                 self._unitsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
1531                 self._unitsView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
1532                 self._unitsView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
1533                 if not IS_MAEMO:
1534                         self._unitsView.setAlternatingRowColors(True)
1535                 if True:
1536                         self._unitsView.setHeaderHidden(True)
1537
1538                 viewHeader = self._unitsView.header()
1539                 viewHeader.setSortIndicatorShown(True)
1540                 viewHeader.setClickable(True)
1541
1542                 viewHeader.setResizeMode(UnitData.NAME_COLUMN, QtGui.QHeaderView.ResizeToContents)
1543                 viewHeader.setResizeMode(UnitData.VALUE_COLUMN_0, QtGui.QHeaderView.ResizeToContents)
1544                 viewHeader.setResizeMode(UnitData.VALUE_COLUMN_1, QtGui.QHeaderView.ResizeToContents)
1545                 viewHeader.setResizeMode(UnitData.UNIT_COLUMN, QtGui.QHeaderView.ResizeToContents)
1546                 viewHeader.setStretchLastSection(False)
1547
1548                 # Trying to make things faster by locking in the initial size of the immutable columns
1549                 nameSize = min(viewHeader.sectionSize(UnitData.NAME_COLUMN), 125)
1550                 viewHeader.setResizeMode(UnitData.NAME_COLUMN, QtGui.QHeaderView.Fixed)
1551                 viewHeader.resizeSection(UnitData.NAME_COLUMN, nameSize)
1552                 unitSize = min(viewHeader.sectionSize(UnitData.UNIT_COLUMN), 125)
1553                 viewHeader.setResizeMode(UnitData.UNIT_COLUMN, QtGui.QHeaderView.Fixed)
1554                 viewHeader.resizeSection(UnitData.UNIT_COLUMN, unitSize)
1555
1556                 self._layout = QtGui.QVBoxLayout()
1557                 self._layout.addLayout(self._selectedUnitLayout)
1558                 self._layout.addWidget(self._unitsView)
1559
1560                 centralWidget = QtGui.QWidget()
1561                 centralWidget.setLayout(self._layout)
1562
1563                 self._window = QtGui.QMainWindow(parent)
1564                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
1565                 maeqt.set_autorient(self._window, True)
1566                 maeqt.set_stackable(self._window, True)
1567                 self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
1568                 self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
1569                 self._window.setCentralWidget(centralWidget)
1570
1571                 defaultUnitName = self._app.get_recent_unit(self._categoryName)
1572                 if defaultUnitName:
1573                         self.select_unit(defaultUnitName)
1574                 else:
1575                         self._select_unit(0)
1576
1577                 if self._app.sortByNameAction.isChecked():
1578                         sortColumn = UnitData.NAME_COLUMN
1579                 elif self._app.sortByValueAction.isChecked():
1580                         sortColumn = UnitData.VALUE_COLUMN_0
1581                 elif self._app.sortByUnitAction.isChecked():
1582                         sortColumn = UnitData.UNIT_COLUMN
1583                 else:
1584                         raise RuntimeError("No sort column selected")
1585                 if sortColumn != 0:
1586                         # By default it sorts by he first column (name)
1587                         self._unitsModel.sort(sortColumn)
1588
1589                 self._chooseFavoritesAction = QtGui.QAction(None)
1590                 self._chooseFavoritesAction.setText("Select Favorites")
1591                 self._chooseFavoritesAction.setShortcut(QtGui.QKeySequence("CTRL+f"))
1592                 self._chooseFavoritesAction.triggered.connect(self._on_choose_favorites)
1593
1594                 self._app.showFavoritesAction.toggled.connect(self._on_show_favorites)
1595
1596                 self._previousUnitAction = QtGui.QAction(None)
1597                 self._previousUnitAction.setText("Previous Unit")
1598                 self._previousUnitAction.setShortcut(QtGui.QKeySequence("Up"))
1599                 self._previousUnitAction.triggered.connect(self._on_previous_unit)
1600
1601                 self._nextUnitAction = QtGui.QAction(None)
1602                 self._nextUnitAction.setText("Next Unit")
1603                 self._nextUnitAction.setShortcut(QtGui.QKeySequence("Down"))
1604                 self._nextUnitAction.triggered.connect(self._on_next_unit)
1605
1606                 self._closeWindowAction = QtGui.QAction(None)
1607                 self._closeWindowAction.setText("Close Window")
1608                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
1609                 self._closeWindowAction.triggered.connect(self._on_close_window)
1610
1611                 if IS_MAEMO:
1612                         self._window.addAction(self._closeWindowAction)
1613                         self._window.addAction(self._app.quitAction)
1614                         self._window.addAction(self._app.fullscreenAction)
1615
1616                         fileMenu = self._window.menuBar().addMenu("&Units")
1617                         fileMenu.addAction(self._chooseFavoritesAction)
1618
1619                         viewMenu = self._window.menuBar().addMenu("&View")
1620                         viewMenu.addAction(self._app.showFavoritesAction)
1621                         viewMenu.addAction(self._app.condensedAction)
1622                         viewMenu.addSeparator()
1623                         viewMenu.addAction(self._app.sortByNameAction)
1624                         viewMenu.addAction(self._app.sortByValueAction)
1625                         viewMenu.addAction(self._app.sortByUnitAction)
1626                         viewMenu.addSeparator()
1627                         viewMenu.addAction(self._app.jumpAction)
1628                         viewMenu.addAction(self._app.recentAction)
1629                 else:
1630                         fileMenu = self._window.menuBar().addMenu("&Units")
1631                         fileMenu.addAction(self._chooseFavoritesAction)
1632                         fileMenu.addAction(self._closeWindowAction)
1633                         fileMenu.addAction(self._app.quitAction)
1634
1635                         viewMenu = self._window.menuBar().addMenu("&View")
1636                         viewMenu.addAction(self._app.showFavoritesAction)
1637                         viewMenu.addAction(self._app.condensedAction)
1638                         viewMenu.addSeparator()
1639                         viewMenu.addAction(self._app.sortByNameAction)
1640                         viewMenu.addAction(self._app.sortByValueAction)
1641                         viewMenu.addAction(self._app.sortByUnitAction)
1642                         viewMenu.addSeparator()
1643                         viewMenu.addAction(self._app.jumpAction)
1644                         viewMenu.addAction(self._app.recentAction)
1645                         viewMenu.addSeparator()
1646                         viewMenu.addAction(self._app.fullscreenAction)
1647
1648                 self._app.sortByNameAction.triggered.connect(self._on_sort_by_name)
1649                 self._app.sortByValueAction.triggered.connect(self._on_sort_by_value)
1650                 self._app.sortByUnitAction.triggered.connect(self._on_sort_by_unit)
1651
1652                 self._window.addAction(self._app.logAction)
1653                 self._window.addAction(self._nextUnitAction)
1654                 self._window.addAction(self._previousUnitAction)
1655                 self._window.addAction(self._chooseFavoritesAction)
1656
1657                 self._update_favorites()
1658                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
1659                 self._window.show()
1660
1661         @property
1662         def window(self):
1663                 return self._window
1664
1665         def show(self):
1666                 for child in self.walk_children():
1667                         child.hide()
1668                 self._window.show()
1669
1670         def hide(self):
1671                 for child in self.walk_children():
1672                         child.hide()
1673                 self._window.hide()
1674
1675         def close(self):
1676                 for child in self.walk_children():
1677                         child.window.destroyed.disconnect(self._on_child_close)
1678                         child.close()
1679                 self._window.close()
1680
1681         def set_fullscreen(self, isFullscreen):
1682                 if isFullscreen:
1683                         self._window.showFullScreen()
1684                 else:
1685                         self._window.showNormal()
1686
1687         def select_unit(self, unitName):
1688                 index = self._unitsModel.index_unit(unitName)
1689                 self._select_unit(index)
1690
1691         def walk_children(self):
1692                 if self._favoritesWindow is not None:
1693                         yield self._favoritesWindow
1694
1695         def _update_favorites(self, force = False):
1696                 if self._app.showFavoritesAction.isChecked():
1697                         unitNames = list(self._unitsModel.get_unit_names())
1698                         for i, unitName in enumerate(unitNames):
1699                                 if unitName in self._app.get_hidden_units(self._categoryName):
1700                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), True)
1701                                 else:
1702                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
1703                 else:
1704                         if force:
1705                                 for i in xrange(len(self._unitsModel)):
1706                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
1707
1708         @misc_utils.log_exception(_moduleLogger)
1709         def _on_show_favorites(self, checked = True):
1710                 if checked:
1711                         unitNames = list(self._unitsModel.get_unit_names())
1712                         for i, unitName in enumerate(unitNames):
1713                                 if unitName in self._app.get_hidden_units(self._categoryName):
1714                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), True)
1715                 else:
1716                         for i in xrange(len(self._unitsModel)):
1717                                 self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
1718
1719         @misc_utils.log_exception(_moduleLogger)
1720         def _on_choose_favorites(self, obj = None):
1721                 assert self._favoritesWindow is None
1722                 self._favoritesWindow = FavoritesWindow(
1723                         self._window,
1724                         self._app,
1725                         unit_data.get_units(self._categoryName),
1726                         self._app.get_hidden_units(self._categoryName)
1727                 )
1728                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
1729                 return self._favoritesWindow
1730
1731         @misc_utils.log_exception(_moduleLogger)
1732         def _on_close_favorites(self, obj = None):
1733                 self._favoritesWindow = None
1734                 self._update_favorites(force=True)
1735
1736         @misc_utils.log_exception(_moduleLogger)
1737         def _on_previous_unit(self, checked = True):
1738                 self._select_unit(self._selectedIndex - 1)
1739
1740         @misc_utils.log_exception(_moduleLogger)
1741         def _on_next_unit(self, checked = True):
1742                 self._select_unit(self._selectedIndex + 1)
1743
1744         @misc_utils.log_exception(_moduleLogger)
1745         def _on_close_window(self, checked = True):
1746                 self.close()
1747
1748         @misc_utils.log_exception(_moduleLogger)
1749         def _on_sort_by_name(self, checked = False):
1750                 self._unitsModel.sort(UnitData.NAME_COLUMN, QtCore.Qt.DescendingOrder)
1751
1752         @misc_utils.log_exception(_moduleLogger)
1753         def _on_sort_by_value(self, checked = False):
1754                 self._unitsModel.sort(UnitData.VALUE_COLUMN_0)
1755
1756         @misc_utils.log_exception(_moduleLogger)
1757         def _on_sort_by_unit(self, checked = False):
1758                 self._unitsModel.sort(UnitData.UNIT_COLUMN, QtCore.Qt.DescendingOrder)
1759
1760         @misc_utils.log_exception(_moduleLogger)
1761         def _on_unit_clicked(self, index):
1762                 self._select_unit(index.row())
1763
1764         @misc_utils.log_exception(_moduleLogger)
1765         def _on_value_edited(self, *args):
1766                 userInput = self._selectedUnitValue.text()
1767                 self._unitsModel.update_values(self._selectedIndex, str(userInput))
1768                 self._update_favorites()
1769
1770         def _select_unit(self, index):
1771                 unit = self._unitsModel.get_unit(index)
1772                 self._selectedUnitName.setText(unit.name)
1773                 self._selectedUnitValue.setText(str(unit.value))
1774                 self._selectedUnitSymbol.setText(unit.unit)
1775
1776                 self._selectedIndex = index
1777                 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
1778                 self._unitsView.scrollTo(qindex)
1779                 self._app.add_recent(self._categoryName, self._unitsModel.get_unit(index).name)
1780
1781
1782 def run_gonvert():
1783         app = QtGui.QApplication([])
1784         handle = Gonvert(app)
1785         return app.exec_()
1786
1787
1788 if __name__ == "__main__":
1789         logging.basicConfig(level = logging.DEBUG)
1790         try:
1791                 os.makedirs(constants._data_path_)
1792         except OSError, e:
1793                 if e.errno != 17:
1794                         raise
1795
1796         val = run_gonvert()
1797         sys.exit(val)