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