074c4dea8a4300a3233450f2b46e6f82728a675a
[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                         if not defaultOutputUnitName:
651                                 _moduleLogger.error(
652                                         "Somehow we have an odd numer of items in the history for category %r with only %r present",
653                                         categoryName,
654                                         defaultInputUnitName,
655                                 )
656                                 defaultOutputUnitName = defaultInputUnitName
657                         self.select_output(defaultOutputUnitName)
658
659         def _select_input(self, name):
660                 self._app.add_recent(self._categoryName, name)
661                 self._inputUnitName = name
662
663                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
664                 conversion, unit, description = unitData[name]
665
666                 self._inputUnitSymbol.setText(unit if unit else name)
667
668                 if "" not in [self._categoryName, self._inputUnitName, self._outputUnitName]:
669                         self._update_output()
670
671         def _select_output(self, name):
672                 # Add the output to recent but don't make things weird by making it the most recent
673                 self._app.add_recent(self._categoryName, name)
674                 self._app.add_recent(self._categoryName, self._inputUnitName)
675                 self._outputUnitName = name
676
677                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
678                 conversion, unit, description = unitData[name]
679
680                 self._outputUnitSymbol.setText(unit if unit else name)
681
682                 if "" not in [self._categoryName, self._inputUnitName, self._outputUnitName]:
683                         self._update_output()
684
685         def _sanitize_value(self, userEntry):
686                 if self._categoryName == "Computer Numbers":
687                         if userEntry == '':
688                                 value = '0'
689                         else:
690                                 value = userEntry
691                 else:
692                         if userEntry == '':
693                                 value = 0.0
694                         else:
695                                 value = float(userEntry)
696                 return value
697
698         def _update_output(self):
699                 assert self._categoryName
700                 assert self._inputUnitName
701                 assert self._outputUnitName
702
703                 userInput = str(self._inputUnitValue.text())
704                 value = self._sanitize_value(userInput)
705
706                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
707                 inputConversion, _, _ = unitData[self._inputUnitName]
708                 outputConversion, _, _ = unitData[self._outputUnitName]
709
710                 func, arg = inputConversion
711                 base = func.to_base(value, arg)
712
713                 func, arg = outputConversion
714                 newValue = func.from_base(base, arg)
715                 self._outputUnitValue.setText(str(newValue))
716
717         def _update_input(self):
718                 assert self._categoryName
719                 assert self._inputUnitName
720                 assert self._outputUnitName
721
722                 userOutput = str(self._outputUnitValue.text())
723                 value = self._sanitize_value(userOutput)
724
725                 unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
726                 inputConversion, _, _ = unitData[self._inputUnitName]
727                 outputConversion, _, _ = unitData[self._outputUnitName]
728
729                 func, arg = outputConversion
730                 base = func.to_base(value, arg)
731
732                 func, arg = inputConversion
733                 newValue = func.from_base(base, arg)
734                 self._inputUnitValue.setText(str(newValue))
735
736         def _update_favorites(self):
737                 if self._app.showFavoritesAction.isChecked():
738                         assert self._categoryView.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
739                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
740                                 if catName in self._app.hiddenCategories:
741                                         self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), True)
742                                 else:
743                                         self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), False)
744
745                         for i, unitName in enumerate(self._unitNames):
746                                 if unitName in self._app.get_hidden_units(self._categoryName):
747                                         self._inputView.setRowHidden(i, self._inputView.rootIndex(), True)
748                                         self._outputView.setRowHidden(i, self._outputView.rootIndex(), True)
749                                 else:
750                                         self._inputView.setRowHidden(i, self._inputView.rootIndex(), False)
751                                         self._outputView.setRowHidden(i, self._outputView.rootIndex(), False)
752                 else:
753                         for i in xrange(self._categoryView.topLevelItemCount()):
754                                 self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), False)
755
756                         for i in xrange(len(self._unitNames)):
757                                 self._inputView.setRowHidden(i, self._inputView.rootIndex(), False)
758                                 self._outputView.setRowHidden(i, self._outputView.rootIndex(), False)
759
760         @misc_utils.log_exception(_moduleLogger)
761         def _on_close_window(self, checked = True):
762                 self.close()
763
764         @misc_utils.log_exception(_moduleLogger)
765         def _on_show_favorites(self, checked = True):
766                 if checked:
767                         assert self._categoryView.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
768                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
769                                 if catName in self._app.hiddenCategories:
770                                         self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), True)
771
772                         for i, unitName in enumerate(self._unitNames):
773                                 if unitName in self._app.get_hidden_units(self._categoryName):
774                                         self._inputView.setRowHidden(i, self._inputView.rootIndex(), True)
775                                         self._outputView.setRowHidden(i, self._outputView.rootIndex(), True)
776                 else:
777                         for i in xrange(self._categoryView.topLevelItemCount()):
778                                 self._categoryView.setRowHidden(i, self._categoryView.rootIndex(), False)
779
780                         for i in xrange(len(self._unitNames)):
781                                 self._inputView.setRowHidden(i, self._inputView.rootIndex(), False)
782                                 self._outputView.setRowHidden(i, self._outputView.rootIndex(), False)
783
784         @misc_utils.log_exception(_moduleLogger)
785         def _on_choose_category_favorites(self, obj = None):
786                 assert self._favoritesWindow is None
787                 import windows
788                 self._favoritesWindow = windows.FavoritesWindow(
789                         self._window,
790                         self._app,
791                         unit_data.UNIT_CATEGORIES,
792                         self._app.hiddenCategories
793                 )
794                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
795                 return self._favoritesWindow
796
797         @misc_utils.log_exception(_moduleLogger)
798         def _on_choose_unit_favorites(self, obj = None):
799                 assert self._favoritesWindow is None
800                 import windows
801                 self._favoritesWindow = windows.FavoritesWindow(
802                         self._window,
803                         self._app,
804                         unit_data.get_units(self._categoryName),
805                         self._app.get_hidden_units(self._categoryName)
806                 )
807                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
808                 return self._favoritesWindow
809
810         @misc_utils.log_exception(_moduleLogger)
811         def _on_close_favorites(self, obj = None):
812                 self._favoritesWindow = None
813                 self._update_favorites()
814
815         @misc_utils.log_exception(_moduleLogger)
816         def _on_value_edited(self, *args):
817                 self._update_output()
818
819         @misc_utils.log_exception(_moduleLogger)
820         def _on_output_value_edited(self, *args):
821                 self._update_input()
822
823         @misc_utils.log_exception(_moduleLogger)
824         def _on_category_selection_changed(self, selected, deselected):
825                 selectedNames = [
826                         str(item.text(0))
827                         for item in self._categoryView.selectedItems()
828                 ]
829                 if selectedNames:
830                         self._select_category(selectedNames[0])
831
832         @misc_utils.log_exception(_moduleLogger)
833         def _on_input_selection_changed(self, selected, deselected):
834                 selectedNames = [
835                         str(item.text(1))
836                         for item in self._inputView.selectedItems()
837                 ]
838                 if selectedNames:
839                         assert len(selectedNames) == 1
840                         name = selectedNames[0]
841                         self._select_input(name)
842                 else:
843                         pass
844
845         @misc_utils.log_exception(_moduleLogger)
846         def _on_output_selection_changed(self, selected, deselected):
847                 selectedNames = [
848                         str(item.text(1))
849                         for item in self._outputView.selectedItems()
850                 ]
851                 if selectedNames:
852                         assert len(selectedNames) == 1, selectedNames
853                         name = selectedNames[0]
854                         self._select_output(name)
855                 else:
856                         pass
857
858
859 class CategoryWindow(object):
860
861         def __init__(self, parent, app):
862                 self._app = app
863                 self._unitWindow = None
864                 self._favoritesWindow = None
865
866                 self._categories = QtGui.QTreeWidget()
867                 self._categories.setHeaderLabels(["Categories"])
868                 self._categories.itemClicked.connect(self._on_category_clicked)
869                 self._categories.setHeaderHidden(True)
870                 self._categories.setRootIsDecorated(False)
871                 self._categories.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
872                 self._categories.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
873                 if not constants.IS_MAEMO:
874                         self._categories.setAlternatingRowColors(True)
875                 for catName in unit_data.UNIT_CATEGORIES:
876                         twi = QtGui.QTreeWidgetItem(self._categories)
877                         twi.setText(0, catName)
878
879                 self._layout = QtGui.QVBoxLayout()
880                 self._layout.addWidget(self._categories)
881
882                 centralWidget = QtGui.QWidget()
883                 centralWidget.setLayout(self._layout)
884
885                 self._window = QtGui.QMainWindow(parent)
886                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
887                 qui_utils.set_stackable(self._window, True)
888                 self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
889                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
890                 self._window.setCentralWidget(centralWidget)
891
892                 self._chooseFavoritesAction = QtGui.QAction(None)
893                 self._chooseFavoritesAction.setText("Select Favorites")
894                 self._chooseFavoritesAction.setShortcut(QtGui.QKeySequence("CTRL+f"))
895                 self._chooseFavoritesAction.triggered.connect(self._on_choose_favorites)
896
897                 self._app.showFavoritesAction.toggled.connect(self._on_show_favorites)
898
899                 self._closeWindowAction = QtGui.QAction(None)
900                 self._closeWindowAction.setText("Close")
901                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
902                 self._closeWindowAction.triggered.connect(self._on_close_window)
903
904                 if constants.IS_MAEMO:
905                         fileMenu = self._window.menuBar().addMenu("&Units")
906                         fileMenu.addAction(self._chooseFavoritesAction)
907
908                         viewMenu = self._window.menuBar().addMenu("&View")
909                         viewMenu.addAction(self._app.showFavoritesAction)
910                         viewMenu.addAction(self._app.condensedAction)
911                         viewMenu.addSeparator()
912                         viewMenu.addAction(self._app.jumpAction)
913                         viewMenu.addAction(self._app.recentAction)
914
915                         self._window.addAction(self._closeWindowAction)
916                         self._window.addAction(self._app.quitAction)
917                         self._window.addAction(self._app.fullscreenAction)
918                 else:
919                         fileMenu = self._window.menuBar().addMenu("&Units")
920                         fileMenu.addAction(self._chooseFavoritesAction)
921                         fileMenu.addAction(self._closeWindowAction)
922                         fileMenu.addAction(self._app.quitAction)
923
924                         viewMenu = self._window.menuBar().addMenu("&View")
925                         viewMenu.addAction(self._app.showFavoritesAction)
926                         viewMenu.addAction(self._app.condensedAction)
927                         viewMenu.addSeparator()
928                         viewMenu.addAction(self._app.jumpAction)
929                         viewMenu.addAction(self._app.recentAction)
930                         viewMenu.addSeparator()
931                         viewMenu.addAction(self._app.fullscreenAction)
932
933                 self._window.addAction(self._app.logAction)
934
935                 self._update_favorites()
936                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
937                 self._window.show()
938
939         @property
940         def window(self):
941                 return self._window
942
943         def walk_children(self):
944                 if self._unitWindow is not None:
945                         yield self._unitWindow
946                 if self._favoritesWindow is not None:
947                         yield self._favoritesWindow
948
949         def show(self):
950                 self._window.show()
951                 for child in self.walk_children():
952                         child.show()
953
954         def hide(self):
955                 for child in self.walk_children():
956                         child.hide()
957                 self._window.hide()
958
959         def close(self):
960                 for child in self.walk_children():
961                         child.window.destroyed.disconnect(self._on_child_close)
962                         child.close()
963                 self._window.close()
964
965         def select_category(self, categoryName):
966                 self._select_category(categoryName)
967
968                 self._categories.clearSelection()
969                 i = unit_data.UNIT_CATEGORIES.index(categoryName)
970                 rootIndex = self._categories.rootIndex()
971                 currentIndex = self._categories.model().index(i, 0, rootIndex)
972                 self._categories.scrollTo(currentIndex)
973                 self._categories.topLevelItem(i).setSelected(True)
974                 return self._unitWindow
975
976         def set_fullscreen(self, isFullscreen):
977                 if isFullscreen:
978                         self._window.showFullScreen()
979                 else:
980                         self._window.showNormal()
981                 for child in self.walk_children():
982                         child.set_fullscreen(isFullscreen)
983
984         def _select_category(self, categoryName):
985                 for child in self.walk_children():
986                         child.window.destroyed.disconnect(self._on_child_close)
987                         child.close()
988                 self._unitWindow = UnitWindow(self._window, categoryName, self._app)
989                 self._unitWindow.window.destroyed.connect(self._on_child_close)
990
991         def _update_favorites(self):
992                 if self._app.showFavoritesAction.isChecked():
993                         assert self._categories.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
994                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
995                                 if catName in self._app.hiddenCategories:
996                                         self._categories.setRowHidden(i, self._categories.rootIndex(), True)
997                                 else:
998                                         self._categories.setRowHidden(i, self._categories.rootIndex(), False)
999                 else:
1000                         for i in xrange(self._categories.topLevelItemCount()):
1001                                 self._categories.setRowHidden(i, self._categories.rootIndex(), False)
1002
1003         @misc_utils.log_exception(_moduleLogger)
1004         def _on_show_favorites(self, checked = True):
1005                 if checked:
1006                         assert self._categories.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
1007                         for i, catName in enumerate(unit_data.UNIT_CATEGORIES):
1008                                 if catName in self._app.hiddenCategories:
1009                                         self._categories.setRowHidden(i, self._categories.rootIndex(), True)
1010                 else:
1011                         for i in xrange(self._categories.topLevelItemCount()):
1012                                 self._categories.setRowHidden(i, self._categories.rootIndex(), False)
1013
1014         @misc_utils.log_exception(_moduleLogger)
1015         def _on_choose_favorites(self, obj = None):
1016                 assert self._favoritesWindow is None
1017                 import windows
1018                 self._favoritesWindow = windows.FavoritesWindow(
1019                         self._window,
1020                         self._app,
1021                         unit_data.UNIT_CATEGORIES,
1022                         self._app.hiddenCategories
1023                 )
1024                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
1025                 return self._favoritesWindow
1026
1027         @misc_utils.log_exception(_moduleLogger)
1028         def _on_close_favorites(self, obj = None):
1029                 self._favoritesWindow = None
1030                 self._update_favorites()
1031
1032         @misc_utils.log_exception(_moduleLogger)
1033         def _on_child_close(self, obj = None):
1034                 self._unitWindow = None
1035
1036         @misc_utils.log_exception(_moduleLogger)
1037         def _on_close_window(self, checked = True):
1038                 self.close()
1039
1040         @misc_utils.log_exception(_moduleLogger)
1041         def _on_category_clicked(self, item, columnIndex):
1042                 categoryName = unicode(item.text(0))
1043                 self.select_category(categoryName)
1044
1045
1046 class UnitData(object):
1047
1048         HEADERS = ["Name", "Value", "", "Unit"]
1049         ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
1050         NAME_COLUMN = 0
1051         VALUE_COLUMN_0 = 1
1052         VALUE_COLUMN_1 = 2
1053         UNIT_COLUMN = 3
1054
1055         __slots__ = [
1056                 "_name", "_unit", "_description", "_conversion",
1057                 "_value", "_integerDisplay", "_fractionalDisplay",
1058         ]
1059
1060         def __init__(self, name, unit, description, conversion):
1061                 self._name = name
1062                 self._unit = unit
1063                 self._description = description
1064                 self._conversion = conversion
1065
1066                 self._value = 0.0
1067                 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
1068
1069         @property
1070         def name(self):
1071                 return self._name
1072
1073         @property
1074         def value(self):
1075                 return self._value
1076
1077         def update_value(self, newValue):
1078                 self._value = newValue
1079                 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
1080
1081         @property
1082         def unit(self):
1083                 return self._unit
1084
1085         @property
1086         def conversion(self):
1087                 return self._conversion
1088
1089         def data(self, column):
1090                 try:
1091                         return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
1092                 except IndexError:
1093                         return None
1094
1095
1096 class UnitModel(QtCore.QAbstractItemModel):
1097
1098         def __init__(self, categoryName, parent=None):
1099                 super(UnitModel, self).__init__(parent)
1100                 self._categoryName = categoryName
1101                 self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
1102                 if self._categoryName == "Computer Numbers":
1103                         self._sanitize_value = self._sanitize_alpha_value
1104                 else:
1105                         self._sanitize_value = self._sanitize_numeric_value
1106
1107                 self._children = []
1108                 for key in unit_data.get_units(self._categoryName):
1109                         conversion, unit, description = self._unitData[key]
1110                         self._children.append(UnitData(key, unit, description, conversion))
1111                 self._sortSettings = None
1112
1113         @misc_utils.log_exception(_moduleLogger)
1114         def columnCount(self, parent):
1115                 if parent.isValid():
1116                         return 0
1117                 else:
1118                         return len(UnitData.HEADERS)
1119
1120         @misc_utils.log_exception(_moduleLogger)
1121         def data(self, index, role):
1122                 #if not index.isValid():
1123                 #       return None
1124
1125                 if role == QtCore.Qt.DisplayRole:
1126                         item = index.internalPointer()
1127                         if isinstance(item, UnitData):
1128                                 return item.data(index.column())
1129                         elif item is UnitData.HEADERS:
1130                                 return item[index.column()]
1131                 elif role == QtCore.Qt.TextAlignmentRole:
1132                         return UnitData.ALIGNMENT[index.column()]
1133                 else:
1134                         return None
1135
1136         @misc_utils.log_exception(_moduleLogger)
1137         def sort(self, column, order = QtCore.Qt.AscendingOrder):
1138                 self._sortSettings = column, order
1139                 isReverse = order == QtCore.Qt.AscendingOrder
1140                 if column == UnitData.NAME_COLUMN:
1141                         key_func = lambda item: item.name
1142                 elif column in [UnitData.VALUE_COLUMN_0, UnitData.VALUE_COLUMN_1]:
1143                         key_func = lambda item: item.value
1144                 elif column == UnitData.UNIT_COLUMN:
1145                         key_func = lambda item: item.unit
1146                 self._children.sort(key=key_func, reverse = isReverse)
1147
1148                 self._all_changed()
1149
1150         @misc_utils.log_exception(_moduleLogger)
1151         def flags(self, index):
1152                 if not index.isValid():
1153                         return QtCore.Qt.NoItemFlags
1154
1155                 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
1156
1157         @misc_utils.log_exception(_moduleLogger)
1158         def headerData(self, section, orientation, role):
1159                 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
1160                         return UnitData.HEADERS[section]
1161
1162                 return None
1163
1164         @misc_utils.log_exception(_moduleLogger)
1165         def index(self, row, column, parent):
1166                 #if not self.hasIndex(row, column, parent):
1167                 #       return QtCore.QModelIndex()
1168                 #elif parent.isValid():
1169                 #       return QtCore.QModelIndex()
1170
1171                 parentItem = UnitData.HEADERS
1172                 childItem = self._children[row]
1173                 if childItem:
1174                         return self.createIndex(row, column, childItem)
1175                 else:
1176                         return QtCore.QModelIndex()
1177
1178         @misc_utils.log_exception(_moduleLogger)
1179         def parent(self, index):
1180                 if not index.isValid():
1181                         return QtCore.QModelIndex()
1182
1183                 childItem = index.internalPointer()
1184                 if isinstance(childItem, UnitData):
1185                         return QtCore.QModelIndex()
1186                 elif childItem is UnitData.HEADERS:
1187                         return None
1188
1189         @misc_utils.log_exception(_moduleLogger)
1190         def rowCount(self, parent):
1191                 if 0 < parent.column():
1192                         return 0
1193
1194                 if not parent.isValid():
1195                         return len(self._children)
1196                 else:
1197                         return len(self._children)
1198
1199         def get_unit(self, index):
1200                 assert 0 <= index
1201                 return self._children[index]
1202
1203         def get_unit_names(self):
1204                 for child in self._children:
1205                         yield child.name
1206
1207         def index_unit(self, unitName):
1208                 for i, child in enumerate(self._children):
1209                         if child.name == unitName:
1210                                 return i
1211                 else:
1212                         raise RuntimeError("Unit not found")
1213
1214         def update_values(self, fromIndex, userInput):
1215                 value = self._sanitize_value(userInput)
1216                 func, arg = self._children[fromIndex].conversion
1217                 base = func.to_base(value, arg)
1218                 for i, child in enumerate(self._children):
1219                         func, arg = child.conversion
1220                         newValue = func.from_base(base, arg)
1221                         child.update_value(newValue)
1222
1223                 if (
1224                         self._sortSettings is not None and
1225                         self._sortSettings[0]  in [UnitData.VALUE_COLUMN_0, UnitData.VALUE_COLUMN_1]
1226                 ):
1227                         # Sort takes care of marking everything as changed
1228                         self.sort(*self._sortSettings)
1229                         return True
1230                 else:
1231                         self._values_changed()
1232                         return False
1233
1234         def __len__(self):
1235                 return len(self._children)
1236
1237         def _values_changed(self):
1238                 topLeft = self.createIndex(0, UnitData.VALUE_COLUMN_0, self._children[0])
1239                 bottomRight = self.createIndex(len(self._children)-1, UnitData.VALUE_COLUMN_1, self._children[-1])
1240                 self.dataChanged.emit(topLeft, bottomRight)
1241
1242         def _all_changed(self):
1243                 topLeft = self.createIndex(0, 0, self._children[0])
1244                 bottomRight = self.createIndex(len(self._children)-1, len(UnitData.HEADERS)-1, self._children[-1])
1245                 self.dataChanged.emit(topLeft, bottomRight)
1246
1247         def _sanitize_alpha_value(self, userEntry):
1248                 if userEntry:
1249                         value = userEntry
1250                 else:
1251                         value = '0'
1252                 return value
1253
1254         def _sanitize_numeric_value(self, userEntry):
1255                 if userEntry:
1256                         value = float(userEntry)
1257                 else:
1258                         value = 0.0
1259                 return value
1260
1261
1262 class UnitWindow(object):
1263
1264         def __init__(self, parent, category, app):
1265                 self._app = app
1266                 self._categoryName = category
1267                 self._selectedIndex = 0
1268                 self._favoritesWindow = None
1269
1270                 self._selectedUnitName = QtGui.QLabel()
1271                 self._selectedUnitValue = QtGui.QLineEdit()
1272                 self._selectedUnitValue.textEdited.connect(self._on_value_edited)
1273                 qui_utils.mark_numbers_preferred(self._selectedUnitValue)
1274                 self._selectedUnitSymbol = QtGui.QLabel()
1275                 self._updateDelayTimer = QtCore.QTimer()
1276                 self._updateDelayTimer.setInterval(100)
1277                 self._updateDelayTimer.setSingleShot(True)
1278                 self._updateDelayTimer.timeout.connect(self._on_value_edited_delayed)
1279
1280                 self._selectedUnitLayout = QtGui.QHBoxLayout()
1281                 self._selectedUnitLayout.addWidget(self._selectedUnitName)
1282                 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
1283                 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
1284
1285                 self._unitsModel = UnitModel(self._categoryName)
1286                 self._unitsView = QtGui.QTreeView()
1287                 self._unitsView.setModel(self._unitsModel)
1288                 self._unitsView.setUniformRowHeights(True)
1289                 self._unitsView.setSortingEnabled(True)
1290                 self._unitsView.setRootIsDecorated(False)
1291                 self._unitsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
1292                 self._unitsView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
1293                 self._unitsView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
1294                 self._unitsView.setHeaderHidden(True)
1295                 self._unitsView.clicked.connect(self._on_unit_clicked)
1296                 if not constants.IS_MAEMO:
1297                         self._unitsView.setAlternatingRowColors(True)
1298
1299                 viewHeader = self._unitsView.header()
1300                 viewHeader.setSortIndicatorShown(True)
1301                 viewHeader.setClickable(True)
1302
1303                 viewHeader.setResizeMode(UnitData.NAME_COLUMN, QtGui.QHeaderView.ResizeToContents)
1304                 viewHeader.setResizeMode(UnitData.VALUE_COLUMN_0, QtGui.QHeaderView.ResizeToContents)
1305                 viewHeader.setResizeMode(UnitData.VALUE_COLUMN_1, QtGui.QHeaderView.ResizeToContents)
1306                 viewHeader.setResizeMode(UnitData.UNIT_COLUMN, QtGui.QHeaderView.ResizeToContents)
1307                 viewHeader.setStretchLastSection(False)
1308
1309                 # Trying to make things faster by locking in the initial size of the immutable columns
1310                 nameSize = min(viewHeader.sectionSize(UnitData.NAME_COLUMN), 300)
1311                 viewHeader.setResizeMode(UnitData.NAME_COLUMN, QtGui.QHeaderView.Fixed)
1312                 viewHeader.resizeSection(UnitData.NAME_COLUMN, nameSize)
1313                 unitSize = min(viewHeader.sectionSize(UnitData.UNIT_COLUMN), 150)
1314                 viewHeader.setResizeMode(UnitData.UNIT_COLUMN, QtGui.QHeaderView.Fixed)
1315                 viewHeader.resizeSection(UnitData.UNIT_COLUMN, unitSize)
1316
1317                 self._layout = QtGui.QVBoxLayout()
1318                 self._layout.addLayout(self._selectedUnitLayout)
1319                 self._layout.addWidget(self._unitsView)
1320
1321                 centralWidget = QtGui.QWidget()
1322                 centralWidget.setLayout(self._layout)
1323
1324                 self._window = QtGui.QMainWindow(parent)
1325                 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
1326                 qui_utils.set_stackable(self._window, True)
1327                 self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
1328                 self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
1329                 self._window.setCentralWidget(centralWidget)
1330
1331                 defaultUnitName = self._app.get_recent_unit(self._categoryName)
1332                 if defaultUnitName:
1333                         self.select_unit(defaultUnitName)
1334                 else:
1335                         self._select_unit(0)
1336
1337                 if self._app.sortByNameAction.isChecked():
1338                         sortColumn = UnitData.NAME_COLUMN
1339                 elif self._app.sortByValueAction.isChecked():
1340                         sortColumn = UnitData.VALUE_COLUMN_0
1341                 elif self._app.sortByUnitAction.isChecked():
1342                         sortColumn = UnitData.UNIT_COLUMN
1343                 else:
1344                         raise RuntimeError("No sort column selected")
1345                 if sortColumn != 0:
1346                         # By default it sorts by he first column (name)
1347                         self._unitsModel.sort(sortColumn)
1348
1349                 self._chooseFavoritesAction = QtGui.QAction(None)
1350                 self._chooseFavoritesAction.setText("Select Favorites")
1351                 self._chooseFavoritesAction.setShortcut(QtGui.QKeySequence("CTRL+f"))
1352                 self._chooseFavoritesAction.triggered.connect(self._on_choose_favorites)
1353
1354                 self._app.showFavoritesAction.toggled.connect(self._on_show_favorites)
1355
1356                 self._previousUnitAction = QtGui.QAction(None)
1357                 self._previousUnitAction.setText("Previous Unit")
1358                 self._previousUnitAction.setShortcut(QtGui.QKeySequence("Up"))
1359                 self._previousUnitAction.triggered.connect(self._on_previous_unit)
1360
1361                 self._nextUnitAction = QtGui.QAction(None)
1362                 self._nextUnitAction.setText("Next Unit")
1363                 self._nextUnitAction.setShortcut(QtGui.QKeySequence("Down"))
1364                 self._nextUnitAction.triggered.connect(self._on_next_unit)
1365
1366                 self._closeWindowAction = QtGui.QAction(None)
1367                 self._closeWindowAction.setText("Close Window")
1368                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
1369                 self._closeWindowAction.triggered.connect(self._on_close_window)
1370
1371                 if constants.IS_MAEMO:
1372                         self._window.addAction(self._closeWindowAction)
1373                         self._window.addAction(self._app.quitAction)
1374                         self._window.addAction(self._app.fullscreenAction)
1375
1376                         fileMenu = self._window.menuBar().addMenu("&Units")
1377                         fileMenu.addAction(self._chooseFavoritesAction)
1378
1379                         viewMenu = self._window.menuBar().addMenu("&View")
1380                         viewMenu.addAction(self._app.showFavoritesAction)
1381                         viewMenu.addAction(self._app.condensedAction)
1382                         viewMenu.addSeparator()
1383                         viewMenu.addAction(self._app.sortByNameAction)
1384                         viewMenu.addAction(self._app.sortByValueAction)
1385                         viewMenu.addAction(self._app.sortByUnitAction)
1386                         viewMenu.addSeparator()
1387                         viewMenu.addAction(self._app.jumpAction)
1388                         viewMenu.addAction(self._app.recentAction)
1389                 else:
1390                         fileMenu = self._window.menuBar().addMenu("&Units")
1391                         fileMenu.addAction(self._chooseFavoritesAction)
1392                         fileMenu.addAction(self._closeWindowAction)
1393                         fileMenu.addAction(self._app.quitAction)
1394
1395                         viewMenu = self._window.menuBar().addMenu("&View")
1396                         viewMenu.addAction(self._app.showFavoritesAction)
1397                         viewMenu.addAction(self._app.condensedAction)
1398                         viewMenu.addSeparator()
1399                         viewMenu.addAction(self._app.sortByNameAction)
1400                         viewMenu.addAction(self._app.sortByValueAction)
1401                         viewMenu.addAction(self._app.sortByUnitAction)
1402                         viewMenu.addSeparator()
1403                         viewMenu.addAction(self._app.jumpAction)
1404                         viewMenu.addAction(self._app.recentAction)
1405                         viewMenu.addSeparator()
1406                         viewMenu.addAction(self._app.fullscreenAction)
1407
1408                 self._app.sortByNameAction.triggered.connect(self._on_sort_by_name)
1409                 self._app.sortByValueAction.triggered.connect(self._on_sort_by_value)
1410                 self._app.sortByUnitAction.triggered.connect(self._on_sort_by_unit)
1411
1412                 self._window.addAction(self._app.logAction)
1413                 self._window.addAction(self._nextUnitAction)
1414                 self._window.addAction(self._previousUnitAction)
1415                 self._window.addAction(self._chooseFavoritesAction)
1416
1417                 self._update_favorites()
1418                 self.set_fullscreen(self._app.fullscreenAction.isChecked())
1419                 self._window.show()
1420
1421         @property
1422         def window(self):
1423                 return self._window
1424
1425         def show(self):
1426                 for child in self.walk_children():
1427                         child.hide()
1428                 self._window.show()
1429
1430         def hide(self):
1431                 for child in self.walk_children():
1432                         child.hide()
1433                 self._window.hide()
1434
1435         def close(self):
1436                 for child in self.walk_children():
1437                         child.window.destroyed.disconnect(self._on_child_close)
1438                         child.close()
1439                 self._window.close()
1440
1441         def set_fullscreen(self, isFullscreen):
1442                 if isFullscreen:
1443                         self._window.showFullScreen()
1444                 else:
1445                         self._window.showNormal()
1446
1447         def select_unit(self, unitName):
1448                 index = self._unitsModel.index_unit(unitName)
1449                 self._select_unit(index)
1450
1451                 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
1452                 self._unitsView.scrollTo(qindex)
1453
1454         def walk_children(self):
1455                 if self._favoritesWindow is not None:
1456                         yield self._favoritesWindow
1457
1458         def _select_unit(self, index):
1459                 unit = self._unitsModel.get_unit(index)
1460                 self._selectedUnitName.setText(unit.name)
1461                 self._selectedUnitValue.setText(str(unit.value))
1462                 self._selectedUnitSymbol.setText(unit.unit)
1463
1464                 self._selectedIndex = index
1465                 self._app.add_recent(self._categoryName, self._unitsModel.get_unit(index).name)
1466
1467         def _update_favorites(self, force = False):
1468                 if self._app.showFavoritesAction.isChecked():
1469                         unitNames = list(self._unitsModel.get_unit_names())
1470                         hiddenUnits = self._app.get_hidden_units(self._categoryName)
1471                         for i, unitName in enumerate(unitNames):
1472                                 if unitName in hiddenUnits:
1473                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), True)
1474                                 else:
1475                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
1476                 else:
1477                         if force:
1478                                 for i in xrange(len(self._unitsModel)):
1479                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
1480
1481         @misc_utils.log_exception(_moduleLogger)
1482         def _on_show_favorites(self, checked = True):
1483                 if checked:
1484                         unitNames = list(self._unitsModel.get_unit_names())
1485                         hiddenUnits = self._app.get_hidden_units(self._categoryName)
1486                         for i, unitName in enumerate(unitNames):
1487                                 if unitName in hiddenUnits:
1488                                         self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), True)
1489                 else:
1490                         for i in xrange(len(self._unitsModel)):
1491                                 self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
1492
1493         @misc_utils.log_exception(_moduleLogger)
1494         def _on_choose_favorites(self, obj = None):
1495                 assert self._favoritesWindow is None
1496                 import windows
1497                 self._favoritesWindow = windows.FavoritesWindow(
1498                         self._window,
1499                         self._app,
1500                         unit_data.get_units(self._categoryName),
1501                         self._app.get_hidden_units(self._categoryName)
1502                 )
1503                 self._favoritesWindow.window.destroyed.connect(self._on_close_favorites)
1504                 return self._favoritesWindow
1505
1506         @misc_utils.log_exception(_moduleLogger)
1507         def _on_close_favorites(self, obj = None):
1508                 self._favoritesWindow = None
1509                 self._update_favorites(force=True)
1510
1511         @misc_utils.log_exception(_moduleLogger)
1512         def _on_previous_unit(self, checked = True):
1513                 index = self._selectedIndex - 1
1514                 unitData = self._unitsModel.get_unit(index)
1515                 unitName = unitData.name
1516
1517                 if self._app.showFavoritesAction.isChecked():
1518                         hiddenUnits = self._app.get_hidden_units(self._categoryName)
1519                         while unitName in hiddenUnits:
1520                                 index -= 1
1521                                 unitData = self._unitsModel.get_unit(index)
1522                                 unitName = unitData.name
1523
1524                 self.select_unit(unitName)
1525
1526         @misc_utils.log_exception(_moduleLogger)
1527         def _on_next_unit(self, checked = True):
1528                 index = self._selectedIndex + 1
1529                 unitData = self._unitsModel.get_unit(index)
1530                 unitName = unitData.name
1531
1532                 if self._app.showFavoritesAction.isChecked():
1533                         hiddenUnits = self._app.get_hidden_units(self._categoryName)
1534                         while unitName in hiddenUnits:
1535                                 index += 1
1536                                 unitData = self._unitsModel.get_unit(index)
1537                                 unitName = unitData.name
1538
1539                 self.select_unit(unitName)
1540
1541         @misc_utils.log_exception(_moduleLogger)
1542         def _on_close_window(self, checked = True):
1543                 self.close()
1544
1545         @misc_utils.log_exception(_moduleLogger)
1546         def _on_sort_by_name(self, checked = False):
1547                 self._unitsModel.sort(UnitData.NAME_COLUMN, QtCore.Qt.DescendingOrder)
1548
1549         @misc_utils.log_exception(_moduleLogger)
1550         def _on_sort_by_value(self, checked = False):
1551                 self._unitsModel.sort(UnitData.VALUE_COLUMN_0)
1552
1553         @misc_utils.log_exception(_moduleLogger)
1554         def _on_sort_by_unit(self, checked = False):
1555                 self._unitsModel.sort(UnitData.UNIT_COLUMN, QtCore.Qt.DescendingOrder)
1556
1557         @misc_utils.log_exception(_moduleLogger)
1558         def _on_unit_clicked(self, index):
1559                 self._select_unit(index.row())
1560
1561         @misc_utils.log_exception(_moduleLogger)
1562         def _on_value_edited(self, *args):
1563                 if not self._updateDelayTimer.isActive():
1564                         self._updateDelayTimer.start()
1565
1566         @misc_utils.log_exception(_moduleLogger)
1567         def _on_value_edited_delayed(self, *args):
1568                 userInput = str(self._selectedUnitValue.text())
1569                 orderChanged = self._unitsModel.update_values(self._selectedIndex, userInput)
1570                 if orderChanged:
1571                         self._update_favorites()
1572
1573
1574 def run_gonvert():
1575         try:
1576                 os.makedirs(linux_utils.get_resource_path("config", constants.__app_name__))
1577         except OSError, e:
1578                 if e.errno != 17:
1579                         raise
1580         try:
1581                 os.makedirs(linux_utils.get_resource_path("cache", constants.__app_name__))
1582         except OSError, e:
1583                 if e.errno != 17:
1584                         raise
1585         try:
1586                 os.makedirs(linux_utils.get_resource_path("data", constants.__app_name__))
1587         except OSError, e:
1588                 if e.errno != 17:
1589                         raise
1590
1591         logPath = linux_utils.get_resource_path("cache", constants.__app_name__, "%s.log" % constants.__app_name__)
1592         logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
1593         logging.basicConfig(level=logging.DEBUG, format=logFormat)
1594         rotating = logging.handlers.RotatingFileHandler(logPath, maxBytes=512*1024, backupCount=1)
1595         rotating.setFormatter(logging.Formatter(logFormat))
1596         root = logging.getLogger()
1597         root.addHandler(rotating)
1598         _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
1599         _moduleLogger.info("OS: %s" % (os.uname()[0], ))
1600         _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
1601         _moduleLogger.info("Hostname: %s" % os.uname()[1])
1602
1603         app = QtGui.QApplication([])
1604         handle = Gonvert(app)
1605         if constants.PROFILE_STARTUP:
1606                 return 0
1607         else:
1608                 return app.exec_()
1609
1610
1611 if __name__ == "__main__":
1612         import sys
1613         val = run_gonvert()
1614         sys.exit(val)