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