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 self._categories.setHeaderHidden(True)
97 for catName in unit_data.UNIT_CATEGORIES:
98 twi = QtGui.QTreeWidgetItem(self._categories)
99 twi.setText(0, catName)
101 self._layout = QtGui.QVBoxLayout()
102 self._layout.addWidget(self._categories)
104 centralWidget = QtGui.QWidget()
105 centralWidget.setLayout(self._layout)
107 self._window = QtGui.QMainWindow(parent)
108 if parent is not None:
109 self._window.setWindowModality(QtCore.Qt.WindowModal)
110 self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
111 self._window.setWindowIcon(QtGui.QIcon(appIconPath))
112 self._window.setCentralWidget(centralWidget)
116 @misc_utils.log_exception(_moduleLogger)
117 def _on_category_clicked(self, item, columnIndex):
118 categoryName = unicode(item.text(0))
119 unitWindow = UnitWindow(self._window, categoryName, self._appIconPath)
120 self._unitWindows = [unitWindow]
123 class UnitData(object):
125 HEADERS = ["Name", "Value", "", "Unit"]
126 ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
128 def __init__(self, name, unit, description, conversion):
131 self._description = description
132 self._conversion = conversion
135 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
145 def update_value(self, newValue):
146 self._value = newValue
147 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
154 def conversion(self):
155 return self._conversion
157 def data(self, column):
159 return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
164 class UnitModel(QtCore.QAbstractItemModel):
166 def __init__(self, categoryName, parent=None):
167 super(UnitModel, self).__init__(parent)
168 self._categoryName = categoryName
169 self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
172 for key in unit_data.get_units(self._categoryName):
173 conversion, unit, description = self._unitData[key]
174 self._children.append(UnitData(key, unit, description, conversion))
176 @misc_utils.log_exception(_moduleLogger)
177 def columnCount(self, parent):
181 return len(UnitData.HEADERS)
183 @misc_utils.log_exception(_moduleLogger)
184 def data(self, index, role):
185 if not index.isValid():
187 elif role == QtCore.Qt.TextAlignmentRole:
188 return UnitData.ALIGNMENT[index.column()]
189 elif role != QtCore.Qt.DisplayRole:
192 item = index.internalPointer()
193 if isinstance(item, UnitData):
194 return item.data(index.column())
195 elif item is UnitData.HEADERS:
196 return item[index.column()]
198 @misc_utils.log_exception(_moduleLogger)
199 def sort(self, column, order = QtCore.Qt.AscendingOrder):
200 isReverse = order == QtCore.Qt.AscendingOrder
202 key_func = lambda item: item.name
203 elif column in [1, 2]:
204 key_func = lambda item: item.value
206 key_func = lambda item: item.unit
207 self._children.sort(key=key_func, reverse = isReverse)
211 @misc_utils.log_exception(_moduleLogger)
212 def flags(self, index):
213 if not index.isValid():
214 return QtCore.Qt.NoItemFlags
216 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
218 @misc_utils.log_exception(_moduleLogger)
219 def headerData(self, section, orientation, role):
220 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
221 return UnitData.HEADERS[section]
225 @misc_utils.log_exception(_moduleLogger)
226 def index(self, row, column, parent):
227 if not self.hasIndex(row, column, parent):
228 return QtCore.QModelIndex()
231 return QtCore.QModelIndex()
233 parentItem = UnitData.HEADERS
234 childItem = self._children[row]
236 return self.createIndex(row, column, childItem)
238 return QtCore.QModelIndex()
240 @misc_utils.log_exception(_moduleLogger)
241 def parent(self, index):
242 if not index.isValid():
243 return QtCore.QModelIndex()
245 childItem = index.internalPointer()
246 if isinstance(childItem, UnitData):
247 return QtCore.QModelIndex()
248 elif childItem is UnitData.HEADERS:
251 @misc_utils.log_exception(_moduleLogger)
252 def rowCount(self, parent):
253 if 0 < parent.column():
256 if not parent.isValid():
257 return len(self._children)
259 return len(self._children)
261 def get_unit(self, index):
262 return self._children[index]
264 def update_values(self, fromIndex, userInput):
265 value = self._sanitize_value(userInput)
266 func, arg = self._children[fromIndex].conversion
267 base = func.to_base(value, arg)
268 for i, child in enumerate(self._children):
271 func, arg = child.conversion
272 newValue = func.from_base(base, arg)
273 child.update_value(newValue)
277 def _all_changed(self):
278 topLeft = self.createIndex(0, 1, self._children[0])
279 bottomRight = self.createIndex(len(self._children)-1, 2, self._children[-1])
280 self.dataChanged.emit(topLeft, bottomRight)
282 def _sanitize_value(self, userEntry):
283 if self._categoryName == "Computer Numbers":
292 value = float(userEntry)
296 class UnitWindow(object):
298 def __init__(self, parent, category, appIconPath):
299 self._categoryName = category
300 self._selectedIndex = 0
302 self._selectedUnitName = QtGui.QLabel()
303 self._selectedUnitValue = QtGui.QLineEdit()
304 self._selectedUnitValue.textEdited.connect(self._on_value_edited)
305 self._selectedUnitValue.editingFinished.connect(self._on_value_edited)
306 self._selectedUnitSymbol = QtGui.QLabel()
308 self._selectedUnitLayout = QtGui.QHBoxLayout()
309 self._selectedUnitLayout.addWidget(self._selectedUnitName)
310 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
311 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
313 self._unitsModel = UnitModel(self._categoryName)
314 self._unitsView = QtGui.QTreeView()
315 self._unitsView.setModel(self._unitsModel)
316 self._unitsView.clicked.connect(self._on_unit_clicked)
317 self._unitsView.setUniformRowHeights(True)
318 self._unitsView.header().setSortIndicatorShown(True)
319 self._unitsView.header().setClickable(True)
320 self._unitsView.setSortingEnabled(True)
322 self._unitsView.setHeaderHidden(True)
324 self._searchButton = QtGui.QPushButton()
325 self._searchEntry = QtGui.QLineEdit()
326 self._searchCloseButton = QtGui.QPushButton()
328 self._searchLayout = QtGui.QHBoxLayout()
329 self._searchLayout.addWidget(self._searchButton)
330 self._searchLayout.addWidget(self._searchEntry)
331 self._searchLayout.addWidget(self._searchCloseButton)
333 self._layout = QtGui.QVBoxLayout()
334 self._layout.addLayout(self._selectedUnitLayout)
335 self._layout.addWidget(self._unitsView)
336 self._layout.addLayout(self._searchLayout)
338 centralWidget = QtGui.QWidget()
339 centralWidget.setLayout(self._layout)
341 self._window = QtGui.QMainWindow(parent)
342 if parent is not None:
343 self._window.setWindowModality(QtCore.Qt.WindowModal)
344 self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
345 self._window.setWindowIcon(QtGui.QIcon(appIconPath))
346 self._window.setCentralWidget(centralWidget)
353 def _hide_search(self):
354 self._searchButton.hide()
355 self._searchEntry.hide()
356 self._searchCloseButton.hide()
358 @misc_utils.log_exception(_moduleLogger)
359 def _on_unit_clicked(self, index):
360 self._select_unit(index.row())
362 @misc_utils.log_exception(_moduleLogger)
363 def _on_value_edited(self, *args):
364 userInput = self._selectedUnitValue.text()
365 self._unitsModel.update_values(self._selectedIndex, str(userInput))
367 def _select_unit(self, index):
368 unit = self._unitsModel.get_unit(index)
369 self._selectedUnitName.setText(unit.name)
370 self._selectedUnitValue.setText(str(unit.value))
371 self._selectedUnitSymbol.setText(unit.unit)
373 self._selectedIndex = index
374 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
375 self._unitsView.scrollTo(qindex)
379 app = QtGui.QApplication([])
384 if __name__ == "__main__":
385 logging.basicConfig(level = logging.DEBUG)
387 os.makedirs(constants._data_path_)