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