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