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