#!/usr/bin/env python
# -*- coding: UTF8 -*-
+#@todo Research Fn
+#@todo Research optimizations
+
from __future__ import with_statement
-import sys
import os
import math
import simplejson
import logging
+import logging.handlers
-from PyQt4 import QtGui
-from PyQt4 import QtCore
+import util.qt_compat as qt_compat
+QtCore = qt_compat.QtCore
+QtGui = qt_compat.import_module("QtGui")
import constants
-import maeqt
+from util import qui_utils
from util import misc as misc_utils
import unit_data
-_moduleLogger = logging.getLogger("gonvert_glade")
-
-
-IS_MAEMO = True
-
-
-def change_menu_label(widgets, labelname, newtext):
- item_label = widgets.get_widget(labelname).get_children()[0]
- item_label.set_text(newtext)
+_moduleLogger = logging.getLogger(__name__)
def split_number(number):
+ if number == 0.0:
+ # Optimize the startup case
+ return "0.", "0"
+
try:
fractional, integer = math.modf(number)
except TypeError:
if "e+" in integerDisplay:
integerDisplay = number
fractionalDisplay = ""
- elif "e-" in fractionalDisplay and 0.0 < integer:
- integerDisplay = number
- fractionalDisplay = ""
elif "e-" in fractionalDisplay:
- integerDisplay = ""
- fractionalDisplay = number
+ if 0.0 < integer:
+ integerDisplay = number
+ fractionalDisplay = ""
+ else:
+ integerDisplay = ""
+ fractionalDisplay = number
else:
- integerDisplay = integerDisplay.split(".", 1)[0] + "."
- fractionalDisplay = fractionalDisplay.rsplit(".", 1)[-1]
+ integerDisplay = integerDisplay[0:-2] + "."
+ fractionalDisplay = fractionalDisplay[2:]
return integerDisplay, fractionalDisplay
self._mainWindow.select_category(self._recent[-1][0])
def request_category(self):
- if self._mainWindow is not None:
- self._mainWindow.hide()
-
if self._condensedAction.isChecked():
+ if self._catWindow is not None:
+ self._catWindow.hide()
+
if self._quickWindow is None:
self._quickWindow = QuickConvert(None, self)
self._quickWindow.window.destroyed.connect(self._on_quick_close)
else:
self._quickWindow.show()
+
self._mainWindow = self._quickWindow
else:
+ if self._quickWindow is not None:
+ self._quickWindow.hide()
+
if self._catWindow is None:
self._catWindow = CategoryWindow(None, self)
self._catWindow.window.destroyed.connect(self._on_cat_close)
else:
self._catWindow.window.show()
+
self._mainWindow = self._catWindow
return self._mainWindow
def search_units(self):
- jumpWindow = QuickJump(None, self)
+ import windows
+ jumpWindow = windows.QuickJump(None, self)
jumpWindow.window.destroyed.connect(self._on_jump_close)
- self._fake_close_windows()
self._jumpWindow = jumpWindow
return self._jumpWindow
def show_recent(self):
- recentWindow = Recent(None, self)
+ import windows
+ recentWindow = windows.Recent(None, self)
recentWindow.window.destroyed.connect(self._on_recent_close)
- self._fake_close_windows()
self._recentWindow = recentWindow
return self._recentWindow
self._showFavoritesAction.setChecked(settings.get("showFavorites", True))
- self._condensedAction.setChecked(settings.get("useQuick", self._condensedAction.isChecked()))
+ self._condensedAction.setChecked(settings.get("useQuick", True))
def save_settings(self):
if self._sortByNameAction.isChecked():
if self._recentWindow is not None:
yield self._recentWindow
- def _fake_close_windows(self):
- if self._catWindow is not None:
- self._catWindow.hide()
- if self._quickWindow is not None:
- self._quickWindow.hide()
- if self._jumpWindow is not None:
- self._jumpWindow.window.destroyed.disconnect(self._on_jump_close)
- self._jumpWindow.close()
- self._jumpWindow = None
- if self._recentWindow is not None:
- self._recentWindow.window.destroyed.disconnect(self._on_recent_close)
- self._recentWindow.close()
- self._recentWindow = None
-
def _close_windows(self):
if self._catWindow is not None:
self._catWindow.window.destroyed.disconnect(self._on_cat_close)
self._close_windows()
-class QuickJump(object):
-
- MINIMAL_ENTRY = 3
-
- def __init__(self, parent, app):
- self._app = app
-
- self._searchLabel = QtGui.QLabel("Search:")
- self._searchEntry = QtGui.QLineEdit("")
- self._searchEntry.textEdited.connect(self._on_search_edited)
-
- self._entryLayout = QtGui.QHBoxLayout()
- self._entryLayout.addWidget(self._searchLabel)
- self._entryLayout.addWidget(self._searchEntry)
-
- self._resultsBox = QtGui.QTreeWidget()
- self._resultsBox.setHeaderLabels(["Categories", "Units"])
- self._resultsBox.setHeaderHidden(True)
- if not IS_MAEMO:
- self._resultsBox.setAlternatingRowColors(True)
- self._resultsBox.itemClicked.connect(self._on_result_clicked)
-
- self._layout = QtGui.QVBoxLayout()
- self._layout.addLayout(self._entryLayout)
- self._layout.addWidget(self._resultsBox)
-
- centralWidget = QtGui.QWidget()
- centralWidget.setLayout(self._layout)
-
- self._window = QtGui.QMainWindow(parent)
- self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
- maeqt.set_autorient(self._window, True)
- maeqt.set_stackable(self._window, True)
- self._window.setWindowTitle("%s - Quick Jump" % constants.__pretty_app_name__)
- self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
- self._window.setCentralWidget(centralWidget)
-
- self._closeWindowAction = QtGui.QAction(None)
- self._closeWindowAction.setText("Close")
- self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
- self._closeWindowAction.triggered.connect(self._on_close_window)
-
- if IS_MAEMO:
- self._window.addAction(self._closeWindowAction)
- self._window.addAction(self._app.quitAction)
- self._window.addAction(self._app.fullscreenAction)
- else:
- fileMenu = self._window.menuBar().addMenu("&Units")
- fileMenu.addAction(self._closeWindowAction)
- fileMenu.addAction(self._app.quitAction)
-
- viewMenu = self._window.menuBar().addMenu("&View")
- viewMenu.addAction(self._app.fullscreenAction)
-
- self._window.addAction(self._app.logAction)
-
- self.set_fullscreen(self._app.fullscreenAction.isChecked())
- self._window.show()
-
- @property
- def window(self):
- return self._window
-
- def show(self):
- self._window.show()
-
- def hide(self):
- self._window.hide()
-
- def close(self):
- self._window.close()
-
- def set_fullscreen(self, isFullscreen):
- if isFullscreen:
- self._window.showFullScreen()
- else:
- self._window.showNormal()
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_close_window(self, checked = True):
- self.close()
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_result_clicked(self, item, columnIndex):
- categoryName = unicode(item.text(0))
- unitName = unicode(item.text(1))
- catWindow = self._app.request_category()
- unitsWindow = catWindow.select_category(categoryName)
- unitsWindow.select_unit(unitName)
- self.close()
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_search_edited(self, *args):
- userInput = self._searchEntry.text()
- if len(userInput) < self.MINIMAL_ENTRY:
- return
-
- self._resultsBox.clear()
- lowerInput = str(userInput).lower()
- for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
- units = unit_data.get_units(category)
- for unitIndex, unit in enumerate(units):
- loweredUnit = unit.lower()
- if lowerInput in loweredUnit:
- twi = QtGui.QTreeWidgetItem(self._resultsBox)
- twi.setText(0, category)
- twi.setText(1, unit)
-
-
-class Recent(object):
-
- def __init__(self, parent, app):
- self._app = app
-
- self._resultsBox = QtGui.QTreeWidget()
- self._resultsBox.setHeaderLabels(["Categories", "Units"])
- self._resultsBox.setHeaderHidden(True)
- if not IS_MAEMO:
- self._resultsBox.setAlternatingRowColors(True)
- self._resultsBox.itemClicked.connect(self._on_result_clicked)
-
- self._layout = QtGui.QVBoxLayout()
- self._layout.addWidget(self._resultsBox)
-
- centralWidget = QtGui.QWidget()
- centralWidget.setLayout(self._layout)
-
- self._window = QtGui.QMainWindow(parent)
- self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
- maeqt.set_autorient(self._window, True)
- maeqt.set_stackable(self._window, True)
- self._window.setWindowTitle("%s - Recent" % constants.__pretty_app_name__)
- self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
- self._window.setCentralWidget(centralWidget)
-
- for cat, unit in self._app.get_recent():
- twi = QtGui.QTreeWidgetItem(self._resultsBox)
- twi.setText(0, cat)
- twi.setText(1, unit)
-
- self._closeWindowAction = QtGui.QAction(None)
- self._closeWindowAction.setText("Close")
- self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
- self._closeWindowAction.triggered.connect(self._on_close_window)
-
- if IS_MAEMO:
- self._window.addAction(self._closeWindowAction)
- self._window.addAction(self._app.quitAction)
- self._window.addAction(self._app.fullscreenAction)
- else:
- fileMenu = self._window.menuBar().addMenu("&Units")
- fileMenu.addAction(self._closeWindowAction)
- fileMenu.addAction(self._app.quitAction)
-
- viewMenu = self._window.menuBar().addMenu("&View")
- viewMenu.addAction(self._app.fullscreenAction)
-
- self._window.addAction(self._app.logAction)
-
- self.set_fullscreen(self._app.fullscreenAction.isChecked())
- self._window.show()
-
- @property
- def window(self):
- return self._window
-
- def show(self):
- self._window.show()
-
- def hide(self):
- self._window.hide()
-
- def close(self):
- self._window.close()
-
- def set_fullscreen(self, isFullscreen):
- if isFullscreen:
- self._window.showFullScreen()
- else:
- self._window.showNormal()
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_close_window(self, checked = True):
- self.close()
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_result_clicked(self, item, columnIndex):
- categoryName = unicode(item.text(0))
- unitName = unicode(item.text(1))
- catWindow = self._app.request_category()
- unitsWindow = catWindow.select_category(categoryName)
- unitsWindow.select_unit(unitName)
- self.close()
-
-
class QuickConvert(object):
def __init__(self, parent, app):
self._favoritesWindow = None
self._inputUnitValue = QtGui.QLineEdit()
- self._inputUnitValue.setInputMethodHints(QtCore.Qt.ImhPreferNumbers)
+ qui_utils.mark_numbers_preferred(self._inputUnitValue)
self._inputUnitValue.textEdited.connect(self._on_value_edited)
self._inputUnitSymbol = QtGui.QLabel()
- self._outputUnitValue = QtGui.QLabel()
+ self._outputUnitValue = QtGui.QLineEdit()
+ qui_utils.mark_numbers_preferred(self._outputUnitValue)
+ self._outputUnitValue.textEdited.connect(self._on_output_value_edited)
self._outputUnitSymbol = QtGui.QLabel()
self._conversionLayout = QtGui.QHBoxLayout()
self._categoryView = QtGui.QTreeWidget()
self._categoryView.setHeaderLabels(["Categories"])
self._categoryView.setHeaderHidden(False)
- if not IS_MAEMO:
+ self._categoryView.setRootIsDecorated(False)
+ if not constants.IS_MAEMO:
self._categoryView.setAlternatingRowColors(True)
self._categoryView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self._categoryView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self._inputView.setHeaderLabels(["From", "Name"])
self._inputView.setHeaderHidden(False)
self._inputView.header().hideSection(1)
- if not IS_MAEMO:
+ self._inputView.setRootIsDecorated(False)
+ if not constants.IS_MAEMO:
self._inputView.setAlternatingRowColors(True)
self._inputView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self._inputView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self._outputView.setHeaderLabels(["To", "Name"])
self._outputView.setHeaderHidden(False)
self._outputView.header().hideSection(1)
- if not IS_MAEMO:
+ self._outputView.setRootIsDecorated(False)
+ if not constants.IS_MAEMO:
self._outputView.setAlternatingRowColors(True)
self._outputView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self._outputView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self._window = QtGui.QMainWindow(parent)
self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
- maeqt.set_autorient(self._window, True)
- maeqt.set_stackable(self._window, True)
+ qui_utils.set_stackable(self._window, True)
self._window.setWindowTitle("%s - Quick Convert" % (constants.__pretty_app_name__, ))
self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
self._window.setCentralWidget(centralWidget)
self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
self._closeWindowAction.triggered.connect(self._on_close_window)
- if IS_MAEMO:
+ if constants.IS_MAEMO:
self._window.addAction(self._closeWindowAction)
self._window.addAction(self._app.quitAction)
self._window.addAction(self._app.fullscreenAction)
self._window.showNormal()
def select_category(self, categoryName):
+ self._select_category(categoryName)
+
+ i = unit_data.UNIT_CATEGORIES.index(categoryName)
+ rootIndex = self._categoryView.rootIndex()
+ currentIndex = self._categoryView.model().index(i, 0, rootIndex)
+ self._categoryView.scrollTo(currentIndex)
+ self._categoryView.setItemSelected(self._categoryView.topLevelItem(i), True)
+
+ return self
+
+ def select_unit(self, name):
+ self.select_input(name)
+ return self
+
+ def select_input(self, name):
+ self._select_input(name)
+
+ i = self._unitNames.index(name)
+ rootIndex = self._inputView.rootIndex()
+ currentIndex = self._inputView.model().index(i, 0, rootIndex)
+ self._inputView.scrollTo(currentIndex)
+ self._inputView.setItemSelected(self._inputView.topLevelItem(i), True)
+
+ def select_output(self, name):
+ self._select_output(name)
+
+ i = self._unitNames.index(name)
+ rootIndex = self._outputView.rootIndex()
+ currentIndex = self._outputView.model().index(i, 0, rootIndex)
+ self._outputView.scrollTo(currentIndex)
+ self._outputView.setItemSelected(self._outputView.topLevelItem(i), True)
+
+ def _select_category(self, categoryName):
self._inputUnitName = ""
self._outputUnitName = ""
self._inputUnitValue.setText("")
self._unitNames.sort()
for key in self._unitNames:
conversion, unit, description = unitData[key]
- if not unit:
- unit = key
+ unit = key
twi = QtGui.QTreeWidgetItem(self._inputView)
twi.setText(0, unit)
twi.setText(0, unit)
twi.setText(1, key)
- i = unit_data.UNIT_CATEGORIES.index(categoryName)
- rootIndex = self._categoryView.rootIndex()
- currentIndex = self._categoryView.model().index(i, 0, rootIndex)
- self._categoryView.scrollTo(currentIndex)
-
defaultInputUnitName = self._app.get_recent_unit(categoryName)
if defaultInputUnitName:
self.select_input(defaultInputUnitName)
assert defaultOutputUnitName
self.select_output(defaultOutputUnitName)
- return self
-
- def select_unit(self, name):
- self.select_input(name)
-
- def select_input(self, name):
+ def _select_input(self, name):
self._app.add_recent(self._categoryName, name)
self._inputUnitName = name
self._inputUnitSymbol.setText(unit if unit else name)
- i = self._unitNames.index(name)
- rootIndex = self._inputView.rootIndex()
- currentIndex = self._inputView.model().index(i, 0, rootIndex)
- self._inputView.scrollTo(currentIndex)
-
if "" not in [self._categoryName, self._inputUnitName, self._outputUnitName]:
- self._update_conversion()
+ self._update_output()
- def select_output(self, name):
+ def _select_output(self, name):
# Add the output to recent but don't make things weird by making it the most recent
self._app.add_recent(self._categoryName, name)
self._app.add_recent(self._categoryName, self._inputUnitName)
self._outputUnitSymbol.setText(unit if unit else name)
- i = self._unitNames.index(name)
- rootIndex = self._outputView.rootIndex()
- currentIndex = self._outputView.model().index(i, 0, rootIndex)
- self._outputView.scrollTo(currentIndex)
-
if "" not in [self._categoryName, self._inputUnitName, self._outputUnitName]:
- self._update_conversion()
+ self._update_output()
def _sanitize_value(self, userEntry):
if self._categoryName == "Computer Numbers":
value = float(userEntry)
return value
- def _update_conversion(self):
+ def _update_output(self):
assert self._categoryName
assert self._inputUnitName
assert self._outputUnitName
newValue = func.from_base(base, arg)
self._outputUnitValue.setText(str(newValue))
+ def _update_input(self):
+ assert self._categoryName
+ assert self._inputUnitName
+ assert self._outputUnitName
+
+ userOutput = str(self._outputUnitValue.text())
+ value = self._sanitize_value(userOutput)
+
+ unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
+ inputConversion, _, _ = unitData[self._inputUnitName]
+ outputConversion, _, _ = unitData[self._outputUnitName]
+
+ func, arg = outputConversion
+ base = func.to_base(value, arg)
+
+ func, arg = inputConversion
+ newValue = func.from_base(base, arg)
+ self._inputUnitValue.setText(str(newValue))
+
def _update_favorites(self):
if self._app.showFavoritesAction.isChecked():
assert self._categoryView.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
@misc_utils.log_exception(_moduleLogger)
def _on_choose_category_favorites(self, obj = None):
assert self._favoritesWindow is None
- self._favoritesWindow = FavoritesWindow(
+ import windows
+ self._favoritesWindow = windows.FavoritesWindow(
self._window,
self._app,
unit_data.UNIT_CATEGORIES,
@misc_utils.log_exception(_moduleLogger)
def _on_choose_unit_favorites(self, obj = None):
assert self._favoritesWindow is None
- self._favoritesWindow = FavoritesWindow(
+ import windows
+ self._favoritesWindow = windows.FavoritesWindow(
self._window,
self._app,
unit_data.get_units(self._categoryName),
@misc_utils.log_exception(_moduleLogger)
def _on_value_edited(self, *args):
- self._update_conversion()
+ self._update_output()
+
+ @misc_utils.log_exception(_moduleLogger)
+ def _on_output_value_edited(self, *args):
+ self._update_input()
@misc_utils.log_exception(_moduleLogger)
def _on_category_selection_changed(self, selected, deselected):
for item in self._categoryView.selectedItems()
]
assert len(selectedNames) == 1
- self.select_category(selectedNames[0])
+ self._select_category(selectedNames[0])
@misc_utils.log_exception(_moduleLogger)
def _on_input_selection_changed(self, selected, deselected):
if selectedNames:
assert len(selectedNames) == 1
name = selectedNames[0]
- self.select_input(name)
+ self._select_input(name)
else:
pass
for item in self._outputView.selectedItems()
]
if selectedNames:
- assert len(selectedNames) == 1
+ assert len(selectedNames) == 1, selectedNames
name = selectedNames[0]
- self.select_output(name)
+ self._select_output(name)
else:
pass
-class FavoritesWindow(object):
-
- def __init__(self, parent, app, source, hidden):
- self._app = app
- self._source = list(source)
- self._hidden = hidden
-
- self._categories = QtGui.QTreeWidget()
- self._categories.setHeaderLabels(["Categories"])
- self._categories.setHeaderHidden(True)
- if not IS_MAEMO:
- self._categories.setAlternatingRowColors(True)
- self._categories.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
- self._categories.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
- self._childWidgets = []
- for catName in self._source:
- twi = QtGui.QTreeWidgetItem(self._categories)
- twi.setText(0, catName)
- self._childWidgets.append(twi)
- if catName not in self._hidden:
- self._categories.setItemSelected(twi, True)
- self._selection = self._categories.selectionModel()
- self._selection.selectionChanged.connect(self._on_selection_changed)
-
- self._allButton = QtGui.QPushButton("All")
- self._allButton.clicked.connect(self._on_select_all)
- self._invertButton = QtGui.QPushButton("Invert")
- self._invertButton.clicked.connect(self._on_invert_selection)
- self._noneButton = QtGui.QPushButton("None")
- self._noneButton.clicked.connect(self._on_select_none)
-
- self._buttonLayout = QtGui.QHBoxLayout()
- self._buttonLayout.addWidget(self._allButton)
- self._buttonLayout.addWidget(self._invertButton)
- self._buttonLayout.addWidget(self._noneButton)
-
- self._layout = QtGui.QVBoxLayout()
- self._layout.addWidget(self._categories)
- self._layout.addLayout(self._buttonLayout)
-
- centralWidget = QtGui.QWidget()
- centralWidget.setLayout(self._layout)
-
- self._window = QtGui.QMainWindow(parent)
- self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
- maeqt.set_autorient(self._window, True)
- maeqt.set_stackable(self._window, True)
- self._window.setWindowTitle("%s - Favorites" % constants.__pretty_app_name__)
- self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
- self._window.setCentralWidget(centralWidget)
-
- self._closeWindowAction = QtGui.QAction(None)
- self._closeWindowAction.setText("Close")
- self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
- self._closeWindowAction.triggered.connect(self._on_close_window)
-
- if IS_MAEMO:
- self._window.addAction(self._closeWindowAction)
- self._window.addAction(self._app.quitAction)
- self._window.addAction(self._app.fullscreenAction)
- else:
- fileMenu = self._window.menuBar().addMenu("&Units")
- fileMenu.addAction(self._closeWindowAction)
- fileMenu.addAction(self._app.quitAction)
-
- viewMenu = self._window.menuBar().addMenu("&View")
- viewMenu.addAction(self._app.fullscreenAction)
-
- self._window.addAction(self._app.logAction)
-
- self.set_fullscreen(self._app.fullscreenAction.isChecked())
- self._window.show()
-
- @property
- def window(self):
- return self._window
-
- def show(self):
- self._window.show()
-
- def hide(self):
- self._window.hide()
-
- def close(self):
- self._window.close()
-
- def set_fullscreen(self, isFullscreen):
- if isFullscreen:
- self._window.showFullScreen()
- else:
- self._window.showNormal()
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_select_all(self, checked = False):
- for child in self._childWidgets:
- self._categories.setItemSelected(child, True)
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_invert_selection(self, checked = False):
- for child in self._childWidgets:
- isSelected = self._categories.isItemSelected(child)
- self._categories.setItemSelected(child, not isSelected)
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_select_none(self, checked = False):
- for child in self._childWidgets:
- self._categories.setItemSelected(child, False)
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_selection_changed(self, selected, deselected):
- self._hidden.clear()
- selectedNames = set(
- str(item.text(0))
- for item in self._categories.selectedItems()
- )
- for name in self._source:
- if name not in selectedNames:
- self._hidden.add(name)
-
- @misc_utils.log_exception(_moduleLogger)
- def _on_close_window(self, checked = True):
- self.close()
-
-
class CategoryWindow(object):
def __init__(self, parent, app):
self._categories.setHeaderLabels(["Categories"])
self._categories.itemClicked.connect(self._on_category_clicked)
self._categories.setHeaderHidden(True)
+ self._categories.setRootIsDecorated(False)
self._categories.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self._categories.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
- if not IS_MAEMO:
+ if not constants.IS_MAEMO:
self._categories.setAlternatingRowColors(True)
for catName in unit_data.UNIT_CATEGORIES:
twi = QtGui.QTreeWidgetItem(self._categories)
self._window = QtGui.QMainWindow(parent)
self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
- maeqt.set_autorient(self._window, True)
- maeqt.set_stackable(self._window, True)
+ qui_utils.set_stackable(self._window, True)
self._window.setWindowTitle("%s - Categories" % constants.__pretty_app_name__)
self._window.setWindowIcon(QtGui.QIcon(self._app.appIconPath))
self._window.setCentralWidget(centralWidget)
self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
self._closeWindowAction.triggered.connect(self._on_close_window)
- if IS_MAEMO:
+ if constants.IS_MAEMO:
fileMenu = self._window.menuBar().addMenu("&Units")
fileMenu.addAction(self._chooseFavoritesAction)
self._window.close()
def select_category(self, categoryName):
- for child in self.walk_children():
- child.window.destroyed.disconnect(self._on_child_close)
- child.close()
- self._unitWindow = UnitWindow(self._window, categoryName, self._app)
- self._unitWindow.window.destroyed.connect(self._on_child_close)
+ self._select_category(categoryName)
i = unit_data.UNIT_CATEGORIES.index(categoryName)
rootIndex = self._categories.rootIndex()
currentIndex = self._categories.model().index(i, 0, rootIndex)
self._categories.scrollTo(currentIndex)
+ self._categories.setItemSelected(self._categories.topLevelItem(i), True)
return self._unitWindow
def set_fullscreen(self, isFullscreen):
for child in self.walk_children():
child.set_fullscreen(isFullscreen)
+ def _select_category(self, categoryName):
+ for child in self.walk_children():
+ child.window.destroyed.disconnect(self._on_child_close)
+ child.close()
+ self._unitWindow = UnitWindow(self._window, categoryName, self._app)
+ self._unitWindow.window.destroyed.connect(self._on_child_close)
+
def _update_favorites(self):
if self._app.showFavoritesAction.isChecked():
assert self._categories.topLevelItemCount() == len(unit_data.UNIT_CATEGORIES)
@misc_utils.log_exception(_moduleLogger)
def _on_choose_favorites(self, obj = None):
assert self._favoritesWindow is None
- self._favoritesWindow = FavoritesWindow(
+ import windows
+ self._favoritesWindow = windows.FavoritesWindow(
self._window,
self._app,
unit_data.UNIT_CATEGORIES,
VALUE_COLUMN_1 = 2
UNIT_COLUMN = 3
+ __slots__ = [
+ "_name", "_unit", "_description", "_conversion",
+ "_value", "_integerDisplay", "_fractionalDisplay",
+ ]
+
def __init__(self, name, unit, description, conversion):
self._name = name
self._unit = unit
super(UnitModel, self).__init__(parent)
self._categoryName = categoryName
self._unitData = unit_data.UNIT_DESCRIPTIONS[self._categoryName]
+ if self._categoryName == "Computer Numbers":
+ self._sanitize_value = self._sanitize_alpha_value
+ else:
+ self._sanitize_value = self._sanitize_numeric_value
self._children = []
for key in unit_data.get_units(self._categoryName):
@misc_utils.log_exception(_moduleLogger)
def data(self, index, role):
- if not index.isValid():
- return None
+ #if not index.isValid():
+ # return None
+
+ if role == QtCore.Qt.DisplayRole:
+ item = index.internalPointer()
+ if isinstance(item, UnitData):
+ return item.data(index.column())
+ elif item is UnitData.HEADERS:
+ return item[index.column()]
elif role == QtCore.Qt.TextAlignmentRole:
return UnitData.ALIGNMENT[index.column()]
- elif role != QtCore.Qt.DisplayRole:
+ else:
return None
- item = index.internalPointer()
- if isinstance(item, UnitData):
- return item.data(index.column())
- elif item is UnitData.HEADERS:
- return item[index.column()]
-
@misc_utils.log_exception(_moduleLogger)
def sort(self, column, order = QtCore.Qt.AscendingOrder):
self._sortSettings = column, order
@misc_utils.log_exception(_moduleLogger)
def index(self, row, column, parent):
- if not self.hasIndex(row, column, parent):
- return QtCore.QModelIndex()
-
- if parent.isValid():
- return QtCore.QModelIndex()
+ #if not self.hasIndex(row, column, parent):
+ # return QtCore.QModelIndex()
+ #elif parent.isValid():
+ # return QtCore.QModelIndex()
parentItem = UnitData.HEADERS
childItem = self._children[row]
func, arg = self._children[fromIndex].conversion
base = func.to_base(value, arg)
for i, child in enumerate(self._children):
- if i == fromIndex:
- continue
func, arg = child.conversion
newValue = func.from_base(base, arg)
child.update_value(newValue)
):
# Sort takes care of marking everything as changed
self.sort(*self._sortSettings)
+ return True
else:
self._values_changed()
+ return False
def __len__(self):
return len(self._children)
bottomRight = self.createIndex(len(self._children)-1, len(UnitData.HEADERS)-1, self._children[-1])
self.dataChanged.emit(topLeft, bottomRight)
- def _sanitize_value(self, userEntry):
- if self._categoryName == "Computer Numbers":
- if userEntry == '':
- value = '0'
- else:
- value = userEntry
+ def _sanitize_alpha_value(self, userEntry):
+ if userEntry:
+ value = userEntry
else:
- if userEntry == '':
- value = 0.0
- else:
- value = float(userEntry)
+ value = '0'
+ return value
+
+ def _sanitize_numeric_value(self, userEntry):
+ if userEntry:
+ value = float(userEntry)
+ else:
+ value = 0.0
return value
self._selectedUnitName = QtGui.QLabel()
self._selectedUnitValue = QtGui.QLineEdit()
self._selectedUnitValue.textEdited.connect(self._on_value_edited)
- maeqt.mark_numbers_preferred(self._selectedUnitValue)
+ qui_utils.mark_numbers_preferred(self._selectedUnitValue)
self._selectedUnitSymbol = QtGui.QLabel()
+ self._updateDelayTimer = QtCore.QTimer()
+ self._updateDelayTimer.setInterval(100)
+ self._updateDelayTimer.setSingleShot(True)
+ self._updateDelayTimer.timeout.connect(self._on_value_edited_delayed)
self._selectedUnitLayout = QtGui.QHBoxLayout()
self._selectedUnitLayout.addWidget(self._selectedUnitName)
self._unitsModel = UnitModel(self._categoryName)
self._unitsView = QtGui.QTreeView()
self._unitsView.setModel(self._unitsModel)
- self._unitsView.clicked.connect(self._on_unit_clicked)
self._unitsView.setUniformRowHeights(True)
self._unitsView.setSortingEnabled(True)
- self._unitsView.setTextElideMode(QtCore.Qt.ElideNone)
+ self._unitsView.setRootIsDecorated(False)
self._unitsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self._unitsView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self._unitsView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
- if not IS_MAEMO:
+ self._unitsView.setHeaderHidden(True)
+ self._unitsView.clicked.connect(self._on_unit_clicked)
+ if not constants.IS_MAEMO:
self._unitsView.setAlternatingRowColors(True)
- if True:
- self._unitsView.setHeaderHidden(True)
viewHeader = self._unitsView.header()
viewHeader.setSortIndicatorShown(True)
viewHeader.setStretchLastSection(False)
# Trying to make things faster by locking in the initial size of the immutable columns
- nameSize = min(viewHeader.sectionSize(UnitData.NAME_COLUMN), 125)
+ nameSize = min(viewHeader.sectionSize(UnitData.NAME_COLUMN), 300)
viewHeader.setResizeMode(UnitData.NAME_COLUMN, QtGui.QHeaderView.Fixed)
viewHeader.resizeSection(UnitData.NAME_COLUMN, nameSize)
- unitSize = min(viewHeader.sectionSize(UnitData.UNIT_COLUMN), 125)
+ unitSize = min(viewHeader.sectionSize(UnitData.UNIT_COLUMN), 150)
viewHeader.setResizeMode(UnitData.UNIT_COLUMN, QtGui.QHeaderView.Fixed)
viewHeader.resizeSection(UnitData.UNIT_COLUMN, unitSize)
self._window = QtGui.QMainWindow(parent)
self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
- maeqt.set_autorient(self._window, True)
- maeqt.set_stackable(self._window, True)
+ qui_utils.set_stackable(self._window, True)
self._window.setWindowTitle("%s - %s" % (constants.__pretty_app_name__, category))
self._window.setWindowIcon(QtGui.QIcon(app.appIconPath))
self._window.setCentralWidget(centralWidget)
self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
self._closeWindowAction.triggered.connect(self._on_close_window)
- if IS_MAEMO:
+ if constants.IS_MAEMO:
self._window.addAction(self._closeWindowAction)
self._window.addAction(self._app.quitAction)
self._window.addAction(self._app.fullscreenAction)
index = self._unitsModel.index_unit(unitName)
self._select_unit(index)
+ qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
+ self._unitsView.scrollTo(qindex)
+
def walk_children(self):
if self._favoritesWindow is not None:
yield self._favoritesWindow
+ def _select_unit(self, index):
+ unit = self._unitsModel.get_unit(index)
+ self._selectedUnitName.setText(unit.name)
+ self._selectedUnitValue.setText(str(unit.value))
+ self._selectedUnitSymbol.setText(unit.unit)
+
+ self._selectedIndex = index
+ self._app.add_recent(self._categoryName, self._unitsModel.get_unit(index).name)
+
def _update_favorites(self, force = False):
if self._app.showFavoritesAction.isChecked():
unitNames = list(self._unitsModel.get_unit_names())
+ hiddenUnits = self._app.get_hidden_units(self._categoryName)
for i, unitName in enumerate(unitNames):
- if unitName in self._app.get_hidden_units(self._categoryName):
+ if unitName in hiddenUnits:
self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), True)
else:
self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), False)
def _on_show_favorites(self, checked = True):
if checked:
unitNames = list(self._unitsModel.get_unit_names())
+ hiddenUnits = self._app.get_hidden_units(self._categoryName)
for i, unitName in enumerate(unitNames):
- if unitName in self._app.get_hidden_units(self._categoryName):
+ if unitName in hiddenUnits:
self._unitsView.setRowHidden(i, self._unitsView.rootIndex(), True)
else:
for i in xrange(len(self._unitsModel)):
@misc_utils.log_exception(_moduleLogger)
def _on_choose_favorites(self, obj = None):
assert self._favoritesWindow is None
- self._favoritesWindow = FavoritesWindow(
+ import windows
+ self._favoritesWindow = windows.FavoritesWindow(
self._window,
self._app,
unit_data.get_units(self._categoryName),
@misc_utils.log_exception(_moduleLogger)
def _on_previous_unit(self, checked = True):
- self._select_unit(self._selectedIndex - 1)
+ index = self._selectedIndex - 1
+ unitData = self._unitsModel.get_unit(index)
+ unitName = unitData.name
+
+ if self._app.showFavoritesAction.isChecked():
+ hiddenUnits = self._app.get_hidden_units(self._categoryName)
+ while unitName in hiddenUnits:
+ index -= 1
+ unitData = self._unitsModel.get_unit(index)
+ unitName = unitData.name
+
+ self.select_unit(unitName)
@misc_utils.log_exception(_moduleLogger)
def _on_next_unit(self, checked = True):
- self._select_unit(self._selectedIndex + 1)
+ index = self._selectedIndex + 1
+ unitData = self._unitsModel.get_unit(index)
+ unitName = unitData.name
+
+ if self._app.showFavoritesAction.isChecked():
+ hiddenUnits = self._app.get_hidden_units(self._categoryName)
+ while unitName in hiddenUnits:
+ index += 1
+ unitData = self._unitsModel.get_unit(index)
+ unitName = unitData.name
+
+ self.select_unit(unitName)
@misc_utils.log_exception(_moduleLogger)
def _on_close_window(self, checked = True):
@misc_utils.log_exception(_moduleLogger)
def _on_value_edited(self, *args):
- userInput = self._selectedUnitValue.text()
- self._unitsModel.update_values(self._selectedIndex, str(userInput))
- self._update_favorites()
-
- def _select_unit(self, index):
- unit = self._unitsModel.get_unit(index)
- self._selectedUnitName.setText(unit.name)
- self._selectedUnitValue.setText(str(unit.value))
- self._selectedUnitSymbol.setText(unit.unit)
+ if not self._updateDelayTimer.isActive():
+ self._updateDelayTimer.start()
- self._selectedIndex = index
- qindex = self._unitsModel.createIndex(index, 0, self._unitsModel.get_unit(index))
- self._unitsView.scrollTo(qindex)
- self._app.add_recent(self._categoryName, self._unitsModel.get_unit(index).name)
+ @misc_utils.log_exception(_moduleLogger)
+ def _on_value_edited_delayed(self, *args):
+ userInput = str(self._selectedUnitValue.text())
+ orderChanged = self._unitsModel.update_values(self._selectedIndex, userInput)
+ if orderChanged:
+ self._update_favorites()
def run_gonvert():
- app = QtGui.QApplication([])
- handle = Gonvert(app)
- return app.exec_()
-
-
-if __name__ == "__main__":
- logging.basicConfig(level = logging.DEBUG)
try:
os.makedirs(constants._data_path_)
except OSError, e:
if e.errno != 17:
raise
+ logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
+ logging.basicConfig(level=logging.DEBUG, format=logFormat)
+ rotating = logging.handlers.RotatingFileHandler(constants._user_logpath_, maxBytes=512*1024, backupCount=1)
+ rotating.setFormatter(logging.Formatter(logFormat))
+ root = logging.getLogger()
+ root.addHandler(rotating)
+ _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
+ _moduleLogger.info("OS: %s" % (os.uname()[0], ))
+ _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
+ _moduleLogger.info("Hostname: %s" % os.uname()[1])
+
+ app = QtGui.QApplication([])
+ handle = Gonvert(app)
+ if constants.PROFILE_STARTUP:
+ return 0
+ else:
+ return app.exec_()
+
+
+if __name__ == "__main__":
+ import sys
val = run_gonvert()
sys.exit(val)