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