Basic category selection and unit conversion now working
[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 try:
19         import gettext
20 except ImportError:
21         _ = lambda x: x
22         gettext = None
23 else:
24         _ = gettext.gettext
25
26
27 _moduleLogger = logging.getLogger("gonvert_glade")
28
29 if gettext is not None:
30         gettext.bindtextdomain('gonvert', '/usr/share/locale')
31         gettext.textdomain('gonvert')
32
33
34 def change_menu_label(widgets, labelname, newtext):
35         item_label = widgets.get_widget(labelname).get_children()[0]
36         item_label.set_text(newtext)
37
38
39 def split_number(number):
40         try:
41                 fractional, integer = math.modf(number)
42         except TypeError:
43                 integerDisplay = number
44                 fractionalDisplay = ""
45         else:
46                 integerDisplay = str(integer)
47                 fractionalDisplay = str(fractional)
48                 if "e+" in integerDisplay:
49                         integerDisplay = number
50                         fractionalDisplay = ""
51                 elif "e-" in fractionalDisplay and 0.0 < integer:
52                         integerDisplay = number
53                         fractionalDisplay = ""
54                 elif "e-" in fractionalDisplay:
55                         integerDisplay = ""
56                         fractionalDisplay = number
57                 else:
58                         integerDisplay = integerDisplay.split(".", 1)[0] + "."
59                         fractionalDisplay = fractionalDisplay.rsplit(".", 1)[-1]
60
61         return integerDisplay, fractionalDisplay
62
63
64 class Gonvert(object):
65
66         _DATA_PATHS = [
67                 os.path.dirname(__file__),
68                 os.path.join(os.path.dirname(__file__), "../data"),
69                 os.path.join(os.path.dirname(__file__), "../lib"),
70                 '/usr/share/gonvert',
71                 '/usr/lib/gonvert',
72         ]
73
74         def __init__(self):
75                 self._dataPath = ""
76                 for dataPath in self._DATA_PATHS:
77                         appIconPath = os.path.join(dataPath, "pixmaps", "gonvert.png")
78                         if os.path.isfile(appIconPath):
79                                 self._dataPath = dataPath
80                                 break
81                 else:
82                         raise RuntimeError("UI Descriptor not found!")
83
84                 self._catWindow = CategoryWindow(None, appIconPath)
85
86
87 class CategoryWindow(object):
88
89         def __init__(self, parent, appIconPath):
90                 self._appIconPath = appIconPath
91                 self._unitWindows = []
92
93                 self._categories = QtGui.QTreeWidget()
94                 self._categories.setHeaderLabels(["Categories"])
95                 self._categories.itemClicked.connect(self._on_category_clicked)
96                 for catName in unit_data.UNIT_CATEGORIES:
97                         twi = QtGui.QTreeWidgetItem(self._categories)
98                         twi.setText(0, catName)
99
100                 self._layout = QtGui.QVBoxLayout()
101                 self._layout.addWidget(self._categories)
102
103                 centralWidget = QtGui.QWidget()
104                 centralWidget.setLayout(self._layout)
105
106                 self._window = QtGui.QMainWindow(parent)
107                 if parent is not None:
108                         self._window.setWindowModality(QtCore.Qt.WindowModal)
109                 self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
110                 self._window.setWindowIcon(QtGui.QIcon(appIconPath))
111                 self._window.setCentralWidget(centralWidget)
112
113                 self._window.show()
114
115         @misc_utils.log_exception(_moduleLogger)
116         def _on_category_clicked(self, item, columnIndex):
117                 categoryName = unicode(item.text(0))
118                 unitWindow = UnitWindow(self._window, categoryName, self._appIconPath)
119                 self._unitWindows = [unitWindow]
120
121
122 class UnitData(object):
123
124         HEADERS = ["Name", "Value", "", "Unit"]
125         ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
126
127         def __init__(self, name, unit, description, conversion):
128                 self._name = name
129                 self._unit = unit
130                 self._description = description
131                 self._conversion = conversion
132
133                 self._value = 0.0
134                 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
135
136         @property
137         def name(self):
138                 return self._name
139
140         @property
141         def value(self):
142                 return self._value
143
144         def update_value(self, newValue):
145                 self._value = newValue
146                 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
147
148         @property
149         def unit(self):
150                 return self._unit
151
152         @property
153         def conversion(self):
154                 return self._conversion
155
156         def data(self, column):
157                 try:
158                         return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
159                 except IndexError:
160                         return None
161
162
163 class UnitModel(QtCore.QAbstractItemModel):
164
165         def __init__(self, categoryName, parent=None):
166                 super(UnitModel, self).__init__(parent)
167                 self._categoryName = categoryName
168                 self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
169
170                 self._children = []
171                 for key in unit_data.get_units(self._categoryName):
172                         conversion, unit, description = self._unitData[key]
173                         self._children.append(UnitData(key, unit, description, conversion))
174
175         @misc_utils.log_exception(_moduleLogger)
176         def columnCount(self, parent):
177                 if parent.isValid():
178                         return 0
179                 else:
180                         return len(UnitData.HEADERS)
181
182         @misc_utils.log_exception(_moduleLogger)
183         def data(self, index, role):
184                 if not index.isValid():
185                         return None
186                 elif role == QtCore.Qt.TextAlignmentRole:
187                         return UnitData.ALIGNMENT[index.column()]
188                 elif role != QtCore.Qt.DisplayRole:
189                         return None
190
191                 item = index.internalPointer()
192                 if isinstance(item, UnitData):
193                         return item.data(index.column())
194                 elif item is UnitData.HEADERS:
195                         return item[index.column()]
196
197         @misc_utils.log_exception(_moduleLogger)
198         def flags(self, index):
199                 if not index.isValid():
200                         return QtCore.Qt.NoItemFlags
201
202                 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
203
204         @misc_utils.log_exception(_moduleLogger)
205         def headerData(self, section, orientation, role):
206                 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
207                         return UnitData.HEADERS[section]
208
209                 return None
210
211         @misc_utils.log_exception(_moduleLogger)
212         def index(self, row, column, parent):
213                 if not self.hasIndex(row, column, parent):
214                         return QtCore.QModelIndex()
215
216                 if parent.isValid():
217                         return QtCore.QModelIndex()
218
219                 parentItem = UnitData.HEADERS
220                 childItem = self._children[row]
221                 if childItem:
222                         return self.createIndex(row, column, childItem)
223                 else:
224                         return QtCore.QModelIndex()
225
226         @misc_utils.log_exception(_moduleLogger)
227         def parent(self, index):
228                 if not index.isValid():
229                         return QtCore.QModelIndex()
230
231                 childItem = index.internalPointer()
232                 if isinstance(childItem, UnitData):
233                         return QtCore.QModelIndex()
234                 elif childItem is UnitData.HEADERS:
235                         return None
236
237         @misc_utils.log_exception(_moduleLogger)
238         def rowCount(self, parent):
239                 if 0 < parent.column():
240                         return 0
241
242                 if not parent.isValid():
243                         return len(self._children)
244                 else:
245                         return len(self._children)
246
247         def get_unit(self, index):
248                 return self._children[index]
249
250         def update_values(self, fromIndex, userInput):
251                 value = self._sanitize_value(userInput)
252                 func, arg = self._children[fromIndex].conversion
253                 base = func.to_base(value, arg)
254                 for i, child in enumerate(self._children):
255                         if i == fromIndex:
256                                 continue
257                         func, arg = child.conversion
258                         newValue = func.from_base(base, arg)
259                         child.update_value(newValue)
260
261                 topLeft = self.createIndex(0, 1, self._children[0])
262                 bottomRight = self.createIndex(len(self._children)-1, 2, self._children[-1])
263                 self.dataChanged.emit(topLeft, bottomRight)
264
265         def _sanitize_value(self, userEntry):
266                 if self._categoryName == "Computer Numbers":
267                         if userEntry == '':
268                                 value = '0'
269                         else:
270                                 value = userEntry
271                 else:
272                         if userEntry == '':
273                                 value = 0.0
274                         else:
275                                 value = float(userEntry)
276                 return value
277
278
279 class UnitWindow(object):
280
281         def __init__(self, parent, category, appIconPath):
282                 self._categoryName = category
283                 self._selectedIndex = 0
284
285                 self._selectedUnitName = QtGui.QLabel()
286                 self._selectedUnitValue = QtGui.QLineEdit()
287                 self._selectedUnitValue.textEdited.connect(self._on_value_edited)
288                 self._selectedUnitValue.editingFinished.connect(self._on_value_edited)
289                 self._selectedUnitSymbol = QtGui.QLabel()
290
291                 self._selectedUnitLayout = QtGui.QHBoxLayout()
292                 self._selectedUnitLayout.addWidget(self._selectedUnitName)
293                 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
294                 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
295
296                 self._unitsModel = UnitModel(self._categoryName)
297                 self._unitsView = QtGui.QTreeView()
298                 self._unitsView.setModel(self._unitsModel)
299                 self._unitsView.clicked.connect(self._on_unit_clicked)
300                 self._unitsView.setUniformRowHeights(True)
301
302                 self._searchButton = QtGui.QPushButton()
303                 self._searchEntry = QtGui.QLineEdit()
304                 self._searchCloseButton = QtGui.QPushButton()
305
306                 self._searchLayout = QtGui.QHBoxLayout()
307                 self._searchLayout.addWidget(self._searchButton)
308                 self._searchLayout.addWidget(self._searchEntry)
309                 self._searchLayout.addWidget(self._searchCloseButton)
310
311                 self._layout = QtGui.QVBoxLayout()
312                 self._layout.addLayout(self._selectedUnitLayout)
313                 self._layout.addWidget(self._unitsView)
314                 self._layout.addLayout(self._searchLayout)
315
316                 centralWidget = QtGui.QWidget()
317                 centralWidget.setLayout(self._layout)
318
319                 self._window = QtGui.QMainWindow(parent)
320                 if parent is not None:
321                         self._window.setWindowModality(QtCore.Qt.WindowModal)
322                 self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
323                 self._window.setWindowIcon(QtGui.QIcon(appIconPath))
324                 self._window.setCentralWidget(centralWidget)
325
326                 self._select_unit(0)
327
328                 self._window.show()
329                 self._hide_search()
330
331         def _hide_search(self):
332                 self._searchButton.hide()
333                 self._searchEntry.hide()
334                 self._searchCloseButton.hide()
335
336         @misc_utils.log_exception(_moduleLogger)
337         def _on_unit_clicked(self, index):
338                 self._select_unit(index.row())
339
340         @misc_utils.log_exception(_moduleLogger)
341         def _on_value_edited(self, *args):
342                 userInput = self._selectedUnitValue.text()
343                 self._unitsModel.update_values(self._selectedIndex, str(userInput))
344
345         def _select_unit(self, index):
346                 unit = self._unitsModel.get_unit(index)
347                 self._selectedUnitName.setText(unit.name)
348                 self._selectedUnitValue.setText(str(unit.value))
349                 self._selectedUnitSymbol.setText(unit.unit)
350
351                 self._selectedIndex = index
352                 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
353                 self._unitsView.scrollTo(qindex)
354
355
356 def run_gonvert():
357         app = QtGui.QApplication([])
358         handle = Gonvert()
359         return app.exec_()
360
361
362 if __name__ == "__main__":
363         logging.basicConfig(level = logging.DEBUG)
364         try:
365                 os.makedirs(constants._data_path_)
366         except OSError, e:
367                 if e.errno != 17:
368                         raise
369
370         val = run_gonvert()
371         sys.exit(val)