First pass at switching to distutils
[gonvert] / gonvert / gonvert_qt.py
1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
3
4 #@todo Research Fn
5 #@todo Research optimizations
6
7 from __future__ import with_statement
8
9 import os
10 import math
11 import simplejson
12 import logging
13 import logging.handlers
14
15 import util.qt_compat as qt_compat
16 QtCore = qt_compat.QtCore
17 QtGui = qt_compat.import_module("QtGui")
18
19 import constants
20 from util import qui_utils
21 from util import misc as misc_utils
22 import unit_data
23
24
25 _moduleLogger = logging.getLogger(__name__)
26
27
28 def split_number(number):
29         if number == 0.0:
30                 # Optimize the startup case
31                 return "0.", "0"
32
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:
45                         if 0.0 < integer:
46                                 integerDisplay = number
47                                 fractionalDisplay = ""
48                         else:
49                                 integerDisplay = ""
50                                 fractionalDisplay = number
51                 else:
52                         integerDisplay = integerDisplay[0:-2] + "."
53                         fractionalDisplay = fractionalDisplay[2:]
54
55         return integerDisplay, fractionalDisplay
56
57
58 class Gonvert(object):
59
60         _DATA_PATHS = [
61                 os.path.dirname(__file__),
62                 os.path.join(os.path.dirname(__file__), "../share"),
63                 os.path.join(os.path.dirname(__file__), "../data"),
64                 '/usr/share/gonvert',
65                 '/opt/gonvert/share',
66         ]
67
68         def __init__(self, app):
69                 self._dataPath = ""
70                 self._app = app
71                 self._appIconPath = ""
72                 self._recent = []
73                 self._hiddenCategories = set()
74                 self._hiddenUnits = {}
75                 self._clipboard = QtGui.QApplication.clipboard()
76
77                 self._jumpWindow = None
78                 self._recentWindow = None
79                 self._mainWindow = None
80                 self._catWindow = None
81                 self._quickWindow = None
82
83                 self._on_jump_close = lambda obj = None: self._on_child_close("_jumpWindow", obj)
84                 self._on_recent_close = lambda obj = None: self._on_child_close("_recentWindow", obj)
85                 self._on_cat_close = lambda obj = None: self._on_child_close("_catWindow", obj)
86                 self._on_quick_close = lambda obj = None: self._on_child_close("_quickWindow", obj)
87
88                 self._condensedAction = QtGui.QAction(None)
89                 self._condensedAction.setText("Condensed View")
90                 self._condensedAction.setCheckable(True)
91                 self._condensedAction.triggered.connect(self._on_condensed_start)
92
93                 self._jumpAction = QtGui.QAction(None)
94                 self._jumpAction.setText("Quick Jump")
95                 self._jumpAction.setStatusTip("Search for a unit and jump straight to it")
96                 self._jumpAction.setToolTip("Search for a unit and jump straight to it")
97                 self._jumpAction.setShortcut(QtGui.QKeySequence("CTRL+j"))
98                 self._jumpAction.triggered.connect(self._on_jump_start)
99
100                 self._recentAction = QtGui.QAction(None)
101                 self._recentAction.setText("Recent Units")
102                 self._recentAction.setStatusTip("View the recent units")
103                 self._recentAction.setToolTip("View the recent units")
104                 self._recentAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
105                 self._recentAction.triggered.connect(self._on_recent_start)
106
107                 self._fullscreenAction = QtGui.QAction(None)
108                 self._fullscreenAction.setText("Fullscreen")
109                 self._fullscreenAction.setCheckable(True)
110                 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
111                 self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
112
113                 self._showFavoritesAction = QtGui.QAction(None)
114                 self._showFavoritesAction.setCheckable(True)
115                 self._showFavoritesAction.setText("Favorites Only")
116
117                 self._sortActionGroup = QtGui.QActionGroup(None)
118                 self._sortByNameAction = QtGui.QAction(self._sortActionGroup)
119                 self._sortByNameAction.setText("Sort By Name")
120                 self._sortByNameAction.setStatusTip("Sort the units by name")
121                 self._sortByNameAction.setToolTip("Sort the units by name")
122                 self._sortByNameAction.setCheckable(True)
123                 self._sortByValueAction = QtGui.QAction(self._sortActionGroup)
124                 self._sortByValueAction.setText("Sort By Value")
125                 self._sortByValueAction.setStatusTip("Sort the units by value")
126                 self._sortByValueAction.setToolTip("Sort the units by value")
127                 self._sortByValueAction.setCheckable(True)
128                 self._sortByUnitAction = QtGui.QAction(self._sortActionGroup)
129                 self._sortByUnitAction.setText("Sort By Unit")
130                 self._sortByUnitAction.setStatusTip("Sort the units by unit")
131                 self._sortByUnitAction.setToolTip("Sort the units by unit")
132                 self._sortByUnitAction.setCheckable(True)
133
134                 self._sortByNameAction.setChecked(True)
135
136                 self._logAction = QtGui.QAction(None)
137                 self._logAction.setText("Log")
138                 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
139                 self._logAction.triggered.connect(self._on_log)
140
141                 self._quitAction = QtGui.QAction(None)
142                 self._quitAction.setText("Quit")
143                 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
144                 self._quitAction.triggered.connect(self._on_quit)
145
146                 self._app.lastWindowClosed.connect(self._on_app_quit)
147                 self.load_settings()
148
149                 self.request_category()
150                 if self._recent:
151                         self._mainWindow.select_category(self._recent[-1][0])
152
153         def request_category(self):
154                 if self._condensedAction.isChecked():
155                         if self._catWindow is not None:
156                                 self._catWindow.hide()
157
158                         if self._quickWindow is None:
159                                 self._quickWindow = QuickConvert(None, self)
160                                 self._quickWindow.window.destroyed.connect(self._on_quick_close)
161                         else:
162                                 self._quickWindow.show()
163
164                         self._mainWindow = self._quickWindow
165                 else:
166                         if self._quickWindow is not None:
167                                 self._quickWindow.hide()
168
169                         if self._catWindow is None:
170                                 self._catWindow = CategoryWindow(None, self)
171                                 self._catWindow.window.destroyed.connect(self._on_cat_close)
172                         else:
173                                 self._catWindow.window.show()
174
175                         self._mainWindow = self._catWindow
176
177                 return self._mainWindow
178
179         def search_units(self):
180                 import windows
181                 jumpWindow = windows.QuickJump(None, self)
182                 jumpWindow.window.destroyed.connect(self._on_jump_close)
183                 self._jumpWindow = jumpWindow
184                 return self._jumpWindow
185
186         def show_recent(self):
187                 import windows
188                 recentWindow = windows.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", True))
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 QuickConvert(object):
412
413         def __init__(self, parent, app):
414                 self._app = app
415                 self._categoryName = ""
416                 self._inputUnitName = ""
417                 self._outputUnitName = ""
418                 self._unitNames = []
419                 self._favoritesWindow = None
420
421                 self._inputUnitValue = QtGui.QLineEdit()
422                 qui_utils.mark_numbers_preferred(self._inputUnitValue)
423                 self._inputUnitValue.textEdited.connect(self._on_value_edited)
424                 self._inputUnitSymbol = QtGui.QLabel()
425
426                 self._outputUnitValue = QtGui.QLineEdit()
427                 qui_utils.mark_numbers_preferred(self._outputUnitValue)
428                 self._outputUnitValue.textEdited.connect(self._on_output_value_edited)
429                 self._outputUnitSymbol = QtGui.QLabel()
430
431                 self._conversionLayout = QtGui.QHBoxLayout()
432                 self._conversionLayout.addWidget(self._inputUnitValue)
433                 self._conversionLayout.addWidget(self._inputUnitSymbol)
434                 self._conversionLayout.addWidget(self._outputUnitValue)
435                 self._conversionLayout.addWidget(self._outputUnitSymbol)
436
437                 self._categoryView = QtGui.QTreeWidget()
438                 self._categoryView.setHeaderLabels(["Categories"])
439                 self._categoryView.setHeaderHidden(False)
440                 self._categoryView.setRootIsDecorated(False)
441                 if not constants.IS_MAEMO:
442                         self._categoryView.setAlternatingRowColors(True)
443                 self._categoryView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
444                 self._categoryView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
445                 for catName in unit_data.UNIT_CATEGORIES:
446                         twi = QtGui.QTreeWidgetItem(self._categoryView)
447                         twi.setText(0, catName)
448                 self._categorySelection = self._categoryView.selectionModel()
449                 self._categorySelection.selectionChanged.connect(self._on_category_selection_changed)
450
451                 self._inputView = QtGui.QTreeWidget()
452                 self._inputView.setHeaderLabels(["From", "Name"])
453                 self._inputView.setHeaderHidden(False)
454                 self._inputView.header().hideSection(1)
455                 self._inputView.setRootIsDecorated(False)
456                 if not constants.IS_MAEMO:
457                         self._inputView.setAlternatingRowColors(True)
458                 self._inputView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
459                 self._inputView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
460                 self._inputSelection = self._inputView.selectionModel()
461                 self._inputSelection.selectionChanged.connect(self._on_input_selection_changed)
462
463                 self._outputView = QtGui.QTreeWidget()
464                 self._outputView.setHeaderLabels(["To", "Name"])
465                 self._outputView.setHeaderHidden(False)
466                 self._outputView.header().hideSection(1)
467                 self._outputView.setRootIsDecorated(False)
468                 if not constants.IS_MAEMO:
469                         self._outputView.setAlternatingRowColors(True)
470                 self._outputView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
471                 self._outputView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
472                 self._outputWidgets = []
473                 self._outputSelection = self._outputView.selectionModel()
474                 self._outputSelection.selectionChanged.connect(self._on_output_selection_changed)
475
476                 self._selectionLayout = QtGui.QHBoxLayout()
477                 self._selectionLayout.addWidget(self._categoryView)
478                 self._selectionLayout.addWidget(self._inputView)
479                 self._selectionLayout.addWidget(self._outputView)
480
481                 self._layout = QtGui.QVBoxLayout()
482                 self._layout.addLayout(self._conversionLayout)
483                 self._layout.addLayout(self._selectionLayout)
484
485                 centralWidget = QtGui.QWidget()
486                 centralWidget.setLayout(self._layout)
487
488                 self._window = QtGui.QMainWindow(parent)
489                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
490                 qui_utils.set_stackable(self._window, True)
491                 self._window.setWindowTitle("%s - Quick Convert" % (constants.__pretty_app_name__, ))
492                 self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
493                 self._window.setCentralWidget(centralWidget)
494
495                 self._chooseCatFavoritesAction = QtGui.QAction(None)
496                 self._chooseCatFavoritesAction.setText("Select Categories")
497                 self._chooseCatFavoritesAction.triggered.connect(self._on_choose_category_favorites)
498
499                 self._chooseUnitFavoritesAction = QtGui.QAction(None)
500                 self._chooseUnitFavoritesAction.setText("Select Units")
501                 self._chooseUnitFavoritesAction.triggered.connect(self._on_choose_unit_favorites)
502                 self._chooseUnitFavoritesAction.setEnabled(False)
503
504                 self._app.showFavoritesAction.toggled.connect(self._on_show_favorites)
505
506                 self._closeWindowAction = QtGui.QAction(None)
507                 self._closeWindowAction.setText("Close Window")
508                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
509                 self._closeWindowAction.triggered.connect(self._on_close_window)
510
511                 if constants.IS_MAEMO:
512                         self._window.addAction(self._closeWindowAction)
513                         self._window.addAction(self._app.quitAction)
514                         self._window.addAction(self._app.fullscreenAction)
515
516                         fileMenu = self._window.menuBar().addMenu("&Units")
517                         fileMenu.addAction(self._chooseCatFavoritesAction)
518                         fileMenu.addAction(self._chooseUnitFavoritesAction)
519
520                         viewMenu = self._window.menuBar().addMenu("&View")
521                         viewMenu.addAction(self._app.showFavoritesAction)
522                         viewMenu.addAction(self._app.condensedAction)
523                         viewMenu.addSeparator()
524                         viewMenu.addAction(self._app.jumpAction)
525                         viewMenu.addAction(self._app.recentAction)
526                 else:
527                         fileMenu = self._window.menuBar().addMenu("&Units")
528                         fileMenu.addAction(self._chooseCatFavoritesAction)
529                         fileMenu.addAction(self._chooseUnitFavoritesAction)
530                         fileMenu.addAction(self._closeWindowAction)
531                         fileMenu.addAction(self._app.quitAction)
532
533                         viewMenu = self._window.menuBar().addMenu("&View")
534                         viewMenu.addAction(self._app.showFavoritesAction)
535                         viewMenu.addAction(self._app.condensedAction)
536                         viewMenu.addSeparator()
537                         viewMenu.addAction(self._app.jumpAction)
538                         viewMenu.addAction(self._app.recentAction)
539                         viewMenu.addSeparator()
540                         viewMenu.addAction(self._app.fullscreenAction)
541
542                 self._window.addAction(self._app.logAction)
543
544                 self._update_favorites()
545                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
546                 self._window.show()
547
548         @property
549         def window(self):
550                 return self._window
551
552         def show(self):
553                 self._window.show()
554
555         def hide(self):
556                 self._window.hide()
557
558         def close(self):
559                 self._window.close()
560
561         def set_fullscreen(self, isFullscreen):
562                 if isFullscreen:
563                         self._window.showFullScreen()
564                 else:
565                         self._window.showNormal()
566
567         def select_category(self, categoryName):
568                 self._select_category(categoryName)
569
570                 i = unit_data.UNIT_CATEGORIES.index(categoryName)
571                 rootIndex = self._categoryView.rootIndex()
572                 currentIndex = self._categoryView.model().index(i, 0, rootIndex)
573                 self._categoryView.scrollTo(currentIndex)
574                 self._categoryView.setItemSelected(self._categoryView.topLevelItem(i), True)
575
576                 return self
577
578         def select_unit(self, name):
579                 self.select_input(name)
580                 return self
581
582         def select_input(self, name):
583                 self._select_input(name)
584
585                 i = self._unitNames.index(name)
586                 rootIndex = self._inputView.rootIndex()
587                 currentIndex = self._inputView.model().index(i, 0, rootIndex)
588                 self._inputView.scrollTo(currentIndex)
589                 self._inputView.setItemSelected(self._inputView.topLevelItem(i), True)
590
591         def select_output(self, name):
592                 self._select_output(name)
593
594                 i = self._unitNames.index(name)
595                 rootIndex = self._outputView.rootIndex()
596                 currentIndex = self._outputView.model().index(i, 0, rootIndex)
597                 self._outputView.scrollTo(currentIndex)
598                 self._outputView.setItemSelected(self._outputView.topLevelItem(i), True)
599
600         def _select_category(self, categoryName):
601                 self._inputUnitName = ""
602                 self._outputUnitName = ""
603                 self._inputUnitValue.setText("")
604                 self._inputUnitSymbol.setText("")
605                 self._inputView.clear()
606                 self._outputUnitValue.setText("")
607                 self._outputUnitSymbol.setText("")
608                 self._outputView.clear()
609                 self._categoryName = categoryName
610                 self._chooseUnitFavoritesAction.setEnabled(True)
611
612                 unitData = unit_data.UNIT_DESCRIPTIONS[categoryName]
613                 self._unitNames = list(unit_data.get_units(categoryName))
614                 self._unitNames.sort()
615                 for key in self._unitNames:
616                         conversion, unit, description = unitData[key]
617                         unit = key
618
619                         twi = QtGui.QTreeWidgetItem(self._inputView)
620                         twi.setText(0, unit)
621                         twi.setText(1, key)
622
623                         twi = QtGui.QTreeWidgetItem(self._outputView)
624                         twi.setText(0, unit)
625                         twi.setText(1, key)
626
627                 defaultInputUnitName = self._app.get_recent_unit(categoryName)
628                 if defaultInputUnitName:
629                         self.select_input(defaultInputUnitName)
630                         defaultOutputUnitName = self._app.get_recent_unit(categoryName, 1)
631                         assert defaultOutputUnitName
632                         self.select_output(defaultOutputUnitName)
633
634         def _select_input(self, name):
635                 self._app.add_recent(self._categoryName, name)
636                 self._inputUnitName = name
637
638                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
639                 conversion, unit, description = unitData[name]
640
641                 self._inputUnitSymbol.setText(unit if unit else name)
642
643                 if "" not in [self._categoryName, self._inputUnitName, self._outputUnitName]:
644                         self._update_output()
645
646         def _select_output(self, name):
647                 # Add the output to recent but don't make things weird by making it the most recent
648                 self._app.add_recent(self._categoryName, name)
649                 self._app.add_recent(self._categoryName, self._inputUnitName)
650                 self._outputUnitName = name
651
652                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
653                 conversion, unit, description = unitData[name]
654
655                 self._outputUnitSymbol.setText(unit if unit else name)
656
657                 if "" not in [self._categoryName, self._inputUnitName, self._outputUnitName]:
658                         self._update_output()
659
660         def _sanitize_value(self, userEntry):
661                 if self._categoryName == "Computer Numbers":
662                         if userEntry == '':
663                                 value = '0'
664                         else:
665                                 value = userEntry
666                 else:
667                         if userEntry == '':
668                                 value = 0.0
669                         else:
670                                 value = float(userEntry)
671                 return value
672
673         def _update_output(self):
674                 assert self._categoryName
675                 assert self._inputUnitName
676                 assert self._outputUnitName
677
678                 userInput = str(self._inputUnitValue.text())
679                 value = self._sanitize_value(userInput)
680
681                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
682                 inputConversion, _, _ = unitData[self._inputUnitName]
683                 outputConversion, _, _ = unitData[self._outputUnitName]
684
685                 func, arg = inputConversion
686                 base = func.to_base(value, arg)
687
688                 func, arg = outputConversion
689                 newValue = func.from_base(base, arg)
690                 self._outputUnitValue.setText(str(newValue))
691
692         def _update_input(self):
693                 assert self._categoryName
694                 assert self._inputUnitName
695                 assert self._outputUnitName
696
697                 userOutput = str(self._outputUnitValue.text())
698                 value = self._sanitize_value(userOutput)
699
700                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
701                 inputConversion, _, _ = unitData[self._inputUnitName]
702                 outputConversion, _, _ = unitData[self._outputUnitName]
703
704                 func, arg = outputConversion
705                 base = func.to_base(value, arg)
706
707                 func, arg = inputConversion
708                 newValue = func.from_base(base, arg)
709                 self._inputUnitValue.setText(str(newValue))
710
711         def _update_favorites(self):
712                 if self._app.showFavoritesAction.isChecked():
713                         assert self._categoryView.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
714                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
715                                 if catName in self._app.hiddenCategories:
716                                         self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), True)
717                                 else:
718                                         self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), False)
719
720                         for i, unitName in enumerate(self._unitNames):
721                                 if unitName in self._app.get_hidden_units(self._categoryName):
722                                         self._inputView.setRowHidden(i, self._inputView.rootIndex(), True)
723                                         self._outputView.setRowHidden(i, self._outputView.rootIndex(), True)
724                                 else:
725                                         self._inputView.setRowHidden(i, self._inputView.rootIndex(), False)
726                                         self._outputView.setRowHidden(i, self._outputView.rootIndex(), False)
727                 else:
728                         for i in xrange(self._categoryView.topLevelItemCount()):
729                                 self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), False)
730
731                         for i in xrange(len(self._unitNames)):
732                                 self._inputView.setRowHidden(i, self._inputView.rootIndex(), False)
733                                 self._outputView.setRowHidden(i, self._outputView.rootIndex(), False)
734
735         @misc_utils.log_exception(_moduleLogger)
736         def _on_close_window(self, checked = True):
737                 self.close()
738
739         @misc_utils.log_exception(_moduleLogger)
740         def _on_show_favorites(self, checked = True):
741                 if checked:
742                         assert self._categoryView.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
743                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
744                                 if catName in self._app.hiddenCategories:
745                                         self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), True)
746
747                         for i, unitName in enumerate(self._unitNames):
748                                 if unitName in self._app.get_hidden_units(self._categoryName):
749                                         self._inputView.setRowHidden(i, self._inputView.rootIndex(), True)
750                                         self._outputView.setRowHidden(i, self._outputView.rootIndex(), True)
751                 else:
752                         for i in xrange(self._categoryView.topLevelItemCount()):
753                                 self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), False)
754
755                         for i in xrange(len(self._unitNames)):
756                                 self._inputView.setRowHidden(i, self._inputView.rootIndex(), False)
757                                 self._outputView.setRowHidden(i, self._outputView.rootIndex(), False)
758
759         @misc_utils.log_exception(_moduleLogger)
760         def _on_choose_category_favorites(self, obj = None):
761                 assert self._favoritesWindow is None
762                 import windows
763                 self._favoritesWindow = windows.FavoritesWindow(
764                         self._window,
765                         self._app,
766                         unit_data.UNIT_CATEGORIES,
767                         self._app.hiddenCategories
768                 )
769                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
770                 return self._favoritesWindow
771
772         @misc_utils.log_exception(_moduleLogger)
773         def _on_choose_unit_favorites(self, obj = None):
774                 assert self._favoritesWindow is None
775                 import windows
776                 self._favoritesWindow = windows.FavoritesWindow(
777                         self._window,
778                         self._app,
779                         unit_data.get_units(self._categoryName),
780                         self._app.get_hidden_units(self._categoryName)
781                 )
782                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
783                 return self._favoritesWindow
784
785         @misc_utils.log_exception(_moduleLogger)
786         def _on_close_favorites(self, obj = None):
787                 self._favoritesWindow = None
788                 self._update_favorites()
789
790         @misc_utils.log_exception(_moduleLogger)
791         def _on_value_edited(self, *args):
792                 self._update_output()
793
794         @misc_utils.log_exception(_moduleLogger)
795         def _on_output_value_edited(self, *args):
796                 self._update_input()
797
798         @misc_utils.log_exception(_moduleLogger)
799         def _on_category_selection_changed(self, selected, deselected):
800                 selectedNames = [
801                         str(item.text(0))
802                         for item in self._categoryView.selectedItems()
803                 ]
804                 assert len(selectedNames) == 1
805                 self._select_category(selectedNames[0])
806
807         @misc_utils.log_exception(_moduleLogger)
808         def _on_input_selection_changed(self, selected, deselected):
809                 selectedNames = [
810                         str(item.text(1))
811                         for item in self._inputView.selectedItems()
812                 ]
813                 if selectedNames:
814                         assert len(selectedNames) == 1
815                         name = selectedNames[0]
816                         self._select_input(name)
817                 else:
818                         pass
819
820         @misc_utils.log_exception(_moduleLogger)
821         def _on_output_selection_changed(self, selected, deselected):
822                 selectedNames = [
823                         str(item.text(1))
824                         for item in self._outputView.selectedItems()
825                 ]
826                 if selectedNames:
827                         assert len(selectedNames) == 1, selectedNames
828                         name = selectedNames[0]
829                         self._select_output(name)
830                 else:
831                         pass
832
833
834 class CategoryWindow(object):
835
836         def __init__(self, parent, app):
837                 self._app = app
838                 self._unitWindow = None
839                 self._favoritesWindow = None
840
841                 self._categories = QtGui.QTreeWidget()
842                 self._categories.setHeaderLabels(["Categories"])
843                 self._categories.itemClicked.connect(self._on_category_clicked)
844                 self._categories.setHeaderHidden(True)
845                 self._categories.setRootIsDecorated(False)
846                 self._categories.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
847                 self._categories.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
848                 if not constants.IS_MAEMO:
849                         self._categories.setAlternatingRowColors(True)
850                 for catName in unit_data.UNIT_CATEGORIES:
851                         twi = QtGui.QTreeWidgetItem(self._categories)
852                         twi.setText(0, catName)
853
854                 self._layout = QtGui.QVBoxLayout()
855                 self._layout.addWidget(self._categories)
856
857                 centralWidget = QtGui.QWidget()
858                 centralWidget.setLayout(self._layout)
859
860                 self._window = QtGui.QMainWindow(parent)
861                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
862                 qui_utils.set_stackable(self._window, True)
863                 self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
864                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
865                 self._window.setCentralWidget(centralWidget)
866
867                 self._chooseFavoritesAction = QtGui.QAction(None)
868                 self._chooseFavoritesAction.setText("Select Favorites")
869                 self._chooseFavoritesAction.setShortcut(QtGui.QKeySequence("CTRL+f"))
870                 self._chooseFavoritesAction.triggered.connect(self._on_choose_favorites)
871
872                 self._app.showFavoritesAction.toggled.connect(self._on_show_favorites)
873
874                 self._closeWindowAction = QtGui.QAction(None)
875                 self._closeWindowAction.setText("Close")
876                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
877                 self._closeWindowAction.triggered.connect(self._on_close_window)
878
879                 if constants.IS_MAEMO:
880                         fileMenu = self._window.menuBar().addMenu("&Units")
881                         fileMenu.addAction(self._chooseFavoritesAction)
882
883                         viewMenu = self._window.menuBar().addMenu("&View")
884                         viewMenu.addAction(self._app.showFavoritesAction)
885                         viewMenu.addAction(self._app.condensedAction)
886                         viewMenu.addSeparator()
887                         viewMenu.addAction(self._app.jumpAction)
888                         viewMenu.addAction(self._app.recentAction)
889
890                         self._window.addAction(self._closeWindowAction)
891                         self._window.addAction(self._app.quitAction)
892                         self._window.addAction(self._app.fullscreenAction)
893                 else:
894                         fileMenu = self._window.menuBar().addMenu("&Units")
895                         fileMenu.addAction(self._chooseFavoritesAction)
896                         fileMenu.addAction(self._closeWindowAction)
897                         fileMenu.addAction(self._app.quitAction)
898
899                         viewMenu = self._window.menuBar().addMenu("&View")
900                         viewMenu.addAction(self._app.showFavoritesAction)
901                         viewMenu.addAction(self._app.condensedAction)
902                         viewMenu.addSeparator()
903                         viewMenu.addAction(self._app.jumpAction)
904                         viewMenu.addAction(self._app.recentAction)
905                         viewMenu.addSeparator()
906                         viewMenu.addAction(self._app.fullscreenAction)
907
908                 self._window.addAction(self._app.logAction)
909
910                 self._update_favorites()
911                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
912                 self._window.show()
913
914         @property
915         def window(self):
916                 return self._window
917
918         def walk_children(self):
919                 if self._unitWindow is not None:
920                         yield self._unitWindow
921                 if self._favoritesWindow is not None:
922                         yield self._favoritesWindow
923
924         def show(self):
925                 self._window.show()
926                 for child in self.walk_children():
927                         child.show()
928
929         def hide(self):
930                 for child in self.walk_children():
931                         child.hide()
932                 self._window.hide()
933
934         def close(self):
935                 for child in self.walk_children():
936                         child.window.destroyed.disconnect(self._on_child_close)
937                         child.close()
938                 self._window.close()
939
940         def select_category(self, categoryName):
941                 self._select_category(categoryName)
942
943                 i = unit_data.UNIT_CATEGORIES.index(categoryName)
944                 rootIndex = self._categories.rootIndex()
945                 currentIndex = self._categories.model().index(i, 0, rootIndex)
946                 self._categories.scrollTo(currentIndex)
947                 self._categories.setItemSelected(self._categories.topLevelItem(i), True)
948                 return self._unitWindow
949
950         def set_fullscreen(self, isFullscreen):
951                 if isFullscreen:
952                         self._window.showFullScreen()
953                 else:
954                         self._window.showNormal()
955                 for child in self.walk_children():
956                         child.set_fullscreen(isFullscreen)
957
958         def _select_category(self, categoryName):
959                 for child in self.walk_children():
960                         child.window.destroyed.disconnect(self._on_child_close)
961                         child.close()
962                 self._unitWindow = UnitWindow(self._window, categoryName, self._app)
963                 self._unitWindow.window.destroyed.connect(self._on_child_close)
964
965         def _update_favorites(self):
966                 if self._app.showFavoritesAction.isChecked():
967                         assert self._categories.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
968                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
969                                 if catName in self._app.hiddenCategories:
970                                         self._categories.setRowHidden(i, self._categories.rootIndex(), True)
971                                 else:
972                                         self._categories.setRowHidden(i, self._categories.rootIndex(), False)
973                 else:
974                         for i in xrange(self._categories.topLevelItemCount()):
975                                 self._categories.setRowHidden(i, self._categories.rootIndex(), False)
976
977         @misc_utils.log_exception(_moduleLogger)
978         def _on_show_favorites(self, checked = True):
979                 if checked:
980                         assert self._categories.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
981                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
982                                 if catName in self._app.hiddenCategories:
983                                         self._categories.setRowHidden(i, self._categories.rootIndex(), True)
984                 else:
985                         for i in xrange(self._categories.topLevelItemCount()):
986                                 self._categories.setRowHidden(i, self._categories.rootIndex(), False)
987
988         @misc_utils.log_exception(_moduleLogger)
989         def _on_choose_favorites(self, obj = None):
990                 assert self._favoritesWindow is None
991                 import windows
992                 self._favoritesWindow = windows.FavoritesWindow(
993                         self._window,
994                         self._app,
995                         unit_data.UNIT_CATEGORIES,
996                         self._app.hiddenCategories
997                 )
998                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
999                 return self._favoritesWindow
1000
1001         @misc_utils.log_exception(_moduleLogger)
1002         def _on_close_favorites(self, obj = None):
1003                 self._favoritesWindow = None
1004                 self._update_favorites()
1005
1006         @misc_utils.log_exception(_moduleLogger)
1007         def _on_child_close(self, obj = None):
1008                 self._unitWindow = None
1009
1010         @misc_utils.log_exception(_moduleLogger)
1011         def _on_close_window(self, checked = True):
1012                 self.close()
1013
1014         @misc_utils.log_exception(_moduleLogger)
1015         def _on_category_clicked(self, item, columnIndex):
1016                 categoryName = unicode(item.text(0))
1017                 self.select_category(categoryName)
1018
1019
1020 class UnitData(object):
1021
1022         HEADERS = ["Name", "Value", "", "Unit"]
1023         ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
1024         NAME_COLUMN = 0
1025         VALUE_COLUMN_0 = 1
1026         VALUE_COLUMN_1 = 2
1027         UNIT_COLUMN = 3
1028
1029         __slots__ = [
1030                 "_name", "_unit", "_description", "_conversion",
1031                 "_value", "_integerDisplay", "_fractionalDisplay",
1032         ]
1033
1034         def __init__(self, name, unit, description, conversion):
1035                 self._name = name
1036                 self._unit = unit
1037                 self._description = description
1038                 self._conversion = conversion
1039
1040                 self._value = 0.0
1041                 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
1042
1043         @property
1044         def name(self):
1045                 return self._name
1046
1047         @property
1048         def value(self):
1049                 return self._value
1050
1051         def update_value(self, newValue):
1052                 self._value = newValue
1053                 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
1054
1055         @property
1056         def unit(self):
1057                 return self._unit
1058
1059         @property
1060         def conversion(self):
1061                 return self._conversion
1062
1063         def data(self, column):
1064                 try:
1065                         return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
1066                 except IndexError:
1067                         return None
1068
1069
1070 class UnitModel(QtCore.QAbstractItemModel):
1071
1072         def __init__(self, categoryName, parent=None):
1073                 super(UnitModel, self).__init__(parent)
1074                 self._categoryName = categoryName
1075                 self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
1076                 if self._categoryName == "Computer Numbers":
1077                         self._sanitize_value = self._sanitize_alpha_value
1078                 else:
1079                         self._sanitize_value = self._sanitize_numeric_value
1080
1081                 self._children = []
1082                 for key in unit_data.get_units(self._categoryName):
1083                         conversion, unit, description = self._unitData[key]
1084                         self._children.append(UnitData(key, unit, description, conversion))
1085                 self._sortSettings = None
1086
1087         @misc_utils.log_exception(_moduleLogger)
1088         def columnCount(self, parent):
1089                 if parent.isValid():
1090                         return 0
1091                 else:
1092                         return len(UnitData.HEADERS)
1093
1094         @misc_utils.log_exception(_moduleLogger)
1095         def data(self, index, role):
1096                 #if not index.isValid():
1097                 #       return None
1098
1099                 if role == QtCore.Qt.DisplayRole:
1100                         item = index.internalPointer()
1101                         if isinstance(item, UnitData):
1102                                 return item.data(index.column())
1103                         elif item is UnitData.HEADERS:
1104                                 return item[index.column()]
1105                 elif role == QtCore.Qt.TextAlignmentRole:
1106                         return UnitData.ALIGNMENT[index.column()]
1107                 else:
1108                         return None
1109
1110         @misc_utils.log_exception(_moduleLogger)
1111         def sort(self, column, order = QtCore.Qt.AscendingOrder):
1112                 self._sortSettings = column, order
1113                 isReverse = order == QtCore.Qt.AscendingOrder
1114                 if column == UnitData.NAME_COLUMN:
1115                         key_func = lambda item: item.name
1116                 elif column in [UnitData.VALUE_COLUMN_0, UnitData.VALUE_COLUMN_1]:
1117                         key_func = lambda item: item.value
1118                 elif column == UnitData.UNIT_COLUMN:
1119                         key_func = lambda item: item.unit
1120                 self._children.sort(key=key_func, reverse = isReverse)
1121
1122                 self._all_changed()
1123
1124         @misc_utils.log_exception(_moduleLogger)
1125         def flags(self, index):
1126                 if not index.isValid():
1127                         return QtCore.Qt.NoItemFlags
1128
1129                 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
1130
1131         @misc_utils.log_exception(_moduleLogger)
1132         def headerData(self, section, orientation, role):
1133                 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
1134                         return UnitData.HEADERS[section]
1135
1136                 return None
1137
1138         @misc_utils.log_exception(_moduleLogger)
1139         def index(self, row, column, parent):
1140                 #if not self.hasIndex(row, column, parent):
1141                 #       return QtCore.QModelIndex()
1142                 #elif parent.isValid():
1143                 #       return QtCore.QModelIndex()
1144
1145                 parentItem = UnitData.HEADERS
1146                 childItem = self._children[row]
1147                 if childItem:
1148                         return self.createIndex(row, column, childItem)
1149                 else:
1150                         return QtCore.QModelIndex()
1151
1152         @misc_utils.log_exception(_moduleLogger)
1153         def parent(self, index):
1154                 if not index.isValid():
1155                         return QtCore.QModelIndex()
1156
1157                 childItem = index.internalPointer()
1158                 if isinstance(childItem, UnitData):
1159                         return QtCore.QModelIndex()
1160                 elif childItem is UnitData.HEADERS:
1161                         return None
1162
1163         @misc_utils.log_exception(_moduleLogger)
1164         def rowCount(self, parent):
1165                 if 0 < parent.column():
1166                         return 0
1167
1168                 if not parent.isValid():
1169                         return len(self._children)
1170                 else:
1171                         return len(self._children)
1172
1173         def get_unit(self, index):
1174                 assert 0 <= index
1175                 return self._children[index]
1176
1177         def get_unit_names(self):
1178                 for child in self._children:
1179                         yield child.name
1180
1181         def index_unit(self, unitName):
1182                 for i, child in enumerate(self._children):
1183                         if child.name == unitName:
1184                                 return i
1185                 else:
1186                         raise RuntimeError("Unit not found")
1187
1188         def update_values(self, fromIndex, userInput):
1189                 value = self._sanitize_value(userInput)
1190                 func, arg = self._children[fromIndex].conversion
1191                 base = func.to_base(value, arg)
1192                 for i, child in enumerate(self._children):
1193                         func, arg = child.conversion
1194                         newValue = func.from_base(base, arg)
1195                         child.update_value(newValue)
1196
1197                 if (
1198                         self._sortSettings is not None and
1199                         self._sortSettings[0]  in [UnitData.VALUE_COLUMN_0, UnitData.VALUE_COLUMN_1]
1200                 ):
1201                         # Sort takes care of marking everything as changed
1202                         self.sort(*self._sortSettings)
1203                         return True
1204                 else:
1205                         self._values_changed()
1206                         return False
1207
1208         def __len__(self):
1209                 return len(self._children)
1210
1211         def _values_changed(self):
1212                 topLeft = self.createIndex(0, UnitData.VALUE_COLUMN_0, self._children[0])
1213                 bottomRight = self.createIndex(len(self._children)-1, UnitData.VALUE_COLUMN_1, self._children[-1])
1214                 self.dataChanged.emit(topLeft, bottomRight)
1215
1216         def _all_changed(self):
1217                 topLeft = self.createIndex(0, 0, self._children[0])
1218                 bottomRight = self.createIndex(len(self._children)-1, len(UnitData.HEADERS)-1, self._children[-1])
1219                 self.dataChanged.emit(topLeft, bottomRight)
1220
1221         def _sanitize_alpha_value(self, userEntry):
1222                 if userEntry:
1223                         value = userEntry
1224                 else:
1225                         value = '0'
1226                 return value
1227
1228         def _sanitize_numeric_value(self, userEntry):
1229                 if userEntry:
1230                         value = float(userEntry)
1231                 else:
1232                         value = 0.0
1233                 return value
1234
1235
1236 class UnitWindow(object):
1237
1238         def __init__(self, parent, category, app):
1239                 self._app = app
1240                 self._categoryName = category
1241                 self._selectedIndex = 0
1242                 self._favoritesWindow = None
1243
1244                 self._selectedUnitName = QtGui.QLabel()
1245                 self._selectedUnitValue = QtGui.QLineEdit()
1246                 self._selectedUnitValue.textEdited.connect(self._on_value_edited)
1247                 qui_utils.mark_numbers_preferred(self._selectedUnitValue)
1248                 self._selectedUnitSymbol = QtGui.QLabel()
1249                 self._updateDelayTimer = QtCore.QTimer()
1250                 self._updateDelayTimer.setInterval(100)
1251                 self._updateDelayTimer.setSingleShot(True)
1252                 self._updateDelayTimer.timeout.connect(self._on_value_edited_delayed)
1253
1254                 self._selectedUnitLayout = QtGui.QHBoxLayout()
1255                 self._selectedUnitLayout.addWidget(self._selectedUnitName)
1256                 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
1257                 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
1258
1259                 self._unitsModel = UnitModel(self._categoryName)
1260                 self._unitsView = QtGui.QTreeView()
1261                 self._unitsView.setModel(self._unitsModel)
1262                 self._unitsView.setUniformRowHeights(True)
1263                 self._unitsView.setSortingEnabled(True)
1264                 self._unitsView.setRootIsDecorated(False)
1265                 self._unitsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
1266                 self._unitsView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
1267                 self._unitsView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
1268                 self._unitsView.setHeaderHidden(True)
1269                 self._unitsView.clicked.connect(self._on_unit_clicked)
1270                 if not constants.IS_MAEMO:
1271                         self._unitsView.setAlternatingRowColors(True)
1272
1273                 viewHeader = self._unitsView.header()
1274                 viewHeader.setSortIndicatorShown(True)
1275                 viewHeader.setClickable(True)
1276
1277                 viewHeader.setResizeMode(UnitData.NAME_COLUMN, QtGui.QHeaderView.ResizeToContents)
1278                 viewHeader.setResizeMode(UnitData.VALUE_COLUMN_0, QtGui.QHeaderView.ResizeToContents)
1279                 viewHeader.setResizeMode(UnitData.VALUE_COLUMN_1, QtGui.QHeaderView.ResizeToContents)
1280                 viewHeader.setResizeMode(UnitData.UNIT_COLUMN, QtGui.QHeaderView.ResizeToContents)
1281                 viewHeader.setStretchLastSection(False)
1282
1283                 # Trying to make things faster by locking in the initial size of the immutable columns
1284                 nameSize = min(viewHeader.sectionSize(UnitData.NAME_COLUMN), 300)
1285                 viewHeader.setResizeMode(UnitData.NAME_COLUMN, QtGui.QHeaderView.Fixed)
1286                 viewHeader.resizeSection(UnitData.NAME_COLUMN, nameSize)
1287                 unitSize = min(viewHeader.sectionSize(UnitData.UNIT_COLUMN), 150)
1288                 viewHeader.setResizeMode(UnitData.UNIT_COLUMN, QtGui.QHeaderView.Fixed)
1289                 viewHeader.resizeSection(UnitData.UNIT_COLUMN, unitSize)
1290
1291                 self._layout = QtGui.QVBoxLayout()
1292                 self._layout.addLayout(self._selectedUnitLayout)
1293                 self._layout.addWidget(self._unitsView)
1294
1295                 centralWidget = QtGui.QWidget()
1296                 centralWidget.setLayout(self._layout)
1297
1298                 self._window = QtGui.QMainWindow(parent)
1299                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
1300                 qui_utils.set_stackable(self._window, True)
1301                 self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
1302                 self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
1303                 self._window.setCentralWidget(centralWidget)
1304
1305                 defaultUnitName = self._app.get_recent_unit(self._categoryName)
1306                 if defaultUnitName:
1307                         self.select_unit(defaultUnitName)
1308                 else:
1309                         self._select_unit(0)
1310
1311                 if self._app.sortByNameAction.isChecked():
1312                         sortColumn = UnitData.NAME_COLUMN
1313                 elif self._app.sortByValueAction.isChecked():
1314                         sortColumn = UnitData.VALUE_COLUMN_0
1315                 elif self._app.sortByUnitAction.isChecked():
1316                         sortColumn = UnitData.UNIT_COLUMN
1317                 else:
1318                         raise RuntimeError("No sort column selected")
1319                 if sortColumn != 0:
1320                         # By default it sorts by he first column (name)
1321                         self._unitsModel.sort(sortColumn)
1322
1323                 self._chooseFavoritesAction = QtGui.QAction(None)
1324                 self._chooseFavoritesAction.setText("Select Favorites")
1325                 self._chooseFavoritesAction.setShortcut(QtGui.QKeySequence("CTRL+f"))
1326                 self._chooseFavoritesAction.triggered.connect(self._on_choose_favorites)
1327
1328                 self._app.showFavoritesAction.toggled.connect(self._on_show_favorites)
1329
1330                 self._previousUnitAction = QtGui.QAction(None)
1331                 self._previousUnitAction.setText("Previous Unit")
1332                 self._previousUnitAction.setShortcut(QtGui.QKeySequence("Up"))
1333                 self._previousUnitAction.triggered.connect(self._on_previous_unit)
1334
1335                 self._nextUnitAction = QtGui.QAction(None)
1336                 self._nextUnitAction.setText("Next Unit")
1337                 self._nextUnitAction.setShortcut(QtGui.QKeySequence("Down"))
1338                 self._nextUnitAction.triggered.connect(self._on_next_unit)
1339
1340                 self._closeWindowAction = QtGui.QAction(None)
1341                 self._closeWindowAction.setText("Close Window")
1342                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
1343                 self._closeWindowAction.triggered.connect(self._on_close_window)
1344
1345                 if constants.IS_MAEMO:
1346                         self._window.addAction(self._closeWindowAction)
1347                         self._window.addAction(self._app.quitAction)
1348                         self._window.addAction(self._app.fullscreenAction)
1349
1350                         fileMenu = self._window.menuBar().addMenu("&Units")
1351                         fileMenu.addAction(self._chooseFavoritesAction)
1352
1353                         viewMenu = self._window.menuBar().addMenu("&View")
1354                         viewMenu.addAction(self._app.showFavoritesAction)
1355                         viewMenu.addAction(self._app.condensedAction)
1356                         viewMenu.addSeparator()
1357                         viewMenu.addAction(self._app.sortByNameAction)
1358                         viewMenu.addAction(self._app.sortByValueAction)
1359                         viewMenu.addAction(self._app.sortByUnitAction)
1360                         viewMenu.addSeparator()
1361                         viewMenu.addAction(self._app.jumpAction)
1362                         viewMenu.addAction(self._app.recentAction)
1363                 else:
1364                         fileMenu = self._window.menuBar().addMenu("&Units")
1365                         fileMenu.addAction(self._chooseFavoritesAction)
1366                         fileMenu.addAction(self._closeWindowAction)
1367                         fileMenu.addAction(self._app.quitAction)
1368
1369                         viewMenu = self._window.menuBar().addMenu("&View")
1370                         viewMenu.addAction(self._app.showFavoritesAction)
1371                         viewMenu.addAction(self._app.condensedAction)
1372                         viewMenu.addSeparator()
1373                         viewMenu.addAction(self._app.sortByNameAction)
1374                         viewMenu.addAction(self._app.sortByValueAction)
1375                         viewMenu.addAction(self._app.sortByUnitAction)
1376                         viewMenu.addSeparator()
1377                         viewMenu.addAction(self._app.jumpAction)
1378                         viewMenu.addAction(self._app.recentAction)
1379                         viewMenu.addSeparator()
1380                         viewMenu.addAction(self._app.fullscreenAction)
1381
1382                 self._app.sortByNameAction.triggered.connect(self._on_sort_by_name)
1383                 self._app.sortByValueAction.triggered.connect(self._on_sort_by_value)
1384                 self._app.sortByUnitAction.triggered.connect(self._on_sort_by_unit)
1385
1386                 self._window.addAction(self._app.logAction)
1387                 self._window.addAction(self._nextUnitAction)
1388                 self._window.addAction(self._previousUnitAction)
1389                 self._window.addAction(self._chooseFavoritesAction)
1390
1391                 self._update_favorites()
1392                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
1393                 self._window.show()
1394
1395         @property
1396         def window(self):
1397                 return self._window
1398
1399         def show(self):
1400                 for child in self.walk_children():
1401                         child.hide()
1402                 self._window.show()
1403
1404         def hide(self):
1405                 for child in self.walk_children():
1406                         child.hide()
1407                 self._window.hide()
1408
1409         def close(self):
1410                 for child in self.walk_children():
1411                         child.window.destroyed.disconnect(self._on_child_close)
1412                         child.close()
1413                 self._window.close()
1414
1415         def set_fullscreen(self, isFullscreen):
1416                 if isFullscreen:
1417                         self._window.showFullScreen()
1418                 else:
1419                         self._window.showNormal()
1420
1421         def select_unit(self, unitName):
1422                 index = self._unitsModel.index_unit(unitName)
1423                 self._select_unit(index)
1424
1425                 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
1426                 self._unitsView.scrollTo(qindex)
1427
1428         def walk_children(self):
1429                 if self._favoritesWindow is not None:
1430                         yield self._favoritesWindow
1431
1432         def _select_unit(self, index):
1433                 unit = self._unitsModel.get_unit(index)
1434                 self._selectedUnitName.setText(unit.name)
1435                 self._selectedUnitValue.setText(str(unit.value))
1436                 self._selectedUnitSymbol.setText(unit.unit)
1437
1438                 self._selectedIndex = index
1439                 self._app.add_recent(self._categoryName, self._unitsModel.get_unit(index).name)
1440
1441         def _update_favorites(self, force = False):
1442                 if self._app.showFavoritesAction.isChecked():
1443                         unitNames = list(self._unitsModel.get_unit_names())
1444                         hiddenUnits = self._app.get_hidden_units(self._categoryName)
1445                         for i, unitName in enumerate(unitNames):
1446                                 if unitName in hiddenUnits:
1447                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), True)
1448                                 else:
1449                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
1450                 else:
1451                         if force:
1452                                 for i in xrange(len(self._unitsModel)):
1453                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
1454
1455         @misc_utils.log_exception(_moduleLogger)
1456         def _on_show_favorites(self, checked = True):
1457                 if checked:
1458                         unitNames = list(self._unitsModel.get_unit_names())
1459                         hiddenUnits = self._app.get_hidden_units(self._categoryName)
1460                         for i, unitName in enumerate(unitNames):
1461                                 if unitName in hiddenUnits:
1462                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), True)
1463                 else:
1464                         for i in xrange(len(self._unitsModel)):
1465                                 self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
1466
1467         @misc_utils.log_exception(_moduleLogger)
1468         def _on_choose_favorites(self, obj = None):
1469                 assert self._favoritesWindow is None
1470                 import windows
1471                 self._favoritesWindow = windows.FavoritesWindow(
1472                         self._window,
1473                         self._app,
1474                         unit_data.get_units(self._categoryName),
1475                         self._app.get_hidden_units(self._categoryName)
1476                 )
1477                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
1478                 return self._favoritesWindow
1479
1480         @misc_utils.log_exception(_moduleLogger)
1481         def _on_close_favorites(self, obj = None):
1482                 self._favoritesWindow = None
1483                 self._update_favorites(force=True)
1484
1485         @misc_utils.log_exception(_moduleLogger)
1486         def _on_previous_unit(self, checked = True):
1487                 index = self._selectedIndex - 1
1488                 unitData = self._unitsModel.get_unit(index)
1489                 unitName = unitData.name
1490
1491                 if self._app.showFavoritesAction.isChecked():
1492                         hiddenUnits = self._app.get_hidden_units(self._categoryName)
1493                         while unitName in hiddenUnits:
1494                                 index -= 1
1495                                 unitData = self._unitsModel.get_unit(index)
1496                                 unitName = unitData.name
1497
1498                 self.select_unit(unitName)
1499
1500         @misc_utils.log_exception(_moduleLogger)
1501         def _on_next_unit(self, checked = True):
1502                 index = self._selectedIndex + 1
1503                 unitData = self._unitsModel.get_unit(index)
1504                 unitName = unitData.name
1505
1506                 if self._app.showFavoritesAction.isChecked():
1507                         hiddenUnits = self._app.get_hidden_units(self._categoryName)
1508                         while unitName in hiddenUnits:
1509                                 index += 1
1510                                 unitData = self._unitsModel.get_unit(index)
1511                                 unitName = unitData.name
1512
1513                 self.select_unit(unitName)
1514
1515         @misc_utils.log_exception(_moduleLogger)
1516         def _on_close_window(self, checked = True):
1517                 self.close()
1518
1519         @misc_utils.log_exception(_moduleLogger)
1520         def _on_sort_by_name(self, checked = False):
1521                 self._unitsModel.sort(UnitData.NAME_COLUMN, QtCore.Qt.DescendingOrder)
1522
1523         @misc_utils.log_exception(_moduleLogger)
1524         def _on_sort_by_value(self, checked = False):
1525                 self._unitsModel.sort(UnitData.VALUE_COLUMN_0)
1526
1527         @misc_utils.log_exception(_moduleLogger)
1528         def _on_sort_by_unit(self, checked = False):
1529                 self._unitsModel.sort(UnitData.UNIT_COLUMN, QtCore.Qt.DescendingOrder)
1530
1531         @misc_utils.log_exception(_moduleLogger)
1532         def _on_unit_clicked(self, index):
1533                 self._select_unit(index.row())
1534
1535         @misc_utils.log_exception(_moduleLogger)
1536         def _on_value_edited(self, *args):
1537                 if not self._updateDelayTimer.isActive():
1538                         self._updateDelayTimer.start()
1539
1540         @misc_utils.log_exception(_moduleLogger)
1541         def _on_value_edited_delayed(self, *args):
1542                 userInput = str(self._selectedUnitValue.text())
1543                 orderChanged = self._unitsModel.update_values(self._selectedIndex, userInput)
1544                 if orderChanged:
1545                         self._update_favorites()
1546
1547
1548 def run_gonvert():
1549         try:
1550                 os.makedirs(constants._data_path_)
1551         except OSError, e:
1552                 if e.errno != 17:
1553                         raise
1554
1555         logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
1556         logging.basicConfig(level=logging.DEBUG, format=logFormat)
1557         rotating = logging.handlers.RotatingFileHandler(constants._user_logpath_, maxBytes=512*1024, backupCount=1)
1558         rotating.setFormatter(logging.Formatter(logFormat))
1559         root = logging.getLogger()
1560         root.addHandler(rotating)
1561         _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
1562         _moduleLogger.info("OS: %s" % (os.uname()[0], ))
1563         _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
1564         _moduleLogger.info("Hostname: %s" % os.uname()[1])
1565
1566         app = QtGui.QApplication([])
1567         handle = Gonvert(app)
1568         if constants.PROFILE_STARTUP:
1569                 return 0
1570         else:
1571                 return app.exec_()
1572
1573
1574 if __name__ == "__main__":
1575         import sys
1576         val = run_gonvert()
1577         sys.exit(val)