Some cleanup
[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 Remember last selection
55         # @todo Recent
56         # @todo Favorites
57         # @todo Fullscreen support (showFullscreen, showNormal)
58         # @todo Close Window / Quit keyboard shortcuts
59         # @todo Ctrl+l support
60         # @todo Unit conversion window: focus always on input, arrows switch units
61
62         _DATA_PATHS = [
63                 os.path.dirname(__file__),
64                 os.path.join(os.path.dirname(__file__), "../data"),
65                 os.path.join(os.path.dirname(__file__), "../lib"),
66                 '/usr/share/gonvert',
67                 '/usr/lib/gonvert',
68         ]
69
70         def __init__(self):
71                 self._dataPath = ""
72                 for dataPath in self._DATA_PATHS:
73                         appIconPath = os.path.join(dataPath, "pixmaps", "gonvert.png")
74                         if os.path.isfile(appIconPath):
75                                 self._dataPath = dataPath
76                                 break
77                 else:
78                         raise RuntimeError("UI Descriptor not found!")
79                 self._appIconPath = appIconPath
80
81                 self._jumpWindow = None
82                 self._catWindow = None
83
84                 self._jumpAction = QtGui.QAction(None)
85                 self._jumpAction.setText("Quick Jump")
86                 self._jumpAction.setStatusTip("Search for a unit and jump straight to it")
87                 self._jumpAction.setToolTip("Search for a unit and jump straight to it")
88                 self._jumpAction.setShortcut(QtGui.QKeySequence("CTRL+j"))
89                 self._jumpAction.triggered.connect(self._on_jump_start)
90
91                 self.request_category()
92
93         def request_category(self):
94                 if self._catWindow is not None:
95                         self._catWindow.close()
96                         self._catWindow = None
97                 self._catWindow = CategoryWindow(None, self)
98                 return self._catWindow
99
100         def search_units(self):
101                 if self._jumpWindow is not None:
102                         self._jumpWindow.close()
103                         self._jumpWindow = None
104                 self._jumpWindow = QuickJump(None, self)
105                 return self._jumpWindow
106
107         @property
108         def appIconPath(self):
109                 return self._appIconPath
110
111         @property
112         def jumpAction(self):
113                 return self._jumpAction
114
115         @misc_utils.log_exception(_moduleLogger)
116         def _on_jump_start(self, checked = False):
117                 self.search_units()
118
119
120 class CategoryWindow(object):
121
122         def __init__(self, parent, app):
123                 self._app = app
124                 self._unitWindow = None
125
126                 self._categories = QtGui.QTreeWidget()
127                 self._categories.setHeaderLabels(["Categories"])
128                 self._categories.itemClicked.connect(self._on_category_clicked)
129                 self._categories.setHeaderHidden(True)
130                 self._categories.setAlternatingRowColors(True)
131                 for catName in unit_data.UNIT_CATEGORIES:
132                         twi = QtGui.QTreeWidgetItem(self._categories)
133                         twi.setText(0, catName)
134
135                 self._layout = QtGui.QVBoxLayout()
136                 self._layout.addWidget(self._categories)
137
138                 centralWidget = QtGui.QWidget()
139                 centralWidget.setLayout(self._layout)
140
141                 self._window = QtGui.QMainWindow(parent)
142                 if parent is not None:
143                         self._window.setWindowModality(QtCore.Qt.WindowModal)
144                 self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
145                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
146                 self._window.setCentralWidget(centralWidget)
147
148                 viewMenu = self._window.menuBar().addMenu("&View")
149                 viewMenu.addAction(self._app.jumpAction)
150
151                 self._window.show()
152
153         def close(self):
154                 if self._unitWindow is not None:
155                         self._unitWindow.close()
156                         self._unitWindow = None
157                 self._window.close()
158
159         def selectCategory(self, categoryName):
160                 if self._unitWindow is not None:
161                         self._unitWindow.close()
162                         self._unitWindow = None
163                 self._unitWindow = UnitWindow(self._window, categoryName, self._app)
164                 return self._unitWindow
165
166         @misc_utils.log_exception(_moduleLogger)
167         def _on_category_clicked(self, item, columnIndex):
168                 categoryName = unicode(item.text(0))
169                 self.selectCategory(categoryName)
170
171
172 class QuickJump(object):
173
174         MINIMAL_ENTRY = 3
175
176         def __init__(self, parent, app):
177                 self._app = app
178
179                 self._searchLabel = QtGui.QLabel("Search:")
180                 self._searchEntry = QtGui.QLineEdit("")
181                 self._searchEntry.textEdited.connect(self._on_search_edited)
182
183                 self._entryLayout = QtGui.QHBoxLayout()
184                 self._entryLayout.addWidget(self._searchLabel)
185                 self._entryLayout.addWidget(self._searchEntry)
186
187                 self._resultsBox = QtGui.QTreeWidget()
188                 self._resultsBox.setHeaderLabels(["Categories", "Units"])
189                 self._resultsBox.setHeaderHidden(True)
190                 self._resultsBox.setAlternatingRowColors(True)
191                 self._resultsBox.itemClicked.connect(self._on_result_clicked)
192
193                 self._layout = QtGui.QVBoxLayout()
194                 self._layout.addLayout(self._entryLayout)
195                 self._layout.addWidget(self._resultsBox)
196
197                 centralWidget = QtGui.QWidget()
198                 centralWidget.setLayout(self._layout)
199
200                 self._window = QtGui.QMainWindow(parent)
201                 if parent is not None:
202                         self._window.setWindowModality(QtCore.Qt.WindowModal)
203                 self._window.setWindowTitle("%s - Quick Jump" % constants.__pretty_app_name__)
204                 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
205                 self._window.setCentralWidget(centralWidget)
206
207                 self._window.show()
208
209         def close(self):
210                 self._window.close()
211
212         @misc_utils.log_exception(_moduleLogger)
213         def _on_result_clicked(self, item, columnIndex):
214                 categoryName = unicode(item.text(0))
215                 unitName = unicode(item.text(1))
216                 catWindow = self._app.request_category()
217                 unitsWindow = catWindow.selectCategory(categoryName)
218                 unitsWindow.select_unit(unitName)
219
220         @misc_utils.log_exception(_moduleLogger)
221         def _on_search_edited(self, *args):
222                 userInput = self._searchEntry.text()
223                 if len(userInput) <  self.MINIMAL_ENTRY:
224                         return
225
226                 lowerInput = str(userInput).lower()
227                 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
228                         units = unit_data.get_units(category)
229                         for unitIndex, unit in enumerate(units):
230                                 loweredUnit = unit.lower()
231                                 if lowerInput in loweredUnit:
232                                         twi = QtGui.QTreeWidgetItem(self._resultsBox)
233                                         twi.setText(0, category)
234                                         twi.setText(1, unit)
235
236
237 class UnitData(object):
238
239         HEADERS = ["Name", "Value", "", "Unit"]
240         ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
241
242         def __init__(self, name, unit, description, conversion):
243                 self._name = name
244                 self._unit = unit
245                 self._description = description
246                 self._conversion = conversion
247
248                 self._value = 0.0
249                 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
250
251         @property
252         def name(self):
253                 return self._name
254
255         @property
256         def value(self):
257                 return self._value
258
259         def update_value(self, newValue):
260                 self._value = newValue
261                 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
262
263         @property
264         def unit(self):
265                 return self._unit
266
267         @property
268         def conversion(self):
269                 return self._conversion
270
271         def data(self, column):
272                 try:
273                         return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
274                 except IndexError:
275                         return None
276
277
278 class UnitModel(QtCore.QAbstractItemModel):
279
280         def __init__(self, categoryName, parent=None):
281                 super(UnitModel, self).__init__(parent)
282                 self._categoryName = categoryName
283                 self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
284
285                 self._children = []
286                 for key in unit_data.get_units(self._categoryName):
287                         conversion, unit, description = self._unitData[key]
288                         self._children.append(UnitData(key, unit, description, conversion))
289
290         @misc_utils.log_exception(_moduleLogger)
291         def columnCount(self, parent):
292                 if parent.isValid():
293                         return 0
294                 else:
295                         return len(UnitData.HEADERS)
296
297         @misc_utils.log_exception(_moduleLogger)
298         def data(self, index, role):
299                 if not index.isValid():
300                         return None
301                 elif role == QtCore.Qt.TextAlignmentRole:
302                         return UnitData.ALIGNMENT[index.column()]
303                 elif role != QtCore.Qt.DisplayRole:
304                         return None
305
306                 item = index.internalPointer()
307                 if isinstance(item, UnitData):
308                         return item.data(index.column())
309                 elif item is UnitData.HEADERS:
310                         return item[index.column()]
311
312         @misc_utils.log_exception(_moduleLogger)
313         def sort(self, column, order = QtCore.Qt.AscendingOrder):
314                 isReverse = order == QtCore.Qt.AscendingOrder
315                 if column == 0:
316                         key_func = lambda item: item.name
317                 elif column in [1, 2]:
318                         key_func = lambda item: item.value
319                 elif column == 3:
320                         key_func = lambda item: item.unit
321                 self._children.sort(key=key_func, reverse = isReverse)
322
323                 self._all_changed()
324
325         @misc_utils.log_exception(_moduleLogger)
326         def flags(self, index):
327                 if not index.isValid():
328                         return QtCore.Qt.NoItemFlags
329
330                 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
331
332         @misc_utils.log_exception(_moduleLogger)
333         def headerData(self, section, orientation, role):
334                 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
335                         return UnitData.HEADERS[section]
336
337                 return None
338
339         @misc_utils.log_exception(_moduleLogger)
340         def index(self, row, column, parent):
341                 if not self.hasIndex(row, column, parent):
342                         return QtCore.QModelIndex()
343
344                 if parent.isValid():
345                         return QtCore.QModelIndex()
346
347                 parentItem = UnitData.HEADERS
348                 childItem = self._children[row]
349                 if childItem:
350                         return self.createIndex(row, column, childItem)
351                 else:
352                         return QtCore.QModelIndex()
353
354         @misc_utils.log_exception(_moduleLogger)
355         def parent(self, index):
356                 if not index.isValid():
357                         return QtCore.QModelIndex()
358
359                 childItem = index.internalPointer()
360                 if isinstance(childItem, UnitData):
361                         return QtCore.QModelIndex()
362                 elif childItem is UnitData.HEADERS:
363                         return None
364
365         @misc_utils.log_exception(_moduleLogger)
366         def rowCount(self, parent):
367                 if 0 < parent.column():
368                         return 0
369
370                 if not parent.isValid():
371                         return len(self._children)
372                 else:
373                         return len(self._children)
374
375         def get_unit(self, index):
376                 return self._children[index]
377
378         def index_unit(self, unitName):
379                 for i, child in enumerate(self._children):
380                         if child.name == unitName:
381                                 return i
382                 else:
383                         raise RuntimeError("Unit not found")
384
385         def update_values(self, fromIndex, userInput):
386                 value = self._sanitize_value(userInput)
387                 func, arg = self._children[fromIndex].conversion
388                 base = func.to_base(value, arg)
389                 for i, child in enumerate(self._children):
390                         if i == fromIndex:
391                                 continue
392                         func, arg = child.conversion
393                         newValue = func.from_base(base, arg)
394                         child.update_value(newValue)
395
396                 self._all_changed()
397
398         def _all_changed(self):
399                 topLeft = self.createIndex(0, 1, self._children[0])
400                 bottomRight = self.createIndex(len(self._children)-1, 2, self._children[-1])
401                 self.dataChanged.emit(topLeft, bottomRight)
402
403         def _sanitize_value(self, userEntry):
404                 if self._categoryName == "Computer Numbers":
405                         if userEntry == '':
406                                 value = '0'
407                         else:
408                                 value = userEntry
409                 else:
410                         if userEntry == '':
411                                 value = 0.0
412                         else:
413                                 value = float(userEntry)
414                 return value
415
416
417 class UnitWindow(object):
418
419         def __init__(self, parent, category, app):
420                 self._app = app
421                 self._categoryName = category
422                 self._selectedIndex = 0
423
424                 self._selectedUnitName = QtGui.QLabel()
425                 self._selectedUnitValue = QtGui.QLineEdit()
426                 self._selectedUnitValue.textEdited.connect(self._on_value_edited)
427                 self._selectedUnitSymbol = QtGui.QLabel()
428
429                 self._selectedUnitLayout = QtGui.QHBoxLayout()
430                 self._selectedUnitLayout.addWidget(self._selectedUnitName)
431                 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
432                 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
433
434                 self._unitsModel = UnitModel(self._categoryName)
435                 self._unitsView = QtGui.QTreeView()
436                 self._unitsView.setModel(self._unitsModel)
437                 self._unitsView.clicked.connect(self._on_unit_clicked)
438                 self._unitsView.setUniformRowHeights(True)
439                 self._unitsView.header().setSortIndicatorShown(True)
440                 self._unitsView.header().setClickable(True)
441                 self._unitsView.setSortingEnabled(True)
442                 self._unitsView.setAlternatingRowColors(True)
443                 if True:
444                         self._unitsView.setHeaderHidden(True)
445
446                 self._layout = QtGui.QVBoxLayout()
447                 self._layout.addLayout(self._selectedUnitLayout)
448                 self._layout.addWidget(self._unitsView)
449
450                 centralWidget = QtGui.QWidget()
451                 centralWidget.setLayout(self._layout)
452
453                 self._window = QtGui.QMainWindow(parent)
454                 if parent is not None:
455                         self._window.setWindowModality(QtCore.Qt.WindowModal)
456                 self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
457                 self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
458                 self._window.setCentralWidget(centralWidget)
459
460                 self._select_unit(0)
461                 self._unitsModel.sort(1)
462
463                 self._sortActionGroup = QtGui.QActionGroup(None)
464                 self._sortByNameAction = QtGui.QAction(self._sortActionGroup)
465                 self._sortByNameAction.setText("Sort By Name")
466                 self._sortByNameAction.setStatusTip("Sort the units by name")
467                 self._sortByNameAction.setToolTip("Sort the units by name")
468                 self._sortByValueAction = QtGui.QAction(self._sortActionGroup)
469                 self._sortByValueAction.setText("Sort By Value")
470                 self._sortByValueAction.setStatusTip("Sort the units by value")
471                 self._sortByValueAction.setToolTip("Sort the units by value")
472                 self._sortByUnitAction = QtGui.QAction(self._sortActionGroup)
473                 self._sortByUnitAction.setText("Sort By Unit")
474                 self._sortByUnitAction.setStatusTip("Sort the units by unit")
475                 self._sortByUnitAction.setToolTip("Sort the units by unit")
476
477                 self._sortByValueAction.setChecked(True)
478
479                 viewMenu = self._window.menuBar().addMenu("&View")
480                 viewMenu.addAction(self._app.jumpAction)
481                 viewMenu.addSeparator()
482                 viewMenu.addAction(self._sortByNameAction)
483                 viewMenu.addAction(self._sortByValueAction)
484                 viewMenu.addAction(self._sortByUnitAction)
485
486                 self._sortByNameAction.triggered.connect(self._on_sort_by_name)
487                 self._sortByValueAction.triggered.connect(self._on_sort_by_value)
488                 self._sortByUnitAction.triggered.connect(self._on_sort_by_unit)
489
490                 self._window.show()
491
492         def close(self):
493                 self._window.close()
494
495         def select_unit(self, unitName):
496                 index = self._unitsModel.index_unit(unitName)
497                 self._select_unit(index)
498
499         @misc_utils.log_exception(_moduleLogger)
500         def _on_sort_by_name(self, checked = False):
501                 self._unitsModel.sort(0, QtCore.Qt.DescendingOrder)
502
503         @misc_utils.log_exception(_moduleLogger)
504         def _on_sort_by_value(self, checked = False):
505                 self._unitsModel.sort(1)
506
507         @misc_utils.log_exception(_moduleLogger)
508         def _on_sort_by_unit(self, checked = False):
509                 self._unitsModel.sort(3, QtCore.Qt.DescendingOrder)
510
511         @misc_utils.log_exception(_moduleLogger)
512         def _on_unit_clicked(self, index):
513                 self._select_unit(index.row())
514
515         @misc_utils.log_exception(_moduleLogger)
516         def _on_value_edited(self, *args):
517                 userInput = self._selectedUnitValue.text()
518                 self._unitsModel.update_values(self._selectedIndex, str(userInput))
519
520         def _select_unit(self, index):
521                 unit = self._unitsModel.get_unit(index)
522                 self._selectedUnitName.setText(unit.name)
523                 self._selectedUnitValue.setText(str(unit.value))
524                 self._selectedUnitSymbol.setText(unit.unit)
525
526                 self._selectedIndex = index
527                 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
528                 self._unitsView.scrollTo(qindex)
529
530
531 def run_gonvert():
532         app = QtGui.QApplication([])
533         handle = Gonvert()
534         return app.exec_()
535
536
537 if __name__ == "__main__":
538         logging.basicConfig(level = logging.DEBUG)
539         try:
540                 os.makedirs(constants._data_path_)
541         except OSError, e:
542                 if e.errno != 17:
543                         raise
544
545         val = run_gonvert()
546         sys.exit(val)