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