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):
54 # @todo Persist settings
56 # @todo Add menus to all windows
57 # @bug Fix the resurrecting window problem
58 # @todo Close Window / Quit keyboard shortcuts
59 # @todo Ctrl+l support
60 # @todo Unit conversion window: focus always on input, arrows switch units
63 os.path.dirname(__file__),
64 os.path.join(os.path.dirname(__file__), "../data"),
65 os.path.join(os.path.dirname(__file__), "../lib"),
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
78 raise RuntimeError("UI Descriptor not found!")
79 self._appIconPath = appIconPath
81 self._isFullscreen = False
83 self._jumpWindow = None
84 self._recentWindow = None
85 self._catWindow = None
87 self._jumpAction = QtGui.QAction(None)
88 self._jumpAction.setText("Quick Jump")
89 self._jumpAction.setStatusTip("Search for a unit and jump straight to it")
90 self._jumpAction.setToolTip("Search for a unit and jump straight to it")
91 self._jumpAction.setShortcut(QtGui.QKeySequence("CTRL+j"))
92 self._jumpAction.triggered.connect(self._on_jump_start)
94 self._recentAction = QtGui.QAction(None)
95 self._recentAction.setText("Recent Units")
96 self._recentAction.setStatusTip("View the recent units")
97 self._recentAction.setToolTip("View the recent units")
98 self._recentAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
99 self._recentAction.triggered.connect(self._on_recent_start)
101 self._fullscreenAction = QtGui.QAction(None)
102 self._fullscreenAction.setText("Toggle Fullscreen")
103 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
104 self._fullscreenAction.triggered.connect(self._on_toggle_fullscreen)
106 self.request_category()
108 def request_category(self):
109 if self._catWindow is not None:
110 self._catWindow.close()
111 self._catWindow = None
112 self._catWindow = CategoryWindow(None, self)
113 return self._catWindow
115 def search_units(self):
116 if self._jumpWindow is not None:
117 self._jumpWindow.close()
118 self._jumpWindow = None
119 self._jumpWindow = QuickJump(None, self)
120 return self._jumpWindow
122 def show_recent(self):
123 if self._recentWindow is not None:
124 self._recentWindow.close()
125 self._recentWindow = None
126 self._recentWindow = Recent(None, self)
127 return self._recentWindow
129 def add_recent(self, categoryName, unitName):
130 catUnit = categoryName, unitName
132 self._recent.remove(catUnit)
134 pass # ignore if its not already in the recent history
135 self._recent.append(catUnit)
137 def get_recent_unit(self, categoryName):
138 for catName, unitName in reversed(self._recent):
139 if catName == categoryName:
144 def get_recent(self):
145 return reversed(self._recent)
148 def appIconPath(self):
149 return self._appIconPath
152 def jumpAction(self):
153 return self._jumpAction
156 def recentAction(self):
157 return self._recentAction
160 def fullscreenAction(self):
161 return self._fullscreenAction
163 def _walk_children(self):
164 if self._catWindow is not None:
165 yield self._catWindow
166 if self._jumpWindow is not None:
167 yield self._jumpWindow
168 if self._recentWindow is not None:
169 yield self._recentWindow
171 @misc_utils.log_exception(_moduleLogger)
172 def _on_toggle_fullscreen(self, checked = False):
173 self._isFullscreen = not self._isFullscreen
174 for window in self._walk_children():
175 window.setFullscreen(self._isFullscreen)
177 @misc_utils.log_exception(_moduleLogger)
178 def _on_jump_start(self, checked = False):
181 @misc_utils.log_exception(_moduleLogger)
182 def _on_recent_start(self, checked = False):
186 class CategoryWindow(object):
188 def __init__(self, parent, app):
190 self._unitWindow = None
192 self._categories = QtGui.QTreeWidget()
193 self._categories.setHeaderLabels(["Categories"])
194 self._categories.itemClicked.connect(self._on_category_clicked)
195 self._categories.setHeaderHidden(True)
196 self._categories.setAlternatingRowColors(True)
197 for catName in unit_data.UNIT_CATEGORIES:
198 twi = QtGui.QTreeWidgetItem(self._categories)
199 twi.setText(0, catName)
201 self._layout = QtGui.QVBoxLayout()
202 self._layout.addWidget(self._categories)
204 centralWidget = QtGui.QWidget()
205 centralWidget.setLayout(self._layout)
207 self._window = QtGui.QMainWindow(parent)
208 if parent is not None:
209 self._window.setWindowModality(QtCore.Qt.WindowModal)
210 self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
211 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
212 self._window.setCentralWidget(centralWidget)
214 viewMenu = self._window.menuBar().addMenu("&View")
215 viewMenu.addAction(self._app.fullscreenAction)
216 viewMenu.addSeparator()
217 viewMenu.addAction(self._app.jumpAction)
218 viewMenu.addAction(self._app.recentAction)
222 def walk_children(self):
223 if self._unitWindow is not None:
224 yield self._unitWindow
227 for child in self.walk_children():
231 def selectCategory(self, categoryName):
232 for child in self.walk_children():
234 self._unitWindow = UnitWindow(self._window, categoryName, self._app)
235 return self._unitWindow
237 def setFullscreen(self, isFullscreen):
239 self._window.showFullScreen()
241 self._window.showNormal()
242 for child in self.walk_children():
243 child.setFullscreen(isFullscreen)
245 @misc_utils.log_exception(_moduleLogger)
246 def _on_category_clicked(self, item, columnIndex):
247 categoryName = unicode(item.text(0))
248 self.selectCategory(categoryName)
251 class QuickJump(object):
255 def __init__(self, parent, app):
258 self._searchLabel = QtGui.QLabel("Search:")
259 self._searchEntry = QtGui.QLineEdit("")
260 self._searchEntry.textEdited.connect(self._on_search_edited)
262 self._entryLayout = QtGui.QHBoxLayout()
263 self._entryLayout.addWidget(self._searchLabel)
264 self._entryLayout.addWidget(self._searchEntry)
266 self._resultsBox = QtGui.QTreeWidget()
267 self._resultsBox.setHeaderLabels(["Categories", "Units"])
268 self._resultsBox.setHeaderHidden(True)
269 self._resultsBox.setAlternatingRowColors(True)
270 self._resultsBox.itemClicked.connect(self._on_result_clicked)
272 self._layout = QtGui.QVBoxLayout()
273 self._layout.addLayout(self._entryLayout)
274 self._layout.addWidget(self._resultsBox)
276 centralWidget = QtGui.QWidget()
277 centralWidget.setLayout(self._layout)
279 self._window = QtGui.QMainWindow(parent)
280 if parent is not None:
281 self._window.setWindowModality(QtCore.Qt.WindowModal)
282 self._window.setWindowTitle("%s - Quick Jump" % constants.__pretty_app_name__)
283 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
284 self._window.setCentralWidget(centralWidget)
291 def setFullscreen(self, isFullscreen):
293 self._window.showFullScreen()
295 self._window.showNormal()
297 @misc_utils.log_exception(_moduleLogger)
298 def _on_result_clicked(self, item, columnIndex):
299 categoryName = unicode(item.text(0))
300 unitName = unicode(item.text(1))
301 catWindow = self._app.request_category()
302 unitsWindow = catWindow.selectCategory(categoryName)
303 unitsWindow.select_unit(unitName)
306 @misc_utils.log_exception(_moduleLogger)
307 def _on_search_edited(self, *args):
308 userInput = self._searchEntry.text()
309 if len(userInput) < self.MINIMAL_ENTRY:
312 self._resultsBox.clear()
313 lowerInput = str(userInput).lower()
314 for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
315 units = unit_data.get_units(category)
316 for unitIndex, unit in enumerate(units):
317 loweredUnit = unit.lower()
318 if lowerInput in loweredUnit:
319 twi = QtGui.QTreeWidgetItem(self._resultsBox)
320 twi.setText(0, category)
324 class Recent(object):
326 def __init__(self, parent, app):
329 self._resultsBox = QtGui.QTreeWidget()
330 self._resultsBox.setHeaderLabels(["Categories", "Units"])
331 self._resultsBox.setHeaderHidden(True)
332 self._resultsBox.setAlternatingRowColors(True)
333 self._resultsBox.itemClicked.connect(self._on_result_clicked)
335 self._layout = QtGui.QVBoxLayout()
336 self._layout.addWidget(self._resultsBox)
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 - Recent" % constants.__pretty_app_name__)
345 self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
346 self._window.setCentralWidget(centralWidget)
348 for cat, unit in self._app.get_recent():
349 twi = QtGui.QTreeWidgetItem(self._resultsBox)
358 def setFullscreen(self, isFullscreen):
360 self._window.showFullScreen()
362 self._window.showNormal()
364 @misc_utils.log_exception(_moduleLogger)
365 def _on_result_clicked(self, item, columnIndex):
366 categoryName = unicode(item.text(0))
367 unitName = unicode(item.text(1))
368 catWindow = self._app.request_category()
369 unitsWindow = catWindow.selectCategory(categoryName)
370 unitsWindow.select_unit(unitName)
374 class UnitData(object):
376 HEADERS = ["Name", "Value", "", "Unit"]
377 ALIGNMENT = [QtCore.Qt.AlignLeft, QtCore.Qt.AlignRight, QtCore.Qt.AlignLeft, QtCore.Qt.AlignLeft]
379 def __init__(self, name, unit, description, conversion):
382 self._description = description
383 self._conversion = conversion
386 self._integerDisplay, self._fractionalDisplay = split_number(self._value)
396 def update_value(self, newValue):
397 self._value = newValue
398 self._integerDisplay, self._fractionalDisplay = split_number(newValue)
405 def conversion(self):
406 return self._conversion
408 def data(self, column):
410 return [self._name, self._integerDisplay, self._fractionalDisplay, self._unit][column]
415 class UnitModel(QtCore.QAbstractItemModel):
417 def __init__(self, categoryName, parent=None):
418 super(UnitModel, self).__init__(parent)
419 self._categoryName = categoryName
420 self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
423 for key in unit_data.get_units(self._categoryName):
424 conversion, unit, description = self._unitData[key]
425 self._children.append(UnitData(key, unit, description, conversion))
426 self._sortSettings = None
428 @misc_utils.log_exception(_moduleLogger)
429 def columnCount(self, parent):
433 return len(UnitData.HEADERS)
435 @misc_utils.log_exception(_moduleLogger)
436 def data(self, index, role):
437 if not index.isValid():
439 elif role == QtCore.Qt.TextAlignmentRole:
440 return UnitData.ALIGNMENT[index.column()]
441 elif role != QtCore.Qt.DisplayRole:
444 item = index.internalPointer()
445 if isinstance(item, UnitData):
446 return item.data(index.column())
447 elif item is UnitData.HEADERS:
448 return item[index.column()]
450 @misc_utils.log_exception(_moduleLogger)
451 def sort(self, column, order = QtCore.Qt.AscendingOrder):
452 self._sortSettings = column, order
453 isReverse = order == QtCore.Qt.AscendingOrder
455 key_func = lambda item: item.name
456 elif column in [1, 2]:
457 key_func = lambda item: item.value
459 key_func = lambda item: item.unit
460 self._children.sort(key=key_func, reverse = isReverse)
464 @misc_utils.log_exception(_moduleLogger)
465 def flags(self, index):
466 if not index.isValid():
467 return QtCore.Qt.NoItemFlags
469 return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
471 @misc_utils.log_exception(_moduleLogger)
472 def headerData(self, section, orientation, role):
473 if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
474 return UnitData.HEADERS[section]
478 @misc_utils.log_exception(_moduleLogger)
479 def index(self, row, column, parent):
480 if not self.hasIndex(row, column, parent):
481 return QtCore.QModelIndex()
484 return QtCore.QModelIndex()
486 parentItem = UnitData.HEADERS
487 childItem = self._children[row]
489 return self.createIndex(row, column, childItem)
491 return QtCore.QModelIndex()
493 @misc_utils.log_exception(_moduleLogger)
494 def parent(self, index):
495 if not index.isValid():
496 return QtCore.QModelIndex()
498 childItem = index.internalPointer()
499 if isinstance(childItem, UnitData):
500 return QtCore.QModelIndex()
501 elif childItem is UnitData.HEADERS:
504 @misc_utils.log_exception(_moduleLogger)
505 def rowCount(self, parent):
506 if 0 < parent.column():
509 if not parent.isValid():
510 return len(self._children)
512 return len(self._children)
514 def get_unit(self, index):
515 return self._children[index]
517 def index_unit(self, unitName):
518 for i, child in enumerate(self._children):
519 if child.name == unitName:
522 raise RuntimeError("Unit not found")
524 def update_values(self, fromIndex, userInput):
525 value = self._sanitize_value(userInput)
526 func, arg = self._children[fromIndex].conversion
527 base = func.to_base(value, arg)
528 for i, child in enumerate(self._children):
531 func, arg = child.conversion
532 newValue = func.from_base(base, arg)
533 child.update_value(newValue)
535 if self._sortSettings is not None:
536 self.sort(*self._sortSettings)
539 def _all_changed(self):
540 topLeft = self.createIndex(0, 0, self._children[0])
541 bottomRight = self.createIndex(len(self._children)-1, len(UnitData.HEADERS)-1, self._children[-1])
542 self.dataChanged.emit(topLeft, bottomRight)
544 def _sanitize_value(self, userEntry):
545 if self._categoryName == "Computer Numbers":
554 value = float(userEntry)
558 class UnitWindow(object):
560 def __init__(self, parent, category, app):
562 self._categoryName = category
563 self._selectedIndex = 0
565 self._selectedUnitName = QtGui.QLabel()
566 self._selectedUnitValue = QtGui.QLineEdit()
567 self._selectedUnitValue.textEdited.connect(self._on_value_edited)
568 self._selectedUnitSymbol = QtGui.QLabel()
570 self._selectedUnitLayout = QtGui.QHBoxLayout()
571 self._selectedUnitLayout.addWidget(self._selectedUnitName)
572 self._selectedUnitLayout.addWidget(self._selectedUnitValue)
573 self._selectedUnitLayout.addWidget(self._selectedUnitSymbol)
575 self._unitsModel = UnitModel(self._categoryName)
576 self._unitsView = QtGui.QTreeView()
577 self._unitsView.setModel(self._unitsModel)
578 self._unitsView.clicked.connect(self._on_unit_clicked)
579 self._unitsView.setUniformRowHeights(True)
580 self._unitsView.header().setSortIndicatorShown(True)
581 self._unitsView.header().setClickable(True)
582 self._unitsView.setSortingEnabled(True)
583 self._unitsView.setAlternatingRowColors(True)
585 self._unitsView.setHeaderHidden(True)
587 self._layout = QtGui.QVBoxLayout()
588 self._layout.addLayout(self._selectedUnitLayout)
589 self._layout.addWidget(self._unitsView)
591 centralWidget = QtGui.QWidget()
592 centralWidget.setLayout(self._layout)
594 self._window = QtGui.QMainWindow(parent)
595 if parent is not None:
596 self._window.setWindowModality(QtCore.Qt.WindowModal)
597 self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
598 self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
599 self._window.setCentralWidget(centralWidget)
601 defaultUnitName = self._app.get_recent_unit(self._categoryName)
603 self.select_unit(defaultUnitName)
606 self._unitsModel.sort(1)
608 self._sortActionGroup = QtGui.QActionGroup(None)
609 self._sortByNameAction = QtGui.QAction(self._sortActionGroup)
610 self._sortByNameAction.setText("Sort By Name")
611 self._sortByNameAction.setStatusTip("Sort the units by name")
612 self._sortByNameAction.setToolTip("Sort the units by name")
613 self._sortByValueAction = QtGui.QAction(self._sortActionGroup)
614 self._sortByValueAction.setText("Sort By Value")
615 self._sortByValueAction.setStatusTip("Sort the units by value")
616 self._sortByValueAction.setToolTip("Sort the units by value")
617 self._sortByUnitAction = QtGui.QAction(self._sortActionGroup)
618 self._sortByUnitAction.setText("Sort By Unit")
619 self._sortByUnitAction.setStatusTip("Sort the units by unit")
620 self._sortByUnitAction.setToolTip("Sort the units by unit")
622 self._sortByValueAction.setChecked(True)
624 viewMenu = self._window.menuBar().addMenu("&View")
625 viewMenu.addAction(self._app.fullscreenAction)
626 viewMenu.addSeparator()
627 viewMenu.addAction(self._app.jumpAction)
628 viewMenu.addAction(self._app.recentAction)
629 viewMenu.addSeparator()
630 viewMenu.addAction(self._sortByNameAction)
631 viewMenu.addAction(self._sortByValueAction)
632 viewMenu.addAction(self._sortByUnitAction)
634 self._sortByNameAction.triggered.connect(self._on_sort_by_name)
635 self._sortByValueAction.triggered.connect(self._on_sort_by_value)
636 self._sortByUnitAction.triggered.connect(self._on_sort_by_unit)
643 def setFullscreen(self, isFullscreen):
645 self._window.showFullScreen()
647 self._window.showNormal()
649 def select_unit(self, unitName):
650 index = self._unitsModel.index_unit(unitName)
651 self._select_unit(index)
653 @misc_utils.log_exception(_moduleLogger)
654 def _on_sort_by_name(self, checked = False):
655 self._unitsModel.sort(0, QtCore.Qt.DescendingOrder)
657 @misc_utils.log_exception(_moduleLogger)
658 def _on_sort_by_value(self, checked = False):
659 self._unitsModel.sort(1)
661 @misc_utils.log_exception(_moduleLogger)
662 def _on_sort_by_unit(self, checked = False):
663 self._unitsModel.sort(3, QtCore.Qt.DescendingOrder)
665 @misc_utils.log_exception(_moduleLogger)
666 def _on_unit_clicked(self, index):
667 self._select_unit(index.row())
669 @misc_utils.log_exception(_moduleLogger)
670 def _on_value_edited(self, *args):
671 userInput = self._selectedUnitValue.text()
672 self._unitsModel.update_values(self._selectedIndex, str(userInput))
674 def _select_unit(self, index):
675 unit = self._unitsModel.get_unit(index)
676 self._selectedUnitName.setText(unit.name)
677 self._selectedUnitValue.setText(str(unit.value))
678 self._selectedUnitSymbol.setText(unit.unit)
680 self._selectedIndex = index
681 qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
682 self._unitsView.scrollTo(qindex)
683 self._app.add_recent(self._categoryName, self._unitsModel.get_unit(index).name)
687 app = QtGui.QApplication([])
692 if __name__ == "__main__":
693 logging.basicConfig(level = logging.DEBUG)
695 os.makedirs(constants._data_path_)