5949df6ca8607aa99504d53a80c05ea4cc6e6e73
[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 from util import misc as misc_utils
17 import unit_data
18
19
20 _moduleLogger = logging.getLogger("gonvert_glade")
21
22
23 def change_menu_label(widgets, labelname, newtext):
24         item_label = widgets.get_widget(labelname).get_children()[0]
25         item_label.set_text(newtext)
26
27
28 def split_number(number):
29         try:
30                 fractional, integer = math.modf(number)
31         except TypeError:
32                 integerDisplay = number
33                 fractionalDisplay = ""
34         else:
35                 integerDisplay = str(integer)
36                 fractionalDisplay = str(fractional)
37                 if "e+" in integerDisplay:
38                         integerDisplay = number
39                         fractionalDisplay = ""
40                 elif "e-" in fractionalDisplay and 0.0 < integer:
41                         integerDisplay = number
42                         fractionalDisplay = ""
43                 elif "e-" in fractionalDisplay:
44                         integerDisplay = ""
45                         fractionalDisplay = number
46                 else:
47                         integerDisplay = integerDisplay.split(".", 1)[0] + "."
48                         fractionalDisplay = fractionalDisplay.rsplit(".", 1)[-1]
49
50         return integerDisplay, fractionalDisplay
51
52
53 class Gonvert(object):
54
55         # @todo Favorites
56         # @bug Fix the resurrecting window problem
57         # @todo Unit conversion window: focus always on input, arrows switch units
58
59         _DATA_PATHS = [
60                 os.path.dirname(__file__),
61                 os.path.join(os.path.dirname(__file__), "../data"),
62                 os.path.join(os.path.dirname(__file__), "../lib"),
63                 '/usr/share/gonvert',
64                 '/usr/lib/gonvert',
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._isFullscreen = False
80                 self._clipboard = QtGui.QApplication.clipboard()
81
82                 self._jumpWindow = None
83                 self._recentWindow = None
84                 self._catWindow = None
85
86                 self._jumpAction = QtGui.QAction(None)
87                 self._jumpAction.setText("Quick Jump")
88                 self._jumpAction.setStatusTip("Search for a unit and jump straight to it")
89                 self._jumpAction.setToolTip("Search for a unit and jump straight to it")
90                 self._jumpAction.setShortcut(QtGui.QKeySequence("CTRL+j"))
91                 self._jumpAction.triggered.connect(self._on_jump_start)
92
93                 self._recentAction = QtGui.QAction(None)
94                 self._recentAction.setText("Recent Units")
95                 self._recentAction.setStatusTip("View the recent units")
96                 self._recentAction.setToolTip("View the recent units")
97                 self._recentAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
98                 self._recentAction.triggered.connect(self._on_recent_start)
99
100                 self._fullscreenAction = QtGui.QAction(None)
101                 self._fullscreenAction.setText("Toggle Fullscreen")
102                 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
103                 self._fullscreenAction.triggered.connect(self._on_toggle_fullscreen)
104
105                 self._logAction = QtGui.QAction(None)
106                 self._logAction.setText("Log")
107                 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
108                 self._logAction.triggered.connect(self._on_log)
109
110                 self._quitAction = QtGui.QAction(None)
111                 self._quitAction.setText("Quit")
112                 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
113                 self._quitAction.triggered.connect(self._on_quit)
114
115                 self._app.lastWindowClosed.connect(self._on_app_quit)
116                 self.request_category()
117                 self.load_settings()
118
119         def request_category(self):
120                 if self._catWindow is not None:
121                         self._catWindow.close()
122                         self._catWindow = None
123                 self._catWindow = CategoryWindow(None, self)
124                 return self._catWindow
125
126         def search_units(self):
127                 if self._jumpWindow is not None:
128                         self._jumpWindow.close()
129                         self._jumpWindow = None
130                 self._jumpWindow = QuickJump(None, self)
131                 return self._jumpWindow
132
133         def show_recent(self):
134                 if self._recentWindow is not None:
135                         self._recentWindow.close()
136                         self._recentWindow = None
137                 self._recentWindow = Recent(None, self)
138                 return self._recentWindow
139
140         def add_recent(self, categoryName, unitName):
141                 catUnit = categoryName, unitName
142                 try:
143                         self._recent.remove(catUnit)
144                 except ValueError:
145                         pass # ignore if its not already in the recent history
146                 assert catUnit not in self._recent
147                 self._recent.append(catUnit)
148
149         def get_recent_unit(self, categoryName):
150                 for catName, unitName in reversed(self._recent):
151                         if catName == categoryName:
152                                 return unitName
153                 else:
154                         return ""
155
156         def get_recent(self):
157                 return reversed(self._recent)
158
159         def load_settings(self):
160                 try:
161                         with open(constants._user_settings_, "r") as settingsFile:
162                                 settings = simplejson.load(settingsFile)
163                 except IOError, e:
164                         settings = {}
165                 self._isFullscreen = settings.get("isFullScreen", self._isFullscreen)
166                 recent = settings.get("recent", self._recent)
167                 for category, unit in recent:
168                         self.add_recent(category, unit)
169
170                 for window in self._walk_children():
171                         window.set_fullscreen(self._isFullscreen)
172                 if self._recent:
173                         self._catWindow.select_category(self._recent[-1][0])
174
175         def save_settings(self):
176                 settings = {
177                         "isFullScreen": self._isFullscreen,
178                         "recent": self._recent,
179                 }
180                 with open(constants._user_settings_, "w") as settingsFile:
181                         simplejson.dump(settings, settingsFile)
182
183         @property
184         def appIconPath(self):
185                 return self._appIconPath
186
187         @property
188         def jumpAction(self):
189                 return self._jumpAction
190
191         @property
192         def recentAction(self):
193                 return self._recentAction
194
195         @property
196         def fullscreenAction(self):
197                 return self._fullscreenAction
198
199         @property
200         def logAction(self):
201                 return self._logAction
202
203         @property
204         def quitAction(self):
205                 return self._quitAction
206
207         def _walk_children(self):
208                 if self._catWindow is not None:
209                         yield self._catWindow
210                 if self._jumpWindow is not None:
211                         yield self._jumpWindow
212                 if self._recentWindow is not None:
213                         yield self._recentWindow
214
215         @misc_utils.log_exception(_moduleLogger)
216         def _on_app_quit(self, checked = False):
217                 self.save_settings()
218
219         @misc_utils.log_exception(_moduleLogger)
220         def _on_toggle_fullscreen(self, checked = False):
221                 self._isFullscreen = not self._isFullscreen
222                 for window in self._walk_children():
223                         window.set_fullscreen(self._isFullscreen)
224
225         @misc_utils.log_exception(_moduleLogger)
226         def _on_jump_start(self, checked = False):
227                 self.search_units()
228
229         @misc_utils.log_exception(_moduleLogger)
230         def _on_recent_start(self, checked = False):
231                 self.show_recent()
232
233         @misc_utils.log_exception(_moduleLogger)
234         def _on_log(self, checked = False):
235                 with open(constants._user_logpath_, "r") as f:
236                         logLines = f.xreadlines()
237                         log = "".join(logLines)
238                         self._clipboard.setText(log)
239
240         @misc_utils.log_exception(_moduleLogger)
241         def _on_quit(self, checked = False):
242                 for window in self._walk_children():
243                         window.close()
244
245
246 class CategoryWindow(object):
247
248         def __init__(self, parent, app):
249                 self._app = app
250                 self._unitWindow = None
251
252                 self._categories = QtGui.QTreeWidget()
253                 self._categories.setHeaderLabels(["Categories"])
254                 self._categories.itemClicked.connect(self._on_category_clicked)
255                 self._categories.setHeaderHidden(True)
256                 self._categories.setAlternatingRowColors(True)
257                 for catName in unit_data.UNIT_CATEGORIES:
258                         twi = QtGui.QTreeWidgetItem(self._categories)
259                         twi.setText(0, catName)
260
261                 self._layout = QtGui.QVBoxLayout()
262                 self._layout.addWidget(self._categories)
263
264                 centralWidget = QtGui.QWidget()
265                 centralWidget.setLayout(self._layout)
266
267                 self._window = QtGui.QMainWindow(parent)
268                 if parent is not None:
269                         self._window.setWindowModality(QtCore.Qt.WindowModal)
270                 self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
271                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
272                 self._window.setCentralWidget(centralWidget)
273
274                 self._closeWindowAction = QtGui.QAction(None)
275                 self._closeWindowAction.setText("Window")
276                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
277                 self._closeWindowAction.triggered.connect(self._on_close_window)
278
279                 fileMenu = self._window.menuBar().addMenu("&File")
280                 fileMenu.addAction(self._closeWindowAction)
281                 fileMenu.addAction(self._app.quitAction)
282
283                 viewMenu = self._window.menuBar().addMenu("&View")
284                 viewMenu.addAction(self._app.fullscreenAction)
285                 viewMenu.addSeparator()
286                 viewMenu.addAction(self._app.jumpAction)
287                 viewMenu.addAction(self._app.recentAction)
288
289                 self._window.addAction(self._app.logAction)
290
291                 self._window.show()
292
293         def walk_children(self):
294                 if self._unitWindow is not None:
295                         yield self._unitWindow
296
297         def close(self):
298                 for child in self.walk_children():
299                         child.close()
300                 self._window.close()
301
302         def select_category(self, categoryName):
303                 for child in self.walk_children():
304                         child.close()
305                 self._unitWindow = UnitWindow(self._window, categoryName, self._app)
306                 return self._unitWindow
307
308         def set_fullscreen(self, isFullscreen):
309                 if isFullscreen:
310                         self._window.showFullScreen()
311                 else:
312                         self._window.showNormal()
313                 for child in self.walk_children():
314                         child.set_fullscreen(isFullscreen)
315
316         @misc_utils.log_exception(_moduleLogger)
317         def _on_close_window(self, checked = True):
318                 self.close()
319
320         @misc_utils.log_exception(_moduleLogger)
321         def _on_category_clicked(self, item, columnIndex):
322                 categoryName = unicode(item.text(0))
323                 self.select_category(categoryName)
324
325
326 class QuickJump(object):
327
328         MINIMAL_ENTRY = 3
329
330         def __init__(self, parent, app):
331                 self._app = app
332
333                 self._searchLabel = QtGui.QLabel("Search:")
334                 self._searchEntry = QtGui.QLineEdit("")
335                 self._searchEntry.textEdited.connect(self._on_search_edited)
336
337                 self._entryLayout = QtGui.QHBoxLayout()
338                 self._entryLayout.addWidget(self._searchLabel)
339                 self._entryLayout.addWidget(self._searchEntry)
340
341                 self._resultsBox = QtGui.QTreeWidget()
342                 self._resultsBox.setHeaderLabels(["Categories", "Units"])
343                 self._resultsBox.setHeaderHidden(True)
344                 self._resultsBox.setAlternatingRowColors(True)
345                 self._resultsBox.itemClicked.connect(self._on_result_clicked)
346
347                 self._layout = QtGui.QVBoxLayout()
348                 self._layout.addLayout(self._entryLayout)
349                 self._layout.addWidget(self._resultsBox)
350
351                 centralWidget = QtGui.QWidget()
352                 centralWidget.setLayout(self._layout)
353
354                 self._window = QtGui.QMainWindow(parent)
355                 if parent is not None:
356                         self._window.setWindowModality(QtCore.Qt.WindowModal)
357                 self._window.setWindowTitle("%s - Quick Jump" % constants.__pretty_app_name__)
358                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
359                 self._window.setCentralWidget(centralWidget)
360
361                 self._closeWindowAction = QtGui.QAction(None)
362                 self._closeWindowAction.setText("Window")
363                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
364                 self._closeWindowAction.triggered.connect(self._on_close_window)
365
366                 fileMenu = self._window.menuBar().addMenu("&File")
367                 fileMenu.addAction(self._closeWindowAction)
368                 fileMenu.addAction(self._app.quitAction)
369
370                 viewMenu = self._window.menuBar().addMenu("&View")
371                 viewMenu.addAction(self._app.fullscreenAction)
372
373                 self._window.addAction(self._app.logAction)
374
375                 self._window.show()
376
377         def close(self):
378                 self._window.close()
379
380         def set_fullscreen(self, isFullscreen):
381                 if isFullscreen:
382                         self._window.showFullScreen()
383                 else:
384                         self._window.showNormal()
385
386         @misc_utils.log_exception(_moduleLogger)
387         def _on_close_window(self, checked = True):
388                 self.close()
389
390         @misc_utils.log_exception(_moduleLogger)
391         def _on_result_clicked(self, item, columnIndex):
392                 categoryName = unicode(item.text(0))
393                 unitName = unicode(item.text(1))
394                 catWindow = self._app.request_category()
395                 unitsWindow = catWindow.select_category(categoryName)
396                 unitsWindow.select_unit(unitName)
397                 self.close()
398
399         @misc_utils.log_exception(_moduleLogger)
400         def _on_search_edited(self, *args):
401                 userInput = self._searchEntry.text()
402                 if len(userInput) <  self.MINIMAL_ENTRY:
403                         return
404
405                 self._resultsBox.clear()
406                 lowerInput = str(userInput).lower()
407                 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
408                         units = unit_data.get_units(category)
409                         for unitIndex, unit in enumerate(units):
410                                 loweredUnit = unit.lower()
411                                 if lowerInput in loweredUnit:
412                                         twi = QtGui.QTreeWidgetItem(self._resultsBox)
413                                         twi.setText(0, category)
414                                         twi.setText(1, unit)
415
416
417 class Recent(object):
418
419         def __init__(self, parent, app):
420                 self._app = app
421
422                 self._resultsBox = QtGui.QTreeWidget()
423                 self._resultsBox.setHeaderLabels(["Categories", "Units"])
424                 self._resultsBox.setHeaderHidden(True)
425                 self._resultsBox.setAlternatingRowColors(True)
426                 self._resultsBox.itemClicked.connect(self._on_result_clicked)
427
428                 self._layout = QtGui.QVBoxLayout()
429                 self._layout.addWidget(self._resultsBox)
430
431                 centralWidget = QtGui.QWidget()
432                 centralWidget.setLayout(self._layout)
433
434                 self._window = QtGui.QMainWindow(parent)
435                 if parent is not None:
436                         self._window.setWindowModality(QtCore.Qt.WindowModal)
437                 self._window.setWindowTitle("%s - Recent" % constants.__pretty_app_name__)
438                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
439                 self._window.setCentralWidget(centralWidget)
440
441                 for cat, unit in self._app.get_recent():
442                         twi = QtGui.QTreeWidgetItem(self._resultsBox)
443                         twi.setText(0, cat)
444                         twi.setText(1, unit)
445
446                 self._closeWindowAction = QtGui.QAction(None)
447                 self._closeWindowAction.setText("Window")
448                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
449                 self._closeWindowAction.triggered.connect(self._on_close_window)
450
451                 fileMenu = self._window.menuBar().addMenu("&File")
452                 fileMenu.addAction(self._closeWindowAction)
453                 fileMenu.addAction(self._app.quitAction)
454
455                 viewMenu = self._window.menuBar().addMenu("&View")
456                 viewMenu.addAction(self._app.fullscreenAction)
457
458                 self._window.addAction(self._app.logAction)
459
460                 self._window.show()
461
462         def close(self):
463                 self._window.close()
464
465         def set_fullscreen(self, isFullscreen):
466                 if isFullscreen:
467                         self._window.showFullScreen()
468                 else:
469                         self._window.showNormal()
470
471         @misc_utils.log_exception(_moduleLogger)
472         def _on_close_window(self, checked = True):
473                 self.close()
474
475         @misc_utils.log_exception(_moduleLogger)
476         def _on_result_clicked(self, item, columnIndex):
477                 categoryName = unicode(item.text(0))
478                 unitName = unicode(item.text(1))
479                 catWindow = self._app.request_category()
480                 unitsWindow = catWindow.select_category(categoryName)
481                 unitsWindow.select_unit(unitName)
482                 self.close()
483
484
485 class UnitData(object):
486
487         HEADERS = ["Name", "Value", "", "Unit"]
488         ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
489
490         def __init__(self, name, unit, description, conversion):
491                 self._name = name
492                 self._unit = unit
493                 self._description = description
494                 self._conversion = conversion
495
496                 self._value = 0.0
497                 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
498
499         @property
500         def name(self):
501                 return self._name
502
503         @property
504         def value(self):
505                 return self._value
506
507         def update_value(self, newValue):
508                 self._value = newValue
509                 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
510
511         @property
512         def unit(self):
513                 return self._unit
514
515         @property
516         def conversion(self):
517                 return self._conversion
518
519         def data(self, column):
520                 try:
521                         return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
522                 except IndexError:
523                         return None
524
525
526 class UnitModel(QtCore.QAbstractItemModel):
527
528         def __init__(self, categoryName, parent=None):
529                 super(UnitModel, self).__init__(parent)
530                 self._categoryName = categoryName
531                 self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
532
533                 self._children = []
534                 for key in unit_data.get_units(self._categoryName):
535                         conversion, unit, description = self._unitData[key]
536                         self._children.append(UnitData(key, unit, description, conversion))
537                 self._sortSettings = None
538
539         @misc_utils.log_exception(_moduleLogger)
540         def columnCount(self, parent):
541                 if parent.isValid():
542                         return 0
543                 else:
544                         return len(UnitData.HEADERS)
545
546         @misc_utils.log_exception(_moduleLogger)
547         def data(self, index, role):
548                 if not index.isValid():
549                         return None
550                 elif role == QtCore.Qt.TextAlignmentRole:
551                         return UnitData.ALIGNMENT[index.column()]
552                 elif role != QtCore.Qt.DisplayRole:
553                         return None
554
555                 item = index.internalPointer()
556                 if isinstance(item, UnitData):
557                         return item.data(index.column())
558                 elif item is UnitData.HEADERS:
559                         return item[index.column()]
560
561         @misc_utils.log_exception(_moduleLogger)
562         def sort(self, column, order = QtCore.Qt.AscendingOrder):
563                 self._sortSettings = column, order
564                 isReverse = order == QtCore.Qt.AscendingOrder
565                 if column == 0:
566                         key_func = lambda item: item.name
567                 elif column in [1, 2]:
568                         key_func = lambda item: item.value
569                 elif column == 3:
570                         key_func = lambda item: item.unit
571                 self._children.sort(key=key_func, reverse = isReverse)
572
573                 self._all_changed()
574
575         @misc_utils.log_exception(_moduleLogger)
576         def flags(self, index):
577                 if not index.isValid():
578                         return QtCore.Qt.NoItemFlags
579
580                 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
581
582         @misc_utils.log_exception(_moduleLogger)
583         def headerData(self, section, orientation, role):
584                 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
585                         return UnitData.HEADERS[section]
586
587                 return None
588
589         @misc_utils.log_exception(_moduleLogger)
590         def index(self, row, column, parent):
591                 if not self.hasIndex(row, column, parent):
592                         return QtCore.QModelIndex()
593
594                 if parent.isValid():
595                         return QtCore.QModelIndex()
596
597                 parentItem = UnitData.HEADERS
598                 childItem = self._children[row]
599                 if childItem:
600                         return self.createIndex(row, column, childItem)
601                 else:
602                         return QtCore.QModelIndex()
603
604         @misc_utils.log_exception(_moduleLogger)
605         def parent(self, index):
606                 if not index.isValid():
607                         return QtCore.QModelIndex()
608
609                 childItem = index.internalPointer()
610                 if isinstance(childItem, UnitData):
611                         return QtCore.QModelIndex()
612                 elif childItem is UnitData.HEADERS:
613                         return None
614
615         @misc_utils.log_exception(_moduleLogger)
616         def rowCount(self, parent):
617                 if 0 < parent.column():
618                         return 0
619
620                 if not parent.isValid():
621                         return len(self._children)
622                 else:
623                         return len(self._children)
624
625         def get_unit(self, index):
626                 return self._children[index]
627
628         def index_unit(self, unitName):
629                 for i, child in enumerate(self._children):
630                         if child.name == unitName:
631                                 return i
632                 else:
633                         raise RuntimeError("Unit not found")
634
635         def update_values(self, fromIndex, userInput):
636                 value = self._sanitize_value(userInput)
637                 func, arg = self._children[fromIndex].conversion
638                 base = func.to_base(value, arg)
639                 for i, child in enumerate(self._children):
640                         if i == fromIndex:
641                                 continue
642                         func, arg = child.conversion
643                         newValue = func.from_base(base, arg)
644                         child.update_value(newValue)
645
646                 if self._sortSettings is not None:
647                         self.sort(*self._sortSettings)
648                 self._all_changed()
649
650         def _all_changed(self):
651                 topLeft = self.createIndex(0, 0, self._children[0])
652                 bottomRight = self.createIndex(len(self._children)-1, len(UnitData.HEADERS)-1, self._children[-1])
653                 self.dataChanged.emit(topLeft, bottomRight)
654
655         def _sanitize_value(self, userEntry):
656                 if self._categoryName == "Computer Numbers":
657                         if userEntry == '':
658                                 value = '0'
659                         else:
660                                 value = userEntry
661                 else:
662                         if userEntry == '':
663                                 value = 0.0
664                         else:
665                                 value = float(userEntry)
666                 return value
667
668
669 class UnitWindow(object):
670
671         def __init__(self, parent, category, app):
672                 self._app = app
673                 self._categoryName = category
674                 self._selectedIndex = 0
675
676                 self._selectedUnitName = QtGui.QLabel()
677                 self._selectedUnitValue = QtGui.QLineEdit()
678                 self._selectedUnitValue.textEdited.connect(self._on_value_edited)
679                 self._selectedUnitSymbol = QtGui.QLabel()
680
681                 self._selectedUnitLayout = QtGui.QHBoxLayout()
682                 self._selectedUnitLayout.addWidget(self._selectedUnitName)
683                 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
684                 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
685
686                 self._unitsModel = UnitModel(self._categoryName)
687                 self._unitsView = QtGui.QTreeView()
688                 self._unitsView.setModel(self._unitsModel)
689                 self._unitsView.clicked.connect(self._on_unit_clicked)
690                 self._unitsView.setUniformRowHeights(True)
691                 self._unitsView.header().setSortIndicatorShown(True)
692                 self._unitsView.header().setClickable(True)
693                 self._unitsView.setSortingEnabled(True)
694                 self._unitsView.setAlternatingRowColors(True)
695                 if True:
696                         self._unitsView.setHeaderHidden(True)
697
698                 self._layout = QtGui.QVBoxLayout()
699                 self._layout.addLayout(self._selectedUnitLayout)
700                 self._layout.addWidget(self._unitsView)
701
702                 centralWidget = QtGui.QWidget()
703                 centralWidget.setLayout(self._layout)
704
705                 self._window = QtGui.QMainWindow(parent)
706                 if parent is not None:
707                         self._window.setWindowModality(QtCore.Qt.WindowModal)
708                 self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
709                 self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
710                 self._window.setCentralWidget(centralWidget)
711
712                 defaultUnitName = self._app.get_recent_unit(self._categoryName)
713                 if defaultUnitName:
714                         self.select_unit(defaultUnitName)
715                 else:
716                         self._select_unit(0)
717                 self._unitsModel.sort(1)
718
719                 self._sortActionGroup = QtGui.QActionGroup(None)
720                 self._sortByNameAction = QtGui.QAction(self._sortActionGroup)
721                 self._sortByNameAction.setText("Sort By Name")
722                 self._sortByNameAction.setStatusTip("Sort the units by name")
723                 self._sortByNameAction.setToolTip("Sort the units by name")
724                 self._sortByValueAction = QtGui.QAction(self._sortActionGroup)
725                 self._sortByValueAction.setText("Sort By Value")
726                 self._sortByValueAction.setStatusTip("Sort the units by value")
727                 self._sortByValueAction.setToolTip("Sort the units by value")
728                 self._sortByUnitAction = QtGui.QAction(self._sortActionGroup)
729                 self._sortByUnitAction.setText("Sort By Unit")
730                 self._sortByUnitAction.setStatusTip("Sort the units by unit")
731                 self._sortByUnitAction.setToolTip("Sort the units by unit")
732
733                 self._sortByValueAction.setChecked(True)
734
735                 self._closeWindowAction = QtGui.QAction(None)
736                 self._closeWindowAction.setText("Close Window")
737                 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
738                 self._closeWindowAction.triggered.connect(self._on_close_window)
739
740                 fileMenu = self._window.menuBar().addMenu("&File")
741                 fileMenu.addAction(self._closeWindowAction)
742                 fileMenu.addAction(self._app.quitAction)
743
744                 viewMenu = self._window.menuBar().addMenu("&View")
745                 viewMenu.addAction(self._app.fullscreenAction)
746                 viewMenu.addSeparator()
747                 viewMenu.addAction(self._app.jumpAction)
748                 viewMenu.addAction(self._app.recentAction)
749                 viewMenu.addSeparator()
750                 viewMenu.addAction(self._sortByNameAction)
751                 viewMenu.addAction(self._sortByValueAction)
752                 viewMenu.addAction(self._sortByUnitAction)
753
754                 self._sortByNameAction.triggered.connect(self._on_sort_by_name)
755                 self._sortByValueAction.triggered.connect(self._on_sort_by_value)
756                 self._sortByUnitAction.triggered.connect(self._on_sort_by_unit)
757
758                 self._window.addAction(self._app.logAction)
759
760                 self._window.show()
761
762         def close(self):
763                 self._window.close()
764
765         def set_fullscreen(self, isFullscreen):
766                 if isFullscreen:
767                         self._window.showFullScreen()
768                 else:
769                         self._window.showNormal()
770
771         def select_unit(self, unitName):
772                 index = self._unitsModel.index_unit(unitName)
773                 self._select_unit(index)
774
775         @misc_utils.log_exception(_moduleLogger)
776         def _on_close_window(self, checked = True):
777                 self.close()
778
779         @misc_utils.log_exception(_moduleLogger)
780         def _on_sort_by_name(self, checked = False):
781                 self._unitsModel.sort(0, QtCore.Qt.DescendingOrder)
782
783         @misc_utils.log_exception(_moduleLogger)
784         def _on_sort_by_value(self, checked = False):
785                 self._unitsModel.sort(1)
786
787         @misc_utils.log_exception(_moduleLogger)
788         def _on_sort_by_unit(self, checked = False):
789                 self._unitsModel.sort(3, QtCore.Qt.DescendingOrder)
790
791         @misc_utils.log_exception(_moduleLogger)
792         def _on_unit_clicked(self, index):
793                 self._select_unit(index.row())
794
795         @misc_utils.log_exception(_moduleLogger)
796         def _on_value_edited(self, *args):
797                 userInput = self._selectedUnitValue.text()
798                 self._unitsModel.update_values(self._selectedIndex, str(userInput))
799
800         def _select_unit(self, index):
801                 unit = self._unitsModel.get_unit(index)
802                 self._selectedUnitName.setText(unit.name)
803                 self._selectedUnitValue.setText(str(unit.value))
804                 self._selectedUnitSymbol.setText(unit.unit)
805
806                 self._selectedIndex = index
807                 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
808                 self._unitsView.scrollTo(qindex)
809                 self._app.add_recent(self._categoryName, self._unitsModel.get_unit(index).name)
810
811
812 def run_gonvert():
813         app = QtGui.QApplication([])
814         handle = Gonvert(app)
815         return app.exec_()
816
817
818 if __name__ == "__main__":
819         logging.basicConfig(level = logging.DEBUG)
820         try:
821                 os.makedirs(constants._data_path_)
822         except OSError, e:
823                 if e.errno != 17:
824                         raise
825
826         val = run_gonvert()
827         sys.exit(val)