4 from __future__ import with_statement
11 from PyQt4 import QtGui
12 from PyQt4 import QtCore
15 from util import misc as misc_utils
19 _moduleLogger = logging.getLogger("gonvert_glade")
22 def change_menu_label(widgets, labelname, newtext):
23 item_label = widgets.get_widget(labelname).get_children()[0]
24 item_label.set_text(newtext)
27 def split_number(number):
29 fractional, integer = math.modf(number)
31 integerDisplay = number
32 fractionalDisplay = ""
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:
44 fractionalDisplay = number
46 integerDisplay = integerDisplay.split(".", 1)[0] + "."
47 fractionalDisplay = fractionalDisplay.rsplit(".", 1)[-1]
49 return integerDisplay, fractionalDisplay
52 class Gonvert(object):
55 os.path.dirname(__file__),
56 os.path.join(os.path.dirname(__file__), "../data"),
57 os.path.join(os.path.dirname(__file__), "../lib"),
64 for dataPath in self._DATA_PATHS:
65 appIconPath = os.path.join(dataPath, "pixmaps", "gonvert.png")
66 if os.path.isfile(appIconPath):
67 self._dataPath = dataPath
70 raise RuntimeError("UI Descriptor not found!")
71 self._appIconPath = appIconPath
73 self._jumpWindow = None
74 self._catWindow = None
76 self._jumpAction = QtGui.QAction(None)
77 self._jumpAction.setText("Quick Jump")
78 self._jumpAction.setStatusTip("Search for a unit and jump straight to it")
79 self._jumpAction.setToolTip("Search for a unit and jump straight to it")
80 self._jumpAction.setShortcut(QtGui.QKeySequence("CTRL+j"))
82 self.request_category()
84 def request_category(self):
85 if self._catWindow is not None:
86 self._catWindow.close()
87 self._catWindow = None
88 self._catWindow = CategoryWindow(None, self)
89 return self._catWindow
91 def search_units(self):
92 if self._jumpWindow is not None:
93 self._jumpWindow.close()
94 self._jumpWindow = None
95 self._jumpWindow = QuickJump(None, self)
96 return self._jumpWindow
99 def appIconPath(self):
100 return self._appIconPath
103 def jumpAction(self):
104 return self._jumpAction
107 class CategoryWindow(object):
109 def __init__(self, parent, app):
111 self._unitWindow = None
113 self._categories = QtGui.QTreeWidget()
114 self._categories.setHeaderLabels(["Categories"])
115 self._categories.itemClicked.connect(self._on_category_clicked)
116 self._categories.setHeaderHidden(True)
117 for catName in unit_data.UNIT_CATEGORIES:
118 twi = QtGui.QTreeWidgetItem(self._categories)
119 twi.setText(0, catName)
121 self._layout = QtGui.QVBoxLayout()
122 self._layout.addWidget(self._categories)
124 centralWidget = QtGui.QWidget()
125 centralWidget.setLayout(self._layout)
127 self._window = QtGui.QMainWindow(parent)
128 if parent is not None:
129 self._window.setWindowModality(QtCore.Qt.WindowModal)
130 self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
131 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
132 self._window.setCentralWidget(centralWidget)
134 viewMenu = self._window.menuBar().addMenu("&View")
135 viewMenu.addAction(self._app.jumpAction)
137 self._app.jumpAction.triggered.connect(self._on_jump_start)
144 def selectCategory(self, categoryName):
145 if self._unitWindow is not None:
146 self._unitWindow.close()
147 self._unitWindow = None
148 self._unitWindow = UnitWindow(self._window, categoryName, self._app)
149 return self._unitWindow
151 @misc_utils.log_exception(_moduleLogger)
152 def _on_jump_start(self, checked = False):
153 self._app.search_units()
155 @misc_utils.log_exception(_moduleLogger)
156 def _on_category_clicked(self, item, columnIndex):
157 categoryName = unicode(item.text(0))
158 self.selectCategory(categoryName)
161 class QuickJump(object):
165 def __init__(self, parent, app):
168 self._searchLabel = QtGui.QLabel("Search:")
169 self._searchEntry = QtGui.QLineEdit("")
170 self._searchEntry.textEdited.connect(self._on_search_edited)
172 self._entryLayout = QtGui.QHBoxLayout()
173 self._entryLayout.addWidget(self._searchLabel)
174 self._entryLayout.addWidget(self._searchEntry)
176 self._resultsBox = QtGui.QTreeWidget()
177 self._resultsBox.setHeaderLabels(["Categories", "Units"])
178 self._resultsBox.setHeaderHidden(True)
179 self._resultsBox.itemClicked.connect(self._on_result_clicked)
181 self._layout = QtGui.QVBoxLayout()
182 self._layout.addLayout(self._entryLayout)
183 self._layout.addWidget(self._resultsBox)
185 centralWidget = QtGui.QWidget()
186 centralWidget.setLayout(self._layout)
188 self._window = QtGui.QMainWindow(parent)
189 if parent is not None:
190 self._window.setWindowModality(QtCore.Qt.WindowModal)
191 self._window.setWindowTitle("%s - Quick Jump" % constants.__pretty_app_name__)
192 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
193 self._window.setCentralWidget(centralWidget)
200 @misc_utils.log_exception(_moduleLogger)
201 def _on_result_clicked(self, item, columnIndex):
202 categoryName = unicode(item.text(0))
203 unitName = unicode(item.text(1))
204 catWindow = self._app.request_category()
205 unitsWindow = catWindow.selectCategory(categoryName)
206 unitsWindow.select_unit(unitName)
208 @misc_utils.log_exception(_moduleLogger)
209 def _on_search_edited(self, *args):
210 userInput = self._searchEntry.text()
211 if len(userInput) < self.MINIMAL_ENTRY:
214 lowerInput = str(userInput).lower()
215 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
216 units = unit_data.get_units(category)
217 for unitIndex, unit in enumerate(units):
218 loweredUnit = unit.lower()
219 if lowerInput in loweredUnit:
220 twi = QtGui.QTreeWidgetItem(self._resultsBox)
221 twi.setText(0, category)
225 class UnitData(object):
227 HEADERS = ["Name", "Value", "", "Unit"]
228 ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
230 def __init__(self, name, unit, description, conversion):
233 self._description = description
234 self._conversion = conversion
237 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
247 def update_value(self, newValue):
248 self._value = newValue
249 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
256 def conversion(self):
257 return self._conversion
259 def data(self, column):
261 return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
266 class UnitModel(QtCore.QAbstractItemModel):
268 def __init__(self, categoryName, parent=None):
269 super(UnitModel, self).__init__(parent)
270 self._categoryName = categoryName
271 self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
274 for key in unit_data.get_units(self._categoryName):
275 conversion, unit, description = self._unitData[key]
276 self._children.append(UnitData(key, unit, description, conversion))
278 @misc_utils.log_exception(_moduleLogger)
279 def columnCount(self, parent):
283 return len(UnitData.HEADERS)
285 @misc_utils.log_exception(_moduleLogger)
286 def data(self, index, role):
287 if not index.isValid():
289 elif role == QtCore.Qt.TextAlignmentRole:
290 return UnitData.ALIGNMENT[index.column()]
291 elif role != QtCore.Qt.DisplayRole:
294 item = index.internalPointer()
295 if isinstance(item, UnitData):
296 return item.data(index.column())
297 elif item is UnitData.HEADERS:
298 return item[index.column()]
300 @misc_utils.log_exception(_moduleLogger)
301 def sort(self, column, order = QtCore.Qt.AscendingOrder):
302 isReverse = order == QtCore.Qt.AscendingOrder
304 key_func = lambda item: item.name
305 elif column in [1, 2]:
306 key_func = lambda item: item.value
308 key_func = lambda item: item.unit
309 self._children.sort(key=key_func, reverse = isReverse)
313 @misc_utils.log_exception(_moduleLogger)
314 def flags(self, index):
315 if not index.isValid():
316 return QtCore.Qt.NoItemFlags
318 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
320 @misc_utils.log_exception(_moduleLogger)
321 def headerData(self, section, orientation, role):
322 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
323 return UnitData.HEADERS[section]
327 @misc_utils.log_exception(_moduleLogger)
328 def index(self, row, column, parent):
329 if not self.hasIndex(row, column, parent):
330 return QtCore.QModelIndex()
333 return QtCore.QModelIndex()
335 parentItem = UnitData.HEADERS
336 childItem = self._children[row]
338 return self.createIndex(row, column, childItem)
340 return QtCore.QModelIndex()
342 @misc_utils.log_exception(_moduleLogger)
343 def parent(self, index):
344 if not index.isValid():
345 return QtCore.QModelIndex()
347 childItem = index.internalPointer()
348 if isinstance(childItem, UnitData):
349 return QtCore.QModelIndex()
350 elif childItem is UnitData.HEADERS:
353 @misc_utils.log_exception(_moduleLogger)
354 def rowCount(self, parent):
355 if 0 < parent.column():
358 if not parent.isValid():
359 return len(self._children)
361 return len(self._children)
363 def get_unit(self, index):
364 return self._children[index]
366 def index_unit(self, unitName):
367 for i, child in enumerate(self._children):
368 if child.name == unitName:
371 raise RuntimeError("Unit not found")
373 def update_values(self, fromIndex, userInput):
374 value = self._sanitize_value(userInput)
375 func, arg = self._children[fromIndex].conversion
376 base = func.to_base(value, arg)
377 for i, child in enumerate(self._children):
380 func, arg = child.conversion
381 newValue = func.from_base(base, arg)
382 child.update_value(newValue)
386 def _all_changed(self):
387 topLeft = self.createIndex(0, 1, self._children[0])
388 bottomRight = self.createIndex(len(self._children)-1, 2, self._children[-1])
389 self.dataChanged.emit(topLeft, bottomRight)
391 def _sanitize_value(self, userEntry):
392 if self._categoryName == "Computer Numbers":
401 value = float(userEntry)
405 class UnitWindow(object):
407 def __init__(self, parent, category, app):
409 self._categoryName = category
410 self._selectedIndex = 0
412 self._selectedUnitName = QtGui.QLabel()
413 self._selectedUnitValue = QtGui.QLineEdit()
414 self._selectedUnitValue.textEdited.connect(self._on_value_edited)
415 self._selectedUnitSymbol = QtGui.QLabel()
417 self._selectedUnitLayout = QtGui.QHBoxLayout()
418 self._selectedUnitLayout.addWidget(self._selectedUnitName)
419 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
420 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
422 self._unitsModel = UnitModel(self._categoryName)
423 self._unitsView = QtGui.QTreeView()
424 self._unitsView.setModel(self._unitsModel)
425 self._unitsView.clicked.connect(self._on_unit_clicked)
426 self._unitsView.setUniformRowHeights(True)
427 self._unitsView.header().setSortIndicatorShown(True)
428 self._unitsView.header().setClickable(True)
429 self._unitsView.setSortingEnabled(True)
431 self._unitsView.setHeaderHidden(True)
433 self._layout = QtGui.QVBoxLayout()
434 self._layout.addLayout(self._selectedUnitLayout)
435 self._layout.addWidget(self._unitsView)
437 centralWidget = QtGui.QWidget()
438 centralWidget.setLayout(self._layout)
440 self._window = QtGui.QMainWindow(parent)
441 if parent is not None:
442 self._window.setWindowModality(QtCore.Qt.WindowModal)
443 self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
444 self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
445 self._window.setCentralWidget(centralWidget)
449 self._sortActionGroup = QtGui.QActionGroup(None)
450 self._sortByNameAction = QtGui.QAction(self._sortActionGroup)
451 self._sortByNameAction.setText("Sort By Name")
452 self._sortByNameAction.setStatusTip("Sort the units by name")
453 self._sortByNameAction.setToolTip("Sort the units by name")
454 self._sortByValueAction = QtGui.QAction(self._sortActionGroup)
455 self._sortByValueAction.setText("Sort By Value")
456 self._sortByValueAction.setStatusTip("Sort the units by value")
457 self._sortByValueAction.setToolTip("Sort the units by value")
458 self._sortByUnitAction = QtGui.QAction(self._sortActionGroup)
459 self._sortByUnitAction.setText("Sort By Unit")
460 self._sortByUnitAction.setStatusTip("Sort the units by unit")
461 self._sortByUnitAction.setToolTip("Sort the units by unit")
463 viewMenu = self._window.menuBar().addMenu("&View")
464 viewMenu.addAction(self._app.jumpAction)
465 viewMenu.addSeparator()
466 viewMenu.addAction(self._sortByNameAction)
467 viewMenu.addAction(self._sortByValueAction)
468 viewMenu.addAction(self._sortByUnitAction)
470 self._app.jumpAction.triggered.connect(self._on_jump_start)
471 self._sortByNameAction.triggered.connect(self._on_sort_by_name)
472 self._sortByValueAction.triggered.connect(self._on_sort_by_value)
473 self._sortByUnitAction.triggered.connect(self._on_sort_by_unit)
480 def select_unit(self, unitName):
481 index = self._unitsModel.index_unit(unitName)
482 self._select_unit(index)
484 @misc_utils.log_exception(_moduleLogger)
485 def _on_sort_by_name(self, checked = False):
486 self._unitsModel.sort(0, QtCore.Qt.DescendingOrder)
488 @misc_utils.log_exception(_moduleLogger)
489 def _on_sort_by_value(self, checked = False):
490 self._unitsModel.sort(1)
492 @misc_utils.log_exception(_moduleLogger)
493 def _on_sort_by_unit(self, checked = False):
494 self._unitsModel.sort(3, QtCore.Qt.DescendingOrder)
496 @misc_utils.log_exception(_moduleLogger)
497 def _on_jump_start(self, checked = False):
498 self._app.search_units()
500 @misc_utils.log_exception(_moduleLogger)
501 def _on_unit_clicked(self, index):
502 self._select_unit(index.row())
504 @misc_utils.log_exception(_moduleLogger)
505 def _on_value_edited(self, *args):
506 userInput = self._selectedUnitValue.text()
507 self._unitsModel.update_values(self._selectedIndex, str(userInput))
509 def _select_unit(self, index):
510 unit = self._unitsModel.get_unit(index)
511 self._selectedUnitName.setText(unit.name)
512 self._selectedUnitValue.setText(str(unit.value))
513 self._selectedUnitSymbol.setText(unit.unit)
515 self._selectedIndex = index
516 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
517 self._unitsView.scrollTo(qindex)
521 app = QtGui.QApplication([])
526 if __name__ == "__main__":
527 logging.basicConfig(level = logging.DEBUG)
529 os.makedirs(constants._data_path_)