4 from __future__ import with_statement
11 from PyQt4 import QtGui
12 from PyQt4 import QtCore
15 from util import misc as misc_utils
27 _moduleLogger = logging.getLogger("gonvert_glade")
29 if gettext is not None:
30 gettext.bindtextdomain('gonvert', '/usr/share/locale')
31 gettext.textdomain('gonvert')
34 def change_menu_label(widgets, labelname, newtext):
35 item_label = widgets.get_widget(labelname).get_children()[0]
36 item_label.set_text(newtext)
39 def split_number(number):
41 fractional, integer = math.modf(number)
43 integerDisplay = number
44 fractionalDisplay = ""
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:
56 fractionalDisplay = number
58 integerDisplay = integerDisplay.split(".", 1)[0] + "."
59 fractionalDisplay = fractionalDisplay.rsplit(".", 1)[-1]
61 return integerDisplay, fractionalDisplay
64 class Gonvert(object):
67 os.path.dirname(__file__),
68 os.path.join(os.path.dirname(__file__), "../data"),
69 os.path.join(os.path.dirname(__file__), "../lib"),
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
82 raise RuntimeError("UI Descriptor not found!")
84 self._catWindow = CategoryWindow(None, appIconPath)
87 class CategoryWindow(object):
89 def __init__(self, parent, appIconPath):
90 self._appIconPath = appIconPath
91 self._unitWindows = []
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)
100 self._layout = QtGui.QVBoxLayout()
101 self._layout.addWidget(self._categories)
103 centralWidget = QtGui.QWidget()
104 centralWidget.setLayout(self._layout)
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)
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]
122 class UnitData(object):
124 HEADERS = ["Name", "Value", "", "Unit"]
125 ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
127 def __init__(self, name, unit, description, conversion):
130 self._description = description
131 self._conversion = conversion
134 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
144 def update_value(self, newValue):
145 self._value = newValue
146 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
153 def conversion(self):
154 return self._conversion
156 def data(self, column):
158 return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
163 class UnitModel(QtCore.QAbstractItemModel):
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]
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))
175 @misc_utils.log_exception(_moduleLogger)
176 def columnCount(self, parent):
180 return len(UnitData.HEADERS)
182 @misc_utils.log_exception(_moduleLogger)
183 def data(self, index, role):
184 if not index.isValid():
186 elif role == QtCore.Qt.TextAlignmentRole:
187 return UnitData.ALIGNMENT[index.column()]
188 elif role != QtCore.Qt.DisplayRole:
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()]
197 @misc_utils.log_exception(_moduleLogger)
198 def flags(self, index):
199 if not index.isValid():
200 return QtCore.Qt.NoItemFlags
202 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
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]
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()
217 return QtCore.QModelIndex()
219 parentItem = UnitData.HEADERS
220 childItem = self._children[row]
222 return self.createIndex(row, column, childItem)
224 return QtCore.QModelIndex()
226 @misc_utils.log_exception(_moduleLogger)
227 def parent(self, index):
228 if not index.isValid():
229 return QtCore.QModelIndex()
231 childItem = index.internalPointer()
232 if isinstance(childItem, UnitData):
233 return QtCore.QModelIndex()
234 elif childItem is UnitData.HEADERS:
237 @misc_utils.log_exception(_moduleLogger)
238 def rowCount(self, parent):
239 if 0 < parent.column():
242 if not parent.isValid():
243 return len(self._children)
245 return len(self._children)
247 def get_unit(self, index):
248 return self._children[index]
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):
257 func, arg = child.conversion
258 newValue = func.from_base(base, arg)
259 child.update_value(newValue)
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)
265 def _sanitize_value(self, userEntry):
266 if self._categoryName == "Computer Numbers":
275 value = float(userEntry)
279 class UnitWindow(object):
281 def __init__(self, parent, category, appIconPath):
282 self._categoryName = category
283 self._selectedIndex = 0
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()
291 self._selectedUnitLayout = QtGui.QHBoxLayout()
292 self._selectedUnitLayout.addWidget(self._selectedUnitName)
293 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
294 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
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)
302 self._searchButton = QtGui.QPushButton()
303 self._searchEntry = QtGui.QLineEdit()
304 self._searchCloseButton = QtGui.QPushButton()
306 self._searchLayout = QtGui.QHBoxLayout()
307 self._searchLayout.addWidget(self._searchButton)
308 self._searchLayout.addWidget(self._searchEntry)
309 self._searchLayout.addWidget(self._searchCloseButton)
311 self._layout = QtGui.QVBoxLayout()
312 self._layout.addLayout(self._selectedUnitLayout)
313 self._layout.addWidget(self._unitsView)
314 self._layout.addLayout(self._searchLayout)
316 centralWidget = QtGui.QWidget()
317 centralWidget.setLayout(self._layout)
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)
331 def _hide_search(self):
332 self._searchButton.hide()
333 self._searchEntry.hide()
334 self._searchCloseButton.hide()
336 @misc_utils.log_exception(_moduleLogger)
337 def _on_unit_clicked(self, index):
338 self._select_unit(index.row())
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))
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)
351 self._selectedIndex = index
352 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
353 self._unitsView.scrollTo(qindex)
357 app = QtGui.QApplication([])
362 if __name__ == "__main__":
363 logging.basicConfig(level = logging.DEBUG)
365 os.makedirs(constants._data_path_)