repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
titusjan/argos | argos/repo/rtiplugins/pandasio.py | PandasDataFrameRti._fetchAllChildren | def _fetchAllChildren(self):
""" Fetches children items.
If this is stand-alone DataFrame the index, column etc are added as PandasIndexRti obj.
"""
assert self.isSliceable, "No underlying pandas object: self._ndFrame is None"
childItems = []
for subName in self._ndFrame.columns: # Note that this is not the first dimension!
childItem = PandasSeriesRti(self._ndFrame[subName], nodeName=subName,
fileName=self.fileName, iconColor=self._iconColor,
standAlone=False)
childItems.append(childItem)
if self._standAlone:
childItems.append(self._createIndexRti(self._ndFrame.index, 'index'))
childItems.append(self._createIndexRti(self._ndFrame.columns, 'columns'))
return childItems | python | def _fetchAllChildren(self):
""" Fetches children items.
If this is stand-alone DataFrame the index, column etc are added as PandasIndexRti obj.
"""
assert self.isSliceable, "No underlying pandas object: self._ndFrame is None"
childItems = []
for subName in self._ndFrame.columns: # Note that this is not the first dimension!
childItem = PandasSeriesRti(self._ndFrame[subName], nodeName=subName,
fileName=self.fileName, iconColor=self._iconColor,
standAlone=False)
childItems.append(childItem)
if self._standAlone:
childItems.append(self._createIndexRti(self._ndFrame.index, 'index'))
childItems.append(self._createIndexRti(self._ndFrame.columns, 'columns'))
return childItems | Fetches children items.
If this is stand-alone DataFrame the index, column etc are added as PandasIndexRti obj. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/pandasio.py#L265-L284 |
titusjan/argos | argos/repo/rtiplugins/pandasio.py | PandasPanelRti._fetchAllChildren | def _fetchAllChildren(self):
""" Fetches children items.
If this is stand-alone Panel the index, column etc are added as PandasIndexRti obj.
"""
assert self.isSliceable, "No underlying pandas object: self._ndFrame is None"
childItems = []
for subName in self._ndFrame.items:
childItem = PandasDataFrameRti(self._ndFrame[subName], nodeName=subName,
fileName=self.fileName, iconColor=self._iconColor,
standAlone=False)
childItems.append(childItem)
if self._standAlone:
childItems.append(self._createIndexRti(self._ndFrame.items, 'items'))
childItems.append(self._createIndexRti(self._ndFrame.major_axis, 'major_axis'))
childItems.append(self._createIndexRti(self._ndFrame.minor_axis, 'minor_axis'))
return childItems | python | def _fetchAllChildren(self):
""" Fetches children items.
If this is stand-alone Panel the index, column etc are added as PandasIndexRti obj.
"""
assert self.isSliceable, "No underlying pandas object: self._ndFrame is None"
childItems = []
for subName in self._ndFrame.items:
childItem = PandasDataFrameRti(self._ndFrame[subName], nodeName=subName,
fileName=self.fileName, iconColor=self._iconColor,
standAlone=False)
childItems.append(childItem)
if self._standAlone:
childItems.append(self._createIndexRti(self._ndFrame.items, 'items'))
childItems.append(self._createIndexRti(self._ndFrame.major_axis, 'major_axis'))
childItems.append(self._createIndexRti(self._ndFrame.minor_axis, 'minor_axis'))
return childItems | Fetches children items.
If this is stand-alone Panel the index, column etc are added as PandasIndexRti obj. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/pandasio.py#L307-L327 |
titusjan/argos | argos/inspector/dialog.py | OpenInspectorDialog.setCurrentInspectorRegItem | def setCurrentInspectorRegItem(self, regItem):
""" Sets the current inspector given an InspectorRegItem
"""
check_class(regItem, InspectorRegItem, allow_none=True)
self.inspectorTab.setCurrentRegItem(regItem) | python | def setCurrentInspectorRegItem(self, regItem):
""" Sets the current inspector given an InspectorRegItem
"""
check_class(regItem, InspectorRegItem, allow_none=True)
self.inspectorTab.setCurrentRegItem(regItem) | Sets the current inspector given an InspectorRegItem | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/dialog.py#L85-L89 |
titusjan/argos | argos/config/groupcti.py | GroupCti.createEditor | def createEditor(self, delegate, parent, _option):
""" Creates a hidden widget so that only the reset button is visible during editing.
:type option: QStyleOptionViewItem
"""
return GroupCtiEditor(self, delegate, parent=parent) | python | def createEditor(self, delegate, parent, _option):
""" Creates a hidden widget so that only the reset button is visible during editing.
:type option: QStyleOptionViewItem
"""
return GroupCtiEditor(self, delegate, parent=parent) | Creates a hidden widget so that only the reset button is visible during editing.
:type option: QStyleOptionViewItem | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/groupcti.py#L52-L56 |
titusjan/argos | argos/utils/misc.py | log_dictionary | def log_dictionary(dictionary, msg='', logger=None, level='debug', item_prefix=' '):
""" Writes a log message with key and value for each item in the dictionary.
:param dictionary: the dictionary to be logged
:type dictionary: dict
:param name: An optional message that is logged before the contents
:type name: string
:param logger: A logging.Logger object to log to. If not set, the 'main' logger is used.
:type logger: logging.Logger or a string
:param level: log level. String or int as described in the logging module documentation.
Default: 'debug'.
:type level: string or int
:param item_prefix: String that will be prefixed to each line. Default: two spaces.
:type item_prefix: string
"""
level_nr = logging.getLevelName(level.upper())
if logger is None:
logger = logging.getLogger('main')
if msg :
logger.log(level_nr, "Logging dictionary: {}".format(msg))
if not dictionary:
logger.log(level_nr,"{}<empty dictionary>".format(item_prefix))
return
max_key_len = max([len(k) for k in dictionary.keys()])
for key, value in sorted(dictionary.items()):
logger.log(level_nr, "{0}{1:<{2}s} = {3}".format(item_prefix, key, max_key_len, value)) | python | def log_dictionary(dictionary, msg='', logger=None, level='debug', item_prefix=' '):
""" Writes a log message with key and value for each item in the dictionary.
:param dictionary: the dictionary to be logged
:type dictionary: dict
:param name: An optional message that is logged before the contents
:type name: string
:param logger: A logging.Logger object to log to. If not set, the 'main' logger is used.
:type logger: logging.Logger or a string
:param level: log level. String or int as described in the logging module documentation.
Default: 'debug'.
:type level: string or int
:param item_prefix: String that will be prefixed to each line. Default: two spaces.
:type item_prefix: string
"""
level_nr = logging.getLevelName(level.upper())
if logger is None:
logger = logging.getLogger('main')
if msg :
logger.log(level_nr, "Logging dictionary: {}".format(msg))
if not dictionary:
logger.log(level_nr,"{}<empty dictionary>".format(item_prefix))
return
max_key_len = max([len(k) for k in dictionary.keys()])
for key, value in sorted(dictionary.items()):
logger.log(level_nr, "{0}{1:<{2}s} = {3}".format(item_prefix, key, max_key_len, value)) | Writes a log message with key and value for each item in the dictionary.
:param dictionary: the dictionary to be logged
:type dictionary: dict
:param name: An optional message that is logged before the contents
:type name: string
:param logger: A logging.Logger object to log to. If not set, the 'main' logger is used.
:type logger: logging.Logger or a string
:param level: log level. String or int as described in the logging module documentation.
Default: 'debug'.
:type level: string or int
:param item_prefix: String that will be prefixed to each line. Default: two spaces.
:type item_prefix: string | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/misc.py#L60-L90 |
titusjan/argos | argos/utils/misc.py | is_quoted | def is_quoted(s):
""" Returns True if the string begins and ends with quotes (single or double)
:param s: a string
:return: boolean
"""
return (s.startswith("'") and s.endswith("'")) or (s.startswith('"') and s.endswith('"')) | python | def is_quoted(s):
""" Returns True if the string begins and ends with quotes (single or double)
:param s: a string
:return: boolean
"""
return (s.startswith("'") and s.endswith("'")) or (s.startswith('"') and s.endswith('"')) | Returns True if the string begins and ends with quotes (single or double)
:param s: a string
:return: boolean | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/misc.py#L103-L109 |
titusjan/argos | argos/utils/misc.py | string_to_identifier | def string_to_identifier(s, white_space_becomes='_'):
""" Takes a string and makes it suitable for use as an identifier
Translates to lower case
Replaces white space by the white_space_becomes character (default=underscore).
Removes and punctuation.
"""
import re
s = s.lower()
s = re.sub(r"\s+", white_space_becomes, s) # replace whitespace with underscores
s = re.sub(r"-", "_", s) # replace hyphens with underscores
s = re.sub(r"[^A-Za-z0-9_]", "", s) # remove everything that's not a character, a digit or a _
return s | python | def string_to_identifier(s, white_space_becomes='_'):
""" Takes a string and makes it suitable for use as an identifier
Translates to lower case
Replaces white space by the white_space_becomes character (default=underscore).
Removes and punctuation.
"""
import re
s = s.lower()
s = re.sub(r"\s+", white_space_becomes, s) # replace whitespace with underscores
s = re.sub(r"-", "_", s) # replace hyphens with underscores
s = re.sub(r"[^A-Za-z0-9_]", "", s) # remove everything that's not a character, a digit or a _
return s | Takes a string and makes it suitable for use as an identifier
Translates to lower case
Replaces white space by the white_space_becomes character (default=underscore).
Removes and punctuation. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/misc.py#L113-L125 |
titusjan/argos | argos/repo/iconfactory.py | RtiIconFactory.registerIcon | def registerIcon(self, fileName, glyph, isOpen=None):
""" Register an icon SVG file given a glyph, and optionally the open/close state.
:param fileName: filename to the SVG file.
If the filename is a relative path, the ICONS_DIRECTORY will be prepended.
:param glyph: a string describing the glyph (e.g. 'file', 'array')
:param isOpen: boolean that indicates if the RTI is open or closed.
If None, the icon will be registered for open is both True and False
:return: QIcon
"""
check_class(isOpen, bool, allow_none=True)
if fileName and not os.path.isabs(fileName):
fileName = os.path.join(self.ICONS_DIRECTORY, fileName)
if isOpen is None:
# Register both opened and closed variants
self._registry[(glyph, True)] = fileName
self._registry[(glyph, False)] = fileName
else:
self._registry[(glyph, isOpen)] = fileName | python | def registerIcon(self, fileName, glyph, isOpen=None):
""" Register an icon SVG file given a glyph, and optionally the open/close state.
:param fileName: filename to the SVG file.
If the filename is a relative path, the ICONS_DIRECTORY will be prepended.
:param glyph: a string describing the glyph (e.g. 'file', 'array')
:param isOpen: boolean that indicates if the RTI is open or closed.
If None, the icon will be registered for open is both True and False
:return: QIcon
"""
check_class(isOpen, bool, allow_none=True)
if fileName and not os.path.isabs(fileName):
fileName = os.path.join(self.ICONS_DIRECTORY, fileName)
if isOpen is None:
# Register both opened and closed variants
self._registry[(glyph, True)] = fileName
self._registry[(glyph, False)] = fileName
else:
self._registry[(glyph, isOpen)] = fileName | Register an icon SVG file given a glyph, and optionally the open/close state.
:param fileName: filename to the SVG file.
If the filename is a relative path, the ICONS_DIRECTORY will be prepended.
:param glyph: a string describing the glyph (e.g. 'file', 'array')
:param isOpen: boolean that indicates if the RTI is open or closed.
If None, the icon will be registered for open is both True and False
:return: QIcon | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/iconfactory.py#L102-L122 |
titusjan/argos | argos/repo/iconfactory.py | RtiIconFactory.getIcon | def getIcon(self, glyph, isOpen, color=None):
""" Returns a QIcon given a glyph name, open/closed state and color.
The reslulting icon is cached so that it only needs to be rendered once.
:param glyph: name of a registered glyph (e.g. 'file', 'array')
:param isOpen: boolean that indicates if the RTI is open or closed.
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:return: QtGui.QIcon
"""
try:
fileName = self._registry[(glyph, isOpen)]
except KeyError:
logger.warn("Unregistered icon glyph: {} (open={})".format(glyph, isOpen))
from argos.utils.misc import log_dictionary
log_dictionary(self._registry, "registry", logger=logger)
raise
return self.loadIcon(fileName, color=color) | python | def getIcon(self, glyph, isOpen, color=None):
""" Returns a QIcon given a glyph name, open/closed state and color.
The reslulting icon is cached so that it only needs to be rendered once.
:param glyph: name of a registered glyph (e.g. 'file', 'array')
:param isOpen: boolean that indicates if the RTI is open or closed.
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:return: QtGui.QIcon
"""
try:
fileName = self._registry[(glyph, isOpen)]
except KeyError:
logger.warn("Unregistered icon glyph: {} (open={})".format(glyph, isOpen))
from argos.utils.misc import log_dictionary
log_dictionary(self._registry, "registry", logger=logger)
raise
return self.loadIcon(fileName, color=color) | Returns a QIcon given a glyph name, open/closed state and color.
The reslulting icon is cached so that it only needs to be rendered once.
:param glyph: name of a registered glyph (e.g. 'file', 'array')
:param isOpen: boolean that indicates if the RTI is open or closed.
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:return: QtGui.QIcon | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/iconfactory.py#L125-L143 |
titusjan/argos | argos/repo/iconfactory.py | RtiIconFactory.loadIcon | def loadIcon(self, fileName, color=None):
""" Reads SVG from a file name and creates an QIcon from it.
Optionally replaces the color. Caches the created icons.
:param fileName: absolute path to an icon file.
If False/empty/None, None returned, which yields no icon.
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:return: QtGui.QIcon
"""
if not fileName:
return None
key = (fileName, color)
if key not in self._icons:
try:
with open(fileName, 'r') as input:
svg = input.read()
self._icons[key] = self.createIconFromSvg(svg, color=color)
except Exception as ex:
# It's preferable to show no icon in case of an error rather than letting
# the application fail. Icons are a (very) nice to have.
logger.warn("Unable to read icon: {}".format(ex))
if DEBUGGING:
raise
else:
return None
return self._icons[key] | python | def loadIcon(self, fileName, color=None):
""" Reads SVG from a file name and creates an QIcon from it.
Optionally replaces the color. Caches the created icons.
:param fileName: absolute path to an icon file.
If False/empty/None, None returned, which yields no icon.
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:return: QtGui.QIcon
"""
if not fileName:
return None
key = (fileName, color)
if key not in self._icons:
try:
with open(fileName, 'r') as input:
svg = input.read()
self._icons[key] = self.createIconFromSvg(svg, color=color)
except Exception as ex:
# It's preferable to show no icon in case of an error rather than letting
# the application fail. Icons are a (very) nice to have.
logger.warn("Unable to read icon: {}".format(ex))
if DEBUGGING:
raise
else:
return None
return self._icons[key] | Reads SVG from a file name and creates an QIcon from it.
Optionally replaces the color. Caches the created icons.
:param fileName: absolute path to an icon file.
If False/empty/None, None returned, which yields no icon.
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:return: QtGui.QIcon | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/iconfactory.py#L146-L175 |
titusjan/argos | argos/repo/iconfactory.py | RtiIconFactory.createIconFromSvg | def createIconFromSvg(self, svg, color=None, colorsToBeReplaced=None):
""" Creates a QIcon given an SVG string.
Optionally replaces the colors in colorsToBeReplaced by color.
:param svg: string containing Scalable Vector Graphics XML
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:param colorsToBeReplaced: optional list of colors to be replaced by color
If None, it will be set to the fill colors of the snip-icon libary
:return: QtGui.QIcon
"""
if colorsToBeReplaced is None:
colorsToBeReplaced = self.colorsToBeReplaced
if color:
for oldColor in colorsToBeReplaced:
svg = svg.replace(oldColor, color)
# From http://stackoverflow.com/questions/15123544/change-the-color-of-an-svg-in-qt
qByteArray = QtCore.QByteArray()
qByteArray.append(svg)
svgRenderer = QtSvg.QSvgRenderer(qByteArray)
icon = QtGui.QIcon()
for size in self.renderSizes:
pixMap = QtGui.QPixmap(QtCore.QSize(size, size))
pixMap.fill(Qt.transparent)
pixPainter = QtGui.QPainter(pixMap)
pixPainter.setRenderHint(QtGui.QPainter.TextAntialiasing, True)
pixPainter.setRenderHint(QtGui.QPainter.Antialiasing, True)
svgRenderer.render(pixPainter)
pixPainter.end()
icon.addPixmap(pixMap)
return icon | python | def createIconFromSvg(self, svg, color=None, colorsToBeReplaced=None):
""" Creates a QIcon given an SVG string.
Optionally replaces the colors in colorsToBeReplaced by color.
:param svg: string containing Scalable Vector Graphics XML
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:param colorsToBeReplaced: optional list of colors to be replaced by color
If None, it will be set to the fill colors of the snip-icon libary
:return: QtGui.QIcon
"""
if colorsToBeReplaced is None:
colorsToBeReplaced = self.colorsToBeReplaced
if color:
for oldColor in colorsToBeReplaced:
svg = svg.replace(oldColor, color)
# From http://stackoverflow.com/questions/15123544/change-the-color-of-an-svg-in-qt
qByteArray = QtCore.QByteArray()
qByteArray.append(svg)
svgRenderer = QtSvg.QSvgRenderer(qByteArray)
icon = QtGui.QIcon()
for size in self.renderSizes:
pixMap = QtGui.QPixmap(QtCore.QSize(size, size))
pixMap.fill(Qt.transparent)
pixPainter = QtGui.QPainter(pixMap)
pixPainter.setRenderHint(QtGui.QPainter.TextAntialiasing, True)
pixPainter.setRenderHint(QtGui.QPainter.Antialiasing, True)
svgRenderer.render(pixPainter)
pixPainter.end()
icon.addPixmap(pixMap)
return icon | Creates a QIcon given an SVG string.
Optionally replaces the colors in colorsToBeReplaced by color.
:param svg: string containing Scalable Vector Graphics XML
:param color: '#RRGGBB' string (e.g. '#FF0000' for red)
:param colorsToBeReplaced: optional list of colors to be replaced by color
If None, it will be set to the fill colors of the snip-icon libary
:return: QtGui.QIcon | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/iconfactory.py#L178-L211 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableModel.data | def data(self, index, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item referred to by the index.
"""
if not index.isValid():
return None
if role not in (Qt.DisplayRole, self.SORT_ROLE, Qt.ForegroundRole):
return None
row = index.row()
col = index.column()
item = self.registry.items[row]
attrName = self.attrNames[col]
if role == Qt.DisplayRole:
return str(getattr(item, attrName))
elif role == self.SORT_ROLE:
# Use the fullName column as a tie-breaker
return (getattr(item, attrName), item.fullName)
elif role == Qt.ForegroundRole:
if item.successfullyImported is None:
return self.notImportedBrush
elif item.successfullyImported:
return self.regularBrush
else:
return self.errorBrush
else:
raise ValueError("Invalid role: {}".format(role)) | python | def data(self, index, role=Qt.DisplayRole):
""" Returns the data stored under the given role for the item referred to by the index.
"""
if not index.isValid():
return None
if role not in (Qt.DisplayRole, self.SORT_ROLE, Qt.ForegroundRole):
return None
row = index.row()
col = index.column()
item = self.registry.items[row]
attrName = self.attrNames[col]
if role == Qt.DisplayRole:
return str(getattr(item, attrName))
elif role == self.SORT_ROLE:
# Use the fullName column as a tie-breaker
return (getattr(item, attrName), item.fullName)
elif role == Qt.ForegroundRole:
if item.successfullyImported is None:
return self.notImportedBrush
elif item.successfullyImported:
return self.regularBrush
else:
return self.errorBrush
else:
raise ValueError("Invalid role: {}".format(role)) | Returns the data stored under the given role for the item referred to by the index. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L71-L100 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableModel.headerData | def headerData(self, section, orientation, role):
""" Returns the header for a section (row or column depending on orientation).
Reimplemented from QAbstractTableModel to make the headers start at 0.
"""
if role == QtCore.Qt.DisplayRole:
if orientation == Qt.Horizontal:
return self.attrNames[section]
else:
return str(section)
else:
return None | python | def headerData(self, section, orientation, role):
""" Returns the header for a section (row or column depending on orientation).
Reimplemented from QAbstractTableModel to make the headers start at 0.
"""
if role == QtCore.Qt.DisplayRole:
if orientation == Qt.Horizontal:
return self.attrNames[section]
else:
return str(section)
else:
return None | Returns the header for a section (row or column depending on orientation).
Reimplemented from QAbstractTableModel to make the headers start at 0. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L103-L113 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableModel.indexFromItem | def indexFromItem(self, regItem, col=0):
""" Gets the index (with column=0) for the row that contains the regItem
If col is negative, it is counted from the end
"""
if col < 0:
col = len(self.attrNames) - col
try:
row = self.registry.items.index(regItem)
except ValueError:
return QtCore.QModelIndex()
else:
return self.index(row, col) | python | def indexFromItem(self, regItem, col=0):
""" Gets the index (with column=0) for the row that contains the regItem
If col is negative, it is counted from the end
"""
if col < 0:
col = len(self.attrNames) - col
try:
row = self.registry.items.index(regItem)
except ValueError:
return QtCore.QModelIndex()
else:
return self.index(row, col) | Gets the index (with column=0) for the row that contains the regItem
If col is negative, it is counted from the end | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L122-L133 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableModel.emitDataChanged | def emitDataChanged(self, regItem):
""" Emits the dataChagned signal for the regItem
"""
leftIndex = self.indexFromItem(regItem, col=0)
rightIndex = self.indexFromItem(regItem, col=-1)
logger.debug("Data changed: {} ...{}".format(self.data(leftIndex), self.data(rightIndex)))
self.dataChanged.emit(leftIndex, rightIndex) | python | def emitDataChanged(self, regItem):
""" Emits the dataChagned signal for the regItem
"""
leftIndex = self.indexFromItem(regItem, col=0)
rightIndex = self.indexFromItem(regItem, col=-1)
logger.debug("Data changed: {} ...{}".format(self.data(leftIndex), self.data(rightIndex)))
self.dataChanged.emit(leftIndex, rightIndex) | Emits the dataChagned signal for the regItem | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L136-L143 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableProxyModel.filterAcceptsRow | def filterAcceptsRow(self, sourceRow, sourceParent):
""" If onlyShowImported is True, regItems that were not (successfully) imported are
filtered out.
"""
if not self.onlyShowImported:
return True
item = self.sourceModel().registry.items[sourceRow]
return bool(item.successfullyImported) | python | def filterAcceptsRow(self, sourceRow, sourceParent):
""" If onlyShowImported is True, regItems that were not (successfully) imported are
filtered out.
"""
if not self.onlyShowImported:
return True
item = self.sourceModel().registry.items[sourceRow]
return bool(item.successfullyImported) | If onlyShowImported is True, regItems that were not (successfully) imported are
filtered out. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L163-L171 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableProxyModel.lessThan | def lessThan(self, leftIndex, rightIndex):
""" Returns true if the value of the item referred to by the given index left is less than
the value of the item referred to by the given index right, otherwise returns false.
"""
leftData = self.sourceModel().data(leftIndex, RegistryTableModel.SORT_ROLE)
rightData = self.sourceModel().data(rightIndex, RegistryTableModel.SORT_ROLE)
return leftData < rightData | python | def lessThan(self, leftIndex, rightIndex):
""" Returns true if the value of the item referred to by the given index left is less than
the value of the item referred to by the given index right, otherwise returns false.
"""
leftData = self.sourceModel().data(leftIndex, RegistryTableModel.SORT_ROLE)
rightData = self.sourceModel().data(rightIndex, RegistryTableModel.SORT_ROLE)
return leftData < rightData | Returns true if the value of the item referred to by the given index left is less than
the value of the item referred to by the given index right, otherwise returns false. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L174-L181 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableProxyModel.itemFromIndex | def itemFromIndex(self, index):
""" Gets the item given the model index
"""
sourceIndex = self.mapToSource(index)
return self.sourceModel().itemFromIndex(sourceIndex) | python | def itemFromIndex(self, index):
""" Gets the item given the model index
"""
sourceIndex = self.mapToSource(index)
return self.sourceModel().itemFromIndex(sourceIndex) | Gets the item given the model index | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L184-L188 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableProxyModel.indexFromItem | def indexFromItem(self, regItem, col=0):
""" Gets the index (with column=0) for the row that contains the regItem
If col is negative, it is counted from the end
"""
sourceIndex = self.sourceModel().indexFromItem(regItem, col=col)
return self.mapFromSource(sourceIndex) | python | def indexFromItem(self, regItem, col=0):
""" Gets the index (with column=0) for the row that contains the regItem
If col is negative, it is counted from the end
"""
sourceIndex = self.sourceModel().indexFromItem(regItem, col=col)
return self.mapFromSource(sourceIndex) | Gets the index (with column=0) for the row that contains the regItem
If col is negative, it is counted from the end | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L191-L196 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableProxyModel.emitDataChanged | def emitDataChanged(self, regItem):
""" Emits the dataChagned signal for the regItem
"""
#self.sourceModel().emitDataChanged(regItem) # Does this work?
leftIndex = self.indexFromItem(regItem, col=0)
rightIndex = self.indexFromItem(regItem, col=-1)
self.dataChanged.emit(leftIndex, rightIndex) | python | def emitDataChanged(self, regItem):
""" Emits the dataChagned signal for the regItem
"""
#self.sourceModel().emitDataChanged(regItem) # Does this work?
leftIndex = self.indexFromItem(regItem, col=0)
rightIndex = self.indexFromItem(regItem, col=-1)
self.dataChanged.emit(leftIndex, rightIndex) | Emits the dataChagned signal for the regItem | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L199-L205 |
titusjan/argos | argos/qt/registrytable.py | RegistryTableView.setCurrentRegItem | def setCurrentRegItem(self, regItem):
""" Sets the current registry item.
"""
rowIndex = self.model().indexFromItem(regItem)
if not rowIndex.isValid():
logger.warn("Can't select {!r} in table".format(regItem))
self.setCurrentIndex(rowIndex) | python | def setCurrentRegItem(self, regItem):
""" Sets the current registry item.
"""
rowIndex = self.model().indexFromItem(regItem)
if not rowIndex.isValid():
logger.warn("Can't select {!r} in table".format(regItem))
self.setCurrentIndex(rowIndex) | Sets the current registry item. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registrytable.py#L265-L271 |
titusjan/argos | docs/examples/buggy_inspector.py | persistentRegisterInspector | def persistentRegisterInspector(fullName, fullClassName, pythonPath=''):
""" Registers an inspector
Loads or inits the inspector registry, register the inspector and saves the settings.
Important: instantiate a Qt application first to use the correct settings file/winreg.
"""
registry = InspectorRegistry()
registry.loadOrInitSettings()
registry.registerInspector(fullName, fullClassName, pythonPath=pythonPath)
registry.saveSettings() | python | def persistentRegisterInspector(fullName, fullClassName, pythonPath=''):
""" Registers an inspector
Loads or inits the inspector registry, register the inspector and saves the settings.
Important: instantiate a Qt application first to use the correct settings file/winreg.
"""
registry = InspectorRegistry()
registry.loadOrInitSettings()
registry.registerInspector(fullName, fullClassName, pythonPath=pythonPath)
registry.saveSettings() | Registers an inspector
Loads or inits the inspector registry, register the inspector and saves the settings.
Important: instantiate a Qt application first to use the correct settings file/winreg. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/docs/examples/buggy_inspector.py#L73-L82 |
titusjan/argos | argos/main.py | browse | def browse(fileNames=None,
inspectorFullName=None,
select=None,
profile=DEFAULT_PROFILE,
resetProfile=False, # TODO: should probably be moved to the main program
resetAllProfiles=False, # TODO: should probably be moved to the main program
resetRegistry=False): # TODO: should probably be moved to the main program
""" Opens the main window(s) for the persistent settings of the given profile,
and executes the application.
:param fileNames: List of file names that will be added to the repository
:param inspectorFullName: The full path name of the inspector that will be loaded
:param select: a path of the repository item that will selected at start up.
:param profile: the name of the profile that will be loaded
:param resetProfile: if True, the profile will be reset to it standard settings.
:param resetAllProfiles: if True, all profiles will be reset to it standard settings.
:param resetRegistry: if True, the registry will be reset to it standard settings.
:return:
"""
# Imported here so this module can be imported without Qt being installed.
from argos.qt import QtWidgets, QtCore
from argos.application import ArgosApplication
from argos.repo.testdata import createArgosTestData
try:
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
except Exception as ex:
logger.debug("AA_UseHighDpiPixmaps not available in PyQt4: {}".format(ex))
# Create
argosApp = ArgosApplication()
if resetProfile:
argosApp.deleteProfile(profile)
if resetAllProfiles:
argosApp.deleteAllProfiles()
if resetRegistry:
argosApp.deleteRegistries()
# Must be called before opening the files so that file formats are auto-detected.
argosApp.loadOrInitRegistries()
# Load data in common repository before windows are created.
argosApp.loadFiles(fileNames)
if DEBUGGING:
argosApp.repo.insertItem(createArgosTestData())
# Create windows for this profile.
argosApp.loadProfile(profile=profile, inspectorFullName=inspectorFullName)
if select:
for mainWindow in argosApp.mainWindows:
mainWindow.trySelectRtiByPath(select)
return argosApp.execute() | python | def browse(fileNames=None,
inspectorFullName=None,
select=None,
profile=DEFAULT_PROFILE,
resetProfile=False, # TODO: should probably be moved to the main program
resetAllProfiles=False, # TODO: should probably be moved to the main program
resetRegistry=False): # TODO: should probably be moved to the main program
""" Opens the main window(s) for the persistent settings of the given profile,
and executes the application.
:param fileNames: List of file names that will be added to the repository
:param inspectorFullName: The full path name of the inspector that will be loaded
:param select: a path of the repository item that will selected at start up.
:param profile: the name of the profile that will be loaded
:param resetProfile: if True, the profile will be reset to it standard settings.
:param resetAllProfiles: if True, all profiles will be reset to it standard settings.
:param resetRegistry: if True, the registry will be reset to it standard settings.
:return:
"""
# Imported here so this module can be imported without Qt being installed.
from argos.qt import QtWidgets, QtCore
from argos.application import ArgosApplication
from argos.repo.testdata import createArgosTestData
try:
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
except Exception as ex:
logger.debug("AA_UseHighDpiPixmaps not available in PyQt4: {}".format(ex))
# Create
argosApp = ArgosApplication()
if resetProfile:
argosApp.deleteProfile(profile)
if resetAllProfiles:
argosApp.deleteAllProfiles()
if resetRegistry:
argosApp.deleteRegistries()
# Must be called before opening the files so that file formats are auto-detected.
argosApp.loadOrInitRegistries()
# Load data in common repository before windows are created.
argosApp.loadFiles(fileNames)
if DEBUGGING:
argosApp.repo.insertItem(createArgosTestData())
# Create windows for this profile.
argosApp.loadProfile(profile=profile, inspectorFullName=inspectorFullName)
if select:
for mainWindow in argosApp.mainWindows:
mainWindow.trySelectRtiByPath(select)
return argosApp.execute() | Opens the main window(s) for the persistent settings of the given profile,
and executes the application.
:param fileNames: List of file names that will be added to the repository
:param inspectorFullName: The full path name of the inspector that will be loaded
:param select: a path of the repository item that will selected at start up.
:param profile: the name of the profile that will be loaded
:param resetProfile: if True, the profile will be reset to it standard settings.
:param resetAllProfiles: if True, all profiles will be reset to it standard settings.
:param resetRegistry: if True, the registry will be reset to it standard settings.
:return: | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/main.py#L37-L91 |
titusjan/argos | argos/main.py | printInspectors | def printInspectors():
""" Prints a list of inspectors
"""
# Imported here so this module can be imported without Qt being installed.
from argos.application import ArgosApplication
argosApp = ArgosApplication()
argosApp.loadOrInitRegistries()
for regItem in argosApp.inspectorRegistry.items:
print(regItem.fullName) | python | def printInspectors():
""" Prints a list of inspectors
"""
# Imported here so this module can be imported without Qt being installed.
from argos.application import ArgosApplication
argosApp = ArgosApplication()
argosApp.loadOrInitRegistries()
for regItem in argosApp.inspectorRegistry.items:
print(regItem.fullName) | Prints a list of inspectors | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/main.py#L94-L103 |
titusjan/argos | argos/main.py | main | def main():
""" Starts Argos main window
"""
about_str = "{} version: {}".format(PROJECT_NAME, VERSION)
parser = argparse.ArgumentParser(description = about_str)
parser.add_argument('fileNames', metavar='FILE', nargs='*', help='Input files')
parser.add_argument('-i', '--inspector', dest='inspector',
help="""The identifier or fullName of the inspector that will be opened at start up.
E.g. 'Qt/Table'""")
parser.add_argument('--list-inspectors', dest='list_inspectors', action = 'store_true',
help="""Prints a list of available inspectors for the -i option""")
parser.add_argument('-s', '--select', dest='selectPath',
help="""Full path name of a repository tree item that will be selected at start-up.
E.g. 'file/var/fieldname'""")
parser.add_argument('-p', '--profile', dest='profile', default=DEFAULT_PROFILE,
help="Can be used to have different persistent settings for different use cases.")
parser.add_argument('--reset', '--reset-profile', dest='reset_profile', action = 'store_true',
help="If set, persistent settings will be reset for the current profile.")
parser.add_argument('--reset-all-profiles', dest='reset_all_profiles', action = 'store_true',
help="If set, persistent settings will be reset for the all profiles.")
parser.add_argument('--reset-registry', dest='reset_registry', action = 'store_true',
help="If set, the registry will be reset to contain only the default plugins.")
parser.add_argument('--version', action = 'store_true',
help="Prints the program version.")
parser.add_argument('-l', '--log-level', dest='log_level', default='warning',
help="Log level. Only log messages with a level higher or equal than this will be printed. "
"Default: 'warning'",
choices=('debug', 'info', 'warning', 'error', 'critical'))
args = parser.parse_args(remove_process_serial_number(sys.argv[1:]))
if DEBUGGING:
logger.info("Setting log level to: {}".format(args.log_level.upper()))
logger.setLevel(args.log_level.upper())
if DEBUGGING:
logger.warn("Debugging flag is on!")
if args.version:
print(about_str)
sys.exit(0)
if args.list_inspectors:
printInspectors()
sys.exit(0)
logger.info('Started {} {}'.format(PROJECT_NAME, VERSION))
logger.info("Python version: {}".format(sys.version).replace('\n', ''))
#logger.info('Using: {}'.format('PyQt' if USE_PYQT else 'PySide'))
# Imported here so this module can be imported without Qt being installed.
from argos.qt.misc import ABOUT_QT_BINDINGS
logger.info("Using {}".format(ABOUT_QT_BINDINGS))
# Browse will create an ArgosApplication with one MainWindow
browse(fileNames = args.fileNames,
inspectorFullName=args.inspector,
select=args.selectPath,
profile=args.profile,
resetProfile=args.reset_profile,
resetAllProfiles=args.reset_all_profiles,
resetRegistry=args.reset_registry)
logger.info('Done {}'.format(PROJECT_NAME)) | python | def main():
""" Starts Argos main window
"""
about_str = "{} version: {}".format(PROJECT_NAME, VERSION)
parser = argparse.ArgumentParser(description = about_str)
parser.add_argument('fileNames', metavar='FILE', nargs='*', help='Input files')
parser.add_argument('-i', '--inspector', dest='inspector',
help="""The identifier or fullName of the inspector that will be opened at start up.
E.g. 'Qt/Table'""")
parser.add_argument('--list-inspectors', dest='list_inspectors', action = 'store_true',
help="""Prints a list of available inspectors for the -i option""")
parser.add_argument('-s', '--select', dest='selectPath',
help="""Full path name of a repository tree item that will be selected at start-up.
E.g. 'file/var/fieldname'""")
parser.add_argument('-p', '--profile', dest='profile', default=DEFAULT_PROFILE,
help="Can be used to have different persistent settings for different use cases.")
parser.add_argument('--reset', '--reset-profile', dest='reset_profile', action = 'store_true',
help="If set, persistent settings will be reset for the current profile.")
parser.add_argument('--reset-all-profiles', dest='reset_all_profiles', action = 'store_true',
help="If set, persistent settings will be reset for the all profiles.")
parser.add_argument('--reset-registry', dest='reset_registry', action = 'store_true',
help="If set, the registry will be reset to contain only the default plugins.")
parser.add_argument('--version', action = 'store_true',
help="Prints the program version.")
parser.add_argument('-l', '--log-level', dest='log_level', default='warning',
help="Log level. Only log messages with a level higher or equal than this will be printed. "
"Default: 'warning'",
choices=('debug', 'info', 'warning', 'error', 'critical'))
args = parser.parse_args(remove_process_serial_number(sys.argv[1:]))
if DEBUGGING:
logger.info("Setting log level to: {}".format(args.log_level.upper()))
logger.setLevel(args.log_level.upper())
if DEBUGGING:
logger.warn("Debugging flag is on!")
if args.version:
print(about_str)
sys.exit(0)
if args.list_inspectors:
printInspectors()
sys.exit(0)
logger.info('Started {} {}'.format(PROJECT_NAME, VERSION))
logger.info("Python version: {}".format(sys.version).replace('\n', ''))
#logger.info('Using: {}'.format('PyQt' if USE_PYQT else 'PySide'))
# Imported here so this module can be imported without Qt being installed.
from argos.qt.misc import ABOUT_QT_BINDINGS
logger.info("Using {}".format(ABOUT_QT_BINDINGS))
# Browse will create an ArgosApplication with one MainWindow
browse(fileNames = args.fileNames,
inspectorFullName=args.inspector,
select=args.selectPath,
profile=args.profile,
resetProfile=args.reset_profile,
resetAllProfiles=args.reset_all_profiles,
resetRegistry=args.reset_registry)
logger.info('Done {}'.format(PROJECT_NAME)) | Starts Argos main window | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/main.py#L124-L197 |
titusjan/argos | argos/widgets/argostreeview.py | ArgosTreeView.setModel | def setModel(self, model):
""" Sets the model.
Checks that the model is a
"""
check_class(model, BaseTreeModel)
super(ArgosTreeView, self).setModel(model) | python | def setModel(self, model):
""" Sets the model.
Checks that the model is a
"""
check_class(model, BaseTreeModel)
super(ArgosTreeView, self).setModel(model) | Sets the model.
Checks that the model is a | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/argostreeview.py#L88-L93 |
titusjan/argos | argos/widgets/argostreeview.py | ArgosTreeView.setCurrentIndex | def setCurrentIndex(self, currentIndex):
""" Sets the current item to be the item at currentIndex.
Also select the row as to give consistent user feedback.
See also the notes at the top of this module on current item vs selected item(s).
"""
selectionModel = self.selectionModel()
selectionFlags = (QtCore.QItemSelectionModel.ClearAndSelect |
QtCore.QItemSelectionModel.Rows)
selectionModel.setCurrentIndex(currentIndex, selectionFlags) | python | def setCurrentIndex(self, currentIndex):
""" Sets the current item to be the item at currentIndex.
Also select the row as to give consistent user feedback.
See also the notes at the top of this module on current item vs selected item(s).
"""
selectionModel = self.selectionModel()
selectionFlags = (QtCore.QItemSelectionModel.ClearAndSelect |
QtCore.QItemSelectionModel.Rows)
selectionModel.setCurrentIndex(currentIndex, selectionFlags) | Sets the current item to be the item at currentIndex.
Also select the row as to give consistent user feedback.
See also the notes at the top of this module on current item vs selected item(s). | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/argostreeview.py#L96-L104 |
titusjan/argos | argos/widgets/argostreeview.py | ArgosTreeView.getRowCurrentIndex | def getRowCurrentIndex(self):
""" Returns the index of column 0 of the current item in the underlying model.
See also the notes at the top of this module on current item vs selected item(s).
"""
curIndex = self.currentIndex()
col0Index = curIndex.sibling(curIndex.row(), 0)
return col0Index | python | def getRowCurrentIndex(self):
""" Returns the index of column 0 of the current item in the underlying model.
See also the notes at the top of this module on current item vs selected item(s).
"""
curIndex = self.currentIndex()
col0Index = curIndex.sibling(curIndex.row(), 0)
return col0Index | Returns the index of column 0 of the current item in the underlying model.
See also the notes at the top of this module on current item vs selected item(s). | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/argostreeview.py#L107-L113 |
titusjan/argos | argos/widgets/argostreeview.py | ArgosTreeView.getCurrentItem | def getCurrentItem(self): # TODO: rename? getCurrentItemAndIndex? getCurrentTuple? getCurrent?
""" Find the current tree item (and the current index while we're at it)
Returns a tuple with the current item, and its index. The item may be None.
See also the notes at the top of this module on current item vs selected item(s).
"""
currentIndex = self.getRowCurrentIndex()
currentItem = self.model().getItem(currentIndex)
return currentItem, currentIndex | python | def getCurrentItem(self): # TODO: rename? getCurrentItemAndIndex? getCurrentTuple? getCurrent?
""" Find the current tree item (and the current index while we're at it)
Returns a tuple with the current item, and its index. The item may be None.
See also the notes at the top of this module on current item vs selected item(s).
"""
currentIndex = self.getRowCurrentIndex()
currentItem = self.model().getItem(currentIndex)
return currentItem, currentIndex | Find the current tree item (and the current index while we're at it)
Returns a tuple with the current item, and its index. The item may be None.
See also the notes at the top of this module on current item vs selected item(s). | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/argostreeview.py#L116-L123 |
titusjan/argos | argos/widgets/argostreeview.py | ArgosTreeView.expandPath | def expandPath(self, path):
""" Follows the path and expand all nodes along the way.
Returns (item, index) tuple of the last node in the path (the leaf node). This can be
reused e.g. to select it.
"""
iiPath = self.model().findItemAndIndexPath(path)
for (item, index) in iiPath[1:]: # skip invisible root
assert index.isValid(), "Sanity check: invalid index in path for item: {}".format(item)
self.expand(index)
leaf = iiPath[-1]
return leaf | python | def expandPath(self, path):
""" Follows the path and expand all nodes along the way.
Returns (item, index) tuple of the last node in the path (the leaf node). This can be
reused e.g. to select it.
"""
iiPath = self.model().findItemAndIndexPath(path)
for (item, index) in iiPath[1:]: # skip invisible root
assert index.isValid(), "Sanity check: invalid index in path for item: {}".format(item)
self.expand(index)
leaf = iiPath[-1]
return leaf | Follows the path and expand all nodes along the way.
Returns (item, index) tuple of the last node in the path (the leaf node). This can be
reused e.g. to select it. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/argostreeview.py#L126-L137 |
titusjan/argos | argos/widgets/argostreeview.py | ArgosTreeView.expandBranch | def expandBranch(self, index=None, expanded=True):
""" Expands or collapses the node at the index and all it's descendants.
If expanded is True the nodes will be expanded, if False they will be collapsed.
If parentIndex is None, the invisible root will be used (i.e. the complete forest will
be expanded).
"""
treeModel = self.model()
if index is None:
index = QtCore.QModelIndex()
if index.isValid():
self.setExpanded(index, expanded)
for rowNr in range(treeModel.rowCount(index)):
childIndex = treeModel.index(rowNr, 0, parentIndex=index)
self.expandBranch(index=childIndex, expanded=expanded) | python | def expandBranch(self, index=None, expanded=True):
""" Expands or collapses the node at the index and all it's descendants.
If expanded is True the nodes will be expanded, if False they will be collapsed.
If parentIndex is None, the invisible root will be used (i.e. the complete forest will
be expanded).
"""
treeModel = self.model()
if index is None:
index = QtCore.QModelIndex()
if index.isValid():
self.setExpanded(index, expanded)
for rowNr in range(treeModel.rowCount(index)):
childIndex = treeModel.index(rowNr, 0, parentIndex=index)
self.expandBranch(index=childIndex, expanded=expanded) | Expands or collapses the node at the index and all it's descendants.
If expanded is True the nodes will be expanded, if False they will be collapsed.
If parentIndex is None, the invisible root will be used (i.e. the complete forest will
be expanded). | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/argostreeview.py#L140-L157 |
titusjan/argos | argos/collect/collector.py | Collector.blockChildrenSignals | def blockChildrenSignals(self, block):
""" If block equals True, the signals of the combo boxes and spin boxes are blocked
Returns the old blocking state.
"""
logger.debug("Blocking collector signals")
for spinBox in self._spinBoxes:
spinBox.blockSignals(block)
for comboBox in self._comboBoxes:
comboBox.blockSignals(block)
result = self._signalsBlocked
self._signalsBlocked = block
return result | python | def blockChildrenSignals(self, block):
""" If block equals True, the signals of the combo boxes and spin boxes are blocked
Returns the old blocking state.
"""
logger.debug("Blocking collector signals")
for spinBox in self._spinBoxes:
spinBox.blockSignals(block)
for comboBox in self._comboBoxes:
comboBox.blockSignals(block)
result = self._signalsBlocked
self._signalsBlocked = block
return result | If block equals True, the signals of the combo boxes and spin boxes are blocked
Returns the old blocking state. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L145-L156 |
titusjan/argos | argos/collect/collector.py | Collector._setColumnCountForContents | def _setColumnCountForContents(self):
""" Sets the column count given the current axes and selected RTI.
Returns the newly set column count.
"""
numRtiDims = self.rti.nDims if self.rti and self.rti.isSliceable else 0
colCount = self.COL_FIRST_COMBO + max(numRtiDims, len(self.axisNames))
self.tree.model().setColumnCount(colCount)
return colCount | python | def _setColumnCountForContents(self):
""" Sets the column count given the current axes and selected RTI.
Returns the newly set column count.
"""
numRtiDims = self.rti.nDims if self.rti and self.rti.isSliceable else 0
colCount = self.COL_FIRST_COMBO + max(numRtiDims, len(self.axisNames))
self.tree.model().setColumnCount(colCount)
return colCount | Sets the column count given the current axes and selected RTI.
Returns the newly set column count. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L159-L167 |
titusjan/argos | argos/collect/collector.py | Collector.clear | def clear(self):
""" Removes all VisItems
"""
model = self.tree.model()
# Don't use model.clear(). it will delete the column sizes
model.removeRows(0, 1)
model.setRowCount(1)
self._setColumnCountForContents() | python | def clear(self):
""" Removes all VisItems
"""
model = self.tree.model()
# Don't use model.clear(). it will delete the column sizes
model.removeRows(0, 1)
model.setRowCount(1)
self._setColumnCountForContents() | Removes all VisItems | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L170-L177 |
titusjan/argos | argos/collect/collector.py | Collector.clearAndSetComboBoxes | def clearAndSetComboBoxes(self, axesNames):
""" Removes all comboboxes.
"""
logger.debug("Collector clearAndSetComboBoxes: {}".format(axesNames))
check_is_a_sequence(axesNames)
row = 0
self._deleteComboBoxes(row)
self.clear()
self._setAxesNames(axesNames)
self._createComboBoxes(row)
self._updateWidgets() | python | def clearAndSetComboBoxes(self, axesNames):
""" Removes all comboboxes.
"""
logger.debug("Collector clearAndSetComboBoxes: {}".format(axesNames))
check_is_a_sequence(axesNames)
row = 0
self._deleteComboBoxes(row)
self.clear()
self._setAxesNames(axesNames)
self._createComboBoxes(row)
self._updateWidgets() | Removes all comboboxes. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L180-L190 |
titusjan/argos | argos/collect/collector.py | Collector._setAxesNames | def _setAxesNames(self, axisNames):
""" Sets the axesnames, combobox lables and updates the headers. Removes old values first.
The comboLables is the axes name + '-axis'
"""
for col, _ in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO):
self._setHeaderLabel(col, '')
self._axisNames = tuple(axisNames)
self._fullAxisNames = tuple([axName + self.AXIS_POST_FIX for axName in axisNames])
for col, label in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO):
self._setHeaderLabel(col, label) | python | def _setAxesNames(self, axisNames):
""" Sets the axesnames, combobox lables and updates the headers. Removes old values first.
The comboLables is the axes name + '-axis'
"""
for col, _ in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO):
self._setHeaderLabel(col, '')
self._axisNames = tuple(axisNames)
self._fullAxisNames = tuple([axName + self.AXIS_POST_FIX for axName in axisNames])
for col, label in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO):
self._setHeaderLabel(col, label) | Sets the axesnames, combobox lables and updates the headers. Removes old values first.
The comboLables is the axes name + '-axis' | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L193-L204 |
titusjan/argos | argos/collect/collector.py | Collector._setHeaderLabel | def _setHeaderLabel(self, col, text):
""" Sets the header of column col to text.
Will increase the number of columns if col is larger than the current number.
"""
model = self.tree.model()
item = model.horizontalHeaderItem(col)
if item:
item.setText(text)
else:
model.setHorizontalHeaderItem(col, QtGui.QStandardItem(text)) | python | def _setHeaderLabel(self, col, text):
""" Sets the header of column col to text.
Will increase the number of columns if col is larger than the current number.
"""
model = self.tree.model()
item = model.horizontalHeaderItem(col)
if item:
item.setText(text)
else:
model.setHorizontalHeaderItem(col, QtGui.QStandardItem(text)) | Sets the header of column col to text.
Will increase the number of columns if col is larger than the current number. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L207-L216 |
titusjan/argos | argos/collect/collector.py | Collector.setRti | def setRti(self, rti):
""" Updates the current VisItem from the contents of the repo tree item.
Is a slot but the signal is usually connected to the Collector, which then calls
this function directly.
"""
check_class(rti, BaseRti)
#assert rti.isSliceable, "RTI must be sliceable" # TODO: maybe later
self._rti = rti
self._updateWidgets()
self._updateRtiInfo() | python | def setRti(self, rti):
""" Updates the current VisItem from the contents of the repo tree item.
Is a slot but the signal is usually connected to the Collector, which then calls
this function directly.
"""
check_class(rti, BaseRti)
#assert rti.isSliceable, "RTI must be sliceable" # TODO: maybe later
self._rti = rti
self._updateWidgets()
self._updateRtiInfo() | Updates the current VisItem from the contents of the repo tree item.
Is a slot but the signal is usually connected to the Collector, which then calls
this function directly. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L220-L231 |
titusjan/argos | argos/collect/collector.py | Collector._updateWidgets | def _updateWidgets(self):
""" Updates the combo and spin boxes given the new rti or axes.
Emits the sigContentsChanged signal.
"""
row = 0
model = self.tree.model()
# Create path label
nodePath = '' if self.rti is None else self.rti.nodePath
pathItem = QtGui.QStandardItem(nodePath)
pathItem.setToolTip(nodePath)
pathItem.setEditable(False)
if self.rti is not None:
pathItem.setIcon(self.rti.decoration)
model.setItem(row, 0, pathItem)
self._deleteSpinBoxes(row)
self._populateComboBoxes(row)
self._createSpinBoxes(row)
self._updateRtiInfo()
self.tree.resizeColumnsToContents(startCol=self.COL_FIRST_COMBO)
logger.debug("{} sigContentsChanged signal (_updateWidgets)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit(UpdateReason.RTI_CHANGED) | python | def _updateWidgets(self):
""" Updates the combo and spin boxes given the new rti or axes.
Emits the sigContentsChanged signal.
"""
row = 0
model = self.tree.model()
# Create path label
nodePath = '' if self.rti is None else self.rti.nodePath
pathItem = QtGui.QStandardItem(nodePath)
pathItem.setToolTip(nodePath)
pathItem.setEditable(False)
if self.rti is not None:
pathItem.setIcon(self.rti.decoration)
model.setItem(row, 0, pathItem)
self._deleteSpinBoxes(row)
self._populateComboBoxes(row)
self._createSpinBoxes(row)
self._updateRtiInfo()
self.tree.resizeColumnsToContents(startCol=self.COL_FIRST_COMBO)
logger.debug("{} sigContentsChanged signal (_updateWidgets)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit(UpdateReason.RTI_CHANGED) | Updates the combo and spin boxes given the new rti or axes.
Emits the sigContentsChanged signal. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L234-L259 |
titusjan/argos | argos/collect/collector.py | Collector._createComboBoxes | def _createComboBoxes(self, row):
""" Creates a combo box for each of the fullAxisNames
"""
tree = self.tree
model = self.tree.model()
self._setColumnCountForContents()
for col, _ in enumerate(self._axisNames, self.COL_FIRST_COMBO):
logger.debug("Adding combobox at ({}, {})".format(row, col))
comboBox = QtWidgets.QComboBox()
comboBox.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
comboBox.activated.connect(self._comboBoxActivated)
self._comboBoxes.append(comboBox)
#editor = LabeledWidget(QtWidgets.QLabel(comboLabel), comboBox)
tree.setIndexWidget(model.index(row, col), comboBox) | python | def _createComboBoxes(self, row):
""" Creates a combo box for each of the fullAxisNames
"""
tree = self.tree
model = self.tree.model()
self._setColumnCountForContents()
for col, _ in enumerate(self._axisNames, self.COL_FIRST_COMBO):
logger.debug("Adding combobox at ({}, {})".format(row, col))
comboBox = QtWidgets.QComboBox()
comboBox.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
comboBox.activated.connect(self._comboBoxActivated)
self._comboBoxes.append(comboBox)
#editor = LabeledWidget(QtWidgets.QLabel(comboLabel), comboBox)
tree.setIndexWidget(model.index(row, col), comboBox) | Creates a combo box for each of the fullAxisNames | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L262-L277 |
titusjan/argos | argos/collect/collector.py | Collector._deleteComboBoxes | def _deleteComboBoxes(self, row):
""" Deletes all comboboxes of a row
"""
tree = self.tree
model = self.tree.model()
for col in range(self.COL_FIRST_COMBO, self.maxCombos):
logger.debug("Removing combobox at: ({}, {})".format(row, col))
tree.setIndexWidget(model.index(row, col), None)
self._comboBoxes = [] | python | def _deleteComboBoxes(self, row):
""" Deletes all comboboxes of a row
"""
tree = self.tree
model = self.tree.model()
for col in range(self.COL_FIRST_COMBO, self.maxCombos):
logger.debug("Removing combobox at: ({}, {})".format(row, col))
tree.setIndexWidget(model.index(row, col), None)
self._comboBoxes = [] | Deletes all comboboxes of a row | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L280-L290 |
titusjan/argos | argos/collect/collector.py | Collector._populateComboBoxes | def _populateComboBoxes(self, row):
""" Populates the combo boxes with values of the repo tree item
"""
logger.debug("_populateComboBoxes")
for comboBox in self._comboBoxes:
comboBox.clear()
if not self.rtiIsSliceable:
# Add an empty item to the combo boxes so that resize to contents works.
for comboBoxNr, comboBox in enumerate(self._comboBoxes):
comboBox.addItem('', userData=None)
comboBox.setEnabled(False)
return
nDims = self._rti.nDims
nCombos = len(self._comboBoxes)
for comboBoxNr, comboBox in enumerate(self._comboBoxes):
# Add a fake dimension of length 1
comboBox.addItem(FAKE_DIM_NAME, userData = FAKE_DIM_OFFSET + comboBoxNr)
for dimNr in range(nDims):
comboBox.addItem(self._rti.dimensionNames[dimNr], userData=dimNr)
# Set combobox current index
if nDims >= nCombos:
# We set the nth combo-box index to the last item - n. This because the
# NetCDF-CF conventions have the preferred dimension order of T, Z, Y, X.
# The +1 below is from the fake dimension.
curIdx = nDims + 1 - nCombos + comboBoxNr
else:
# If there are less dimensions in the RTI than the inspector can show, we fill
# the comboboxes starting at the leftmost and set the remaining comboboxes to the
# fake dimension. This means that a table inspector fill have one column and many
# rows, which is the most convenient.
curIdx = comboBoxNr + 1 if comboBoxNr < nDims else 0
assert 0 <= curIdx <= nDims + 1, \
"curIdx should be <= {}, got {}".format(nDims + 1, curIdx)
comboBox.setCurrentIndex(curIdx)
comboBox.setEnabled(True) | python | def _populateComboBoxes(self, row):
""" Populates the combo boxes with values of the repo tree item
"""
logger.debug("_populateComboBoxes")
for comboBox in self._comboBoxes:
comboBox.clear()
if not self.rtiIsSliceable:
# Add an empty item to the combo boxes so that resize to contents works.
for comboBoxNr, comboBox in enumerate(self._comboBoxes):
comboBox.addItem('', userData=None)
comboBox.setEnabled(False)
return
nDims = self._rti.nDims
nCombos = len(self._comboBoxes)
for comboBoxNr, comboBox in enumerate(self._comboBoxes):
# Add a fake dimension of length 1
comboBox.addItem(FAKE_DIM_NAME, userData = FAKE_DIM_OFFSET + comboBoxNr)
for dimNr in range(nDims):
comboBox.addItem(self._rti.dimensionNames[dimNr], userData=dimNr)
# Set combobox current index
if nDims >= nCombos:
# We set the nth combo-box index to the last item - n. This because the
# NetCDF-CF conventions have the preferred dimension order of T, Z, Y, X.
# The +1 below is from the fake dimension.
curIdx = nDims + 1 - nCombos + comboBoxNr
else:
# If there are less dimensions in the RTI than the inspector can show, we fill
# the comboboxes starting at the leftmost and set the remaining comboboxes to the
# fake dimension. This means that a table inspector fill have one column and many
# rows, which is the most convenient.
curIdx = comboBoxNr + 1 if comboBoxNr < nDims else 0
assert 0 <= curIdx <= nDims + 1, \
"curIdx should be <= {}, got {}".format(nDims + 1, curIdx)
comboBox.setCurrentIndex(curIdx)
comboBox.setEnabled(True) | Populates the combo boxes with values of the repo tree item | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L294-L335 |
titusjan/argos | argos/collect/collector.py | Collector._dimensionSelectedInComboBox | def _dimensionSelectedInComboBox(self, dimNr):
""" Returns True if the dimension is selected in one of the combo boxes.
"""
for combobox in self._comboBoxes:
if self._comboBoxDimensionIndex(combobox) == dimNr:
return True
return False | python | def _dimensionSelectedInComboBox(self, dimNr):
""" Returns True if the dimension is selected in one of the combo boxes.
"""
for combobox in self._comboBoxes:
if self._comboBoxDimensionIndex(combobox) == dimNr:
return True
return False | Returns True if the dimension is selected in one of the combo boxes. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L357-L363 |
titusjan/argos | argos/collect/collector.py | Collector._createSpinBoxes | def _createSpinBoxes(self, row):
""" Creates a spinBox for each dimension that is not selected in a combo box.
"""
assert len(self._spinBoxes) == 0, "Spinbox list not empty. Call _deleteSpinBoxes first"
if not self.rtiIsSliceable:
return
logger.debug("_createSpinBoxes, array shape: {}".format(self._rti.arrayShape))
self._setColumnCountForContents()
tree = self.tree
model = self.tree.model()
col = self.COL_FIRST_COMBO + self.maxCombos
for dimNr, dimSize in enumerate(self._rti.arrayShape):
if self._dimensionSelectedInComboBox(dimNr):
continue
self._setHeaderLabel(col, '')
spinBox = CollectorSpinBox()
self._spinBoxes.append(spinBox)
spinBox.setKeyboardTracking(False)
spinBox.setCorrectionMode(QtWidgets.QAbstractSpinBox.CorrectToNearestValue)
spinBox.setMinimum(0)
spinBox.setMaximum(dimSize - 1)
spinBox.setSingleStep(1)
spinBox.setValue(dimSize // 2) # select the middle of the slice
spinBox.setPrefix("{}: ".format(self._rti.dimensionNames[dimNr]))
spinBox.setSuffix("/{}".format(spinBox.maximum()))
spinBox.setProperty("dim_nr", dimNr)
#spinBox.adjustSize() # necessary?
# This must be done after setValue to prevent emitting too many signals
spinBox.valueChanged[int].connect(self._spinboxValueChanged)
tree.setIndexWidget(model.index(row, col), spinBox)
col += 1
# Resize the spinbox columns to their new contents
self.tree.resizeColumnsToContents(startCol=self.COL_FIRST_COMBO + self.maxCombos) | python | def _createSpinBoxes(self, row):
""" Creates a spinBox for each dimension that is not selected in a combo box.
"""
assert len(self._spinBoxes) == 0, "Spinbox list not empty. Call _deleteSpinBoxes first"
if not self.rtiIsSliceable:
return
logger.debug("_createSpinBoxes, array shape: {}".format(self._rti.arrayShape))
self._setColumnCountForContents()
tree = self.tree
model = self.tree.model()
col = self.COL_FIRST_COMBO + self.maxCombos
for dimNr, dimSize in enumerate(self._rti.arrayShape):
if self._dimensionSelectedInComboBox(dimNr):
continue
self._setHeaderLabel(col, '')
spinBox = CollectorSpinBox()
self._spinBoxes.append(spinBox)
spinBox.setKeyboardTracking(False)
spinBox.setCorrectionMode(QtWidgets.QAbstractSpinBox.CorrectToNearestValue)
spinBox.setMinimum(0)
spinBox.setMaximum(dimSize - 1)
spinBox.setSingleStep(1)
spinBox.setValue(dimSize // 2) # select the middle of the slice
spinBox.setPrefix("{}: ".format(self._rti.dimensionNames[dimNr]))
spinBox.setSuffix("/{}".format(spinBox.maximum()))
spinBox.setProperty("dim_nr", dimNr)
#spinBox.adjustSize() # necessary?
# This must be done after setValue to prevent emitting too many signals
spinBox.valueChanged[int].connect(self._spinboxValueChanged)
tree.setIndexWidget(model.index(row, col), spinBox)
col += 1
# Resize the spinbox columns to their new contents
self.tree.resizeColumnsToContents(startCol=self.COL_FIRST_COMBO + self.maxCombos) | Creates a spinBox for each dimension that is not selected in a combo box. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L366-L411 |
titusjan/argos | argos/collect/collector.py | Collector._deleteSpinBoxes | def _deleteSpinBoxes(self, row):
""" Removes all spinboxes
"""
tree = self.tree
model = self.tree.model()
for col, spinBox in enumerate(self._spinBoxes, self.COL_FIRST_COMBO + self.maxCombos):
spinBox.valueChanged[int].disconnect(self._spinboxValueChanged)
tree.setIndexWidget(model.index(row, col), None)
self._spinBoxes = []
self._setColumnCountForContents() | python | def _deleteSpinBoxes(self, row):
""" Removes all spinboxes
"""
tree = self.tree
model = self.tree.model()
for col, spinBox in enumerate(self._spinBoxes, self.COL_FIRST_COMBO + self.maxCombos):
spinBox.valueChanged[int].disconnect(self._spinboxValueChanged)
tree.setIndexWidget(model.index(row, col), None)
self._spinBoxes = []
self._setColumnCountForContents() | Removes all spinboxes | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L414-L425 |
titusjan/argos | argos/collect/collector.py | Collector._comboBoxActivated | def _comboBoxActivated(self, index, comboBox=None):
""" Is called when a combo box value was changed by the user.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1.
"""
if comboBox is None:
comboBox = self.sender()
assert comboBox, "comboBox not defined and not the sender"
blocked = self.blockChildrenSignals(True)
# If one of the other combo boxes has the same value, set it to the fake dimension
curDimIdx = self._comboBoxDimensionIndex(comboBox)
if curDimIdx < FAKE_DIM_OFFSET:
otherComboBoxes = [cb for cb in self._comboBoxes if cb is not comboBox]
for otherComboBox in otherComboBoxes:
if otherComboBox.currentIndex() == comboBox.currentIndex():
#newIdx = otherComboBox.findData(FAKE_DIM_IDX)
#otherComboBox.setCurrentIndex(newIdx)
otherComboBox.setCurrentIndex(0) # Fake dimension is always the first
# Show only spin boxes that are not selected
row = 0
self._deleteSpinBoxes(row)
self._createSpinBoxes(row)
self._updateRtiInfo()
self.blockChildrenSignals(blocked)
logger.debug("{} sigContentsChanged signal (comboBox)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit(UpdateReason.COLLECTOR_COMBO_BOX) | python | def _comboBoxActivated(self, index, comboBox=None):
""" Is called when a combo box value was changed by the user.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1.
"""
if comboBox is None:
comboBox = self.sender()
assert comboBox, "comboBox not defined and not the sender"
blocked = self.blockChildrenSignals(True)
# If one of the other combo boxes has the same value, set it to the fake dimension
curDimIdx = self._comboBoxDimensionIndex(comboBox)
if curDimIdx < FAKE_DIM_OFFSET:
otherComboBoxes = [cb for cb in self._comboBoxes if cb is not comboBox]
for otherComboBox in otherComboBoxes:
if otherComboBox.currentIndex() == comboBox.currentIndex():
#newIdx = otherComboBox.findData(FAKE_DIM_IDX)
#otherComboBox.setCurrentIndex(newIdx)
otherComboBox.setCurrentIndex(0) # Fake dimension is always the first
# Show only spin boxes that are not selected
row = 0
self._deleteSpinBoxes(row)
self._createSpinBoxes(row)
self._updateRtiInfo()
self.blockChildrenSignals(blocked)
logger.debug("{} sigContentsChanged signal (comboBox)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit(UpdateReason.COLLECTOR_COMBO_BOX) | Is called when a combo box value was changed by the user.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L429-L461 |
titusjan/argos | argos/collect/collector.py | Collector._spinboxValueChanged | def _spinboxValueChanged(self, index, spinBox=None):
""" Is called when a spin box value was changed.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1.
"""
if spinBox is None:
spinBox = self.sender()
assert spinBox, "spinBox not defined and not the sender"
logger.debug("{} sigContentsChanged signal (spinBox)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit(UpdateReason.COLLECTOR_SPIN_BOX) | python | def _spinboxValueChanged(self, index, spinBox=None):
""" Is called when a spin box value was changed.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1.
"""
if spinBox is None:
spinBox = self.sender()
assert spinBox, "spinBox not defined and not the sender"
logger.debug("{} sigContentsChanged signal (spinBox)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit(UpdateReason.COLLECTOR_SPIN_BOX) | Is called when a spin box value was changed.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L465-L477 |
titusjan/argos | argos/collect/collector.py | Collector.getSlicedArray | def getSlicedArray(self, copy=True):
""" Slice the rti using a tuple of slices made from the values of the combo and spin boxes.
:param copy: If True (the default), a copy is made so that inspectors cannot
accidentally modify the underlying of the RTIs. You can set copy=False as a
potential optimization, but only if you are absolutely sure that you don't modify
the the slicedArray in your inspector! Note that this function calls transpose,
which can still make a copy of the array for certain permutations.
:return: Numpy masked array with the same number of dimension as the number of
comboboxes (this can be zero!).
Returns None if no slice can be made (i.e. the RTI is not sliceable).
"""
#logger.debug("getSlicedArray() called")
if not self.rtiIsSliceable:
return None
# The dimensions that are selected in the combo boxes will be set to slice(None),
# the values from the spin boxes will be set as a single integer value
nDims = self.rti.nDims
sliceList = [slice(None)] * nDims
for spinBox in self._spinBoxes:
dimNr = spinBox.property("dim_nr")
sliceList[dimNr] = spinBox.value()
# Make the array slicer. It needs to be a tuple, a list of only integers will be
# interpreted as an index. With a tuple, array[(exp1, exp2, ..., expN)] is equivalent to
# array[exp1, exp2, ..., expN].
# See: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
logger.debug("Array slice list: {}".format(str(sliceList)))
slicedArray = self.rti[tuple(sliceList)]
# Make a copy to prevent inspectors from modifying the underlying array.
if copy:
slicedArray = ma.copy(slicedArray)
# If there are no comboboxes the sliceList will contain no Slices objects, only ints. Then
# the resulting slicedArray will be a usually a scalar (only structured fields may yield an
# array). We convert this scalar to a zero-dimensional Numpy array so that inspectors
# always get an array (having the same number of dimensions as the dimensionality of the
# inspector, i.e. the number of comboboxes).
if self.maxCombos == 0:
slicedArray = ma.MaskedArray(slicedArray)
# Post-condition type check
check_is_an_array(slicedArray, np.ndarray)
# Enforce the return type to be a masked array.
if not isinstance(slicedArray, ma.MaskedArray):
slicedArray = ma.MaskedArray(slicedArray)
# Add fake dimensions of length 1 so that result.ndim will equal the number of combo boxes
for dimNr in range(slicedArray.ndim, self.maxCombos):
#logger.debug("Adding fake dimension: {}".format(dimNr))
slicedArray = ma.expand_dims(slicedArray, dimNr)
# Post-condition dimension check
assert slicedArray.ndim == self.maxCombos, \
"Bug: getSlicedArray should return a {:d}D array, got: {}D" \
.format(self.maxCombos, slicedArray.ndim)
# Convert to ArrayWithMask class for working around issues with the numpy maskedarray
awm = ArrayWithMask.createFromMaskedArray(slicedArray)
del slicedArray
# Shuffle the dimensions to be in the order as specified by the combo boxes
comboDims = [self._comboBoxDimensionIndex(cb) for cb in self._comboBoxes]
permutations = np.argsort(comboDims)
logger.debug("slicedArray.shape: {}".format(awm.data.shape))
logger.debug("Transposing dimensions: {}".format(permutations))
awm = awm.transpose(permutations)
awm.checkIsConsistent()
return awm | python | def getSlicedArray(self, copy=True):
""" Slice the rti using a tuple of slices made from the values of the combo and spin boxes.
:param copy: If True (the default), a copy is made so that inspectors cannot
accidentally modify the underlying of the RTIs. You can set copy=False as a
potential optimization, but only if you are absolutely sure that you don't modify
the the slicedArray in your inspector! Note that this function calls transpose,
which can still make a copy of the array for certain permutations.
:return: Numpy masked array with the same number of dimension as the number of
comboboxes (this can be zero!).
Returns None if no slice can be made (i.e. the RTI is not sliceable).
"""
#logger.debug("getSlicedArray() called")
if not self.rtiIsSliceable:
return None
# The dimensions that are selected in the combo boxes will be set to slice(None),
# the values from the spin boxes will be set as a single integer value
nDims = self.rti.nDims
sliceList = [slice(None)] * nDims
for spinBox in self._spinBoxes:
dimNr = spinBox.property("dim_nr")
sliceList[dimNr] = spinBox.value()
# Make the array slicer. It needs to be a tuple, a list of only integers will be
# interpreted as an index. With a tuple, array[(exp1, exp2, ..., expN)] is equivalent to
# array[exp1, exp2, ..., expN].
# See: http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
logger.debug("Array slice list: {}".format(str(sliceList)))
slicedArray = self.rti[tuple(sliceList)]
# Make a copy to prevent inspectors from modifying the underlying array.
if copy:
slicedArray = ma.copy(slicedArray)
# If there are no comboboxes the sliceList will contain no Slices objects, only ints. Then
# the resulting slicedArray will be a usually a scalar (only structured fields may yield an
# array). We convert this scalar to a zero-dimensional Numpy array so that inspectors
# always get an array (having the same number of dimensions as the dimensionality of the
# inspector, i.e. the number of comboboxes).
if self.maxCombos == 0:
slicedArray = ma.MaskedArray(slicedArray)
# Post-condition type check
check_is_an_array(slicedArray, np.ndarray)
# Enforce the return type to be a masked array.
if not isinstance(slicedArray, ma.MaskedArray):
slicedArray = ma.MaskedArray(slicedArray)
# Add fake dimensions of length 1 so that result.ndim will equal the number of combo boxes
for dimNr in range(slicedArray.ndim, self.maxCombos):
#logger.debug("Adding fake dimension: {}".format(dimNr))
slicedArray = ma.expand_dims(slicedArray, dimNr)
# Post-condition dimension check
assert slicedArray.ndim == self.maxCombos, \
"Bug: getSlicedArray should return a {:d}D array, got: {}D" \
.format(self.maxCombos, slicedArray.ndim)
# Convert to ArrayWithMask class for working around issues with the numpy maskedarray
awm = ArrayWithMask.createFromMaskedArray(slicedArray)
del slicedArray
# Shuffle the dimensions to be in the order as specified by the combo boxes
comboDims = [self._comboBoxDimensionIndex(cb) for cb in self._comboBoxes]
permutations = np.argsort(comboDims)
logger.debug("slicedArray.shape: {}".format(awm.data.shape))
logger.debug("Transposing dimensions: {}".format(permutations))
awm = awm.transpose(permutations)
awm.checkIsConsistent()
return awm | Slice the rti using a tuple of slices made from the values of the combo and spin boxes.
:param copy: If True (the default), a copy is made so that inspectors cannot
accidentally modify the underlying of the RTIs. You can set copy=False as a
potential optimization, but only if you are absolutely sure that you don't modify
the the slicedArray in your inspector! Note that this function calls transpose,
which can still make a copy of the array for certain permutations.
:return: Numpy masked array with the same number of dimension as the number of
comboboxes (this can be zero!).
Returns None if no slice can be made (i.e. the RTI is not sliceable). | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L480-L557 |
titusjan/argos | argos/collect/collector.py | Collector.getSlicesString | def getSlicesString(self):
""" Returns a string representation of the slices that are used to get the sliced array.
For example returns '[:, 5]' if the combo box selects dimension 0 and the spin box 5.
"""
if not self.rtiIsSliceable:
return ''
# The dimensions that are selected in the combo boxes will be set to slice(None),
# the values from the spin boxes will be set as a single integer value
nDims = self.rti.nDims
sliceList = [':'] * nDims
for spinBox in self._spinBoxes:
dimNr = spinBox.property("dim_nr")
sliceList[dimNr] = str(spinBox.value())
# No need to shuffle combobox dimensions like in getSlicedArray; all combobox dimensions
# yield a colon.
return "[" + ", ".join(sliceList) + "]" | python | def getSlicesString(self):
""" Returns a string representation of the slices that are used to get the sliced array.
For example returns '[:, 5]' if the combo box selects dimension 0 and the spin box 5.
"""
if not self.rtiIsSliceable:
return ''
# The dimensions that are selected in the combo boxes will be set to slice(None),
# the values from the spin boxes will be set as a single integer value
nDims = self.rti.nDims
sliceList = [':'] * nDims
for spinBox in self._spinBoxes:
dimNr = spinBox.property("dim_nr")
sliceList[dimNr] = str(spinBox.value())
# No need to shuffle combobox dimensions like in getSlicedArray; all combobox dimensions
# yield a colon.
return "[" + ", ".join(sliceList) + "]" | Returns a string representation of the slices that are used to get the sliced array.
For example returns '[:, 5]' if the combo box selects dimension 0 and the spin box 5. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L560-L579 |
titusjan/argos | argos/collect/collector.py | Collector._updateRtiInfo | def _updateRtiInfo(self):
""" Updates the _rtiInfo property when a new RTI is set or the comboboxes value change.
"""
logger.debug("Updating self._rtiInfo")
# Info about the dependent dimension
rti = self.rti
if rti is None:
info = {'slices': '',
'name': '',
'path': '',
'file-name': '',
'dir-name': '',
'base-name': '',
'unit': '',
'raw-unit': ''}
else:
dirName, baseName = os.path.split(rti.fileName)
info = {'slices': self.getSlicesString(),
'name': rti.nodeName,
'path': rti.nodePath,
'file-name': rti.fileName,
'dir-name': dirName,
'base-name': baseName,
'unit': '({})'.format(rti.unit) if rti.unit else '',
'raw-unit': rti.unit}
# Add the info of the independent dimensions (appended with the axis name of that dim).
for axisName, comboBox in zip(self._axisNames, self._comboBoxes):
dimName = comboBox.currentText()
key = '{}-dim'.format(axisName.lower())
info[key] = dimName
self._rtiInfo = info | python | def _updateRtiInfo(self):
""" Updates the _rtiInfo property when a new RTI is set or the comboboxes value change.
"""
logger.debug("Updating self._rtiInfo")
# Info about the dependent dimension
rti = self.rti
if rti is None:
info = {'slices': '',
'name': '',
'path': '',
'file-name': '',
'dir-name': '',
'base-name': '',
'unit': '',
'raw-unit': ''}
else:
dirName, baseName = os.path.split(rti.fileName)
info = {'slices': self.getSlicesString(),
'name': rti.nodeName,
'path': rti.nodePath,
'file-name': rti.fileName,
'dir-name': dirName,
'base-name': baseName,
'unit': '({})'.format(rti.unit) if rti.unit else '',
'raw-unit': rti.unit}
# Add the info of the independent dimensions (appended with the axis name of that dim).
for axisName, comboBox in zip(self._axisNames, self._comboBoxes):
dimName = comboBox.currentText()
key = '{}-dim'.format(axisName.lower())
info[key] = dimName
self._rtiInfo = info | Updates the _rtiInfo property when a new RTI is set or the comboboxes value change. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L624-L656 |
titusjan/argos | argos/repo/memoryrtis.py | _createFromObject | def _createFromObject(obj, *args, **kwargs):
""" Creates an RTI given an object. Auto-detects which RTI class to return.
The *args and **kwargs parameters are passed to the RTI constructor.
It is therefor important that all memory RTIs accept the same parameters in the
constructor (with exception of the FieldRti which is not auto-detected).
"""
if is_a_sequence(obj):
return SequenceRti(obj, *args, **kwargs)
elif is_a_mapping(obj):
return MappingRti(obj, *args, **kwargs)
elif is_an_array(obj):
return ArrayRti(obj, *args, **kwargs)
elif isinstance(obj, bytearray):
return ArrayRti(np.array(obj), *args, **kwargs)
else:
return ScalarRti(obj, *args, **kwargs) | python | def _createFromObject(obj, *args, **kwargs):
""" Creates an RTI given an object. Auto-detects which RTI class to return.
The *args and **kwargs parameters are passed to the RTI constructor.
It is therefor important that all memory RTIs accept the same parameters in the
constructor (with exception of the FieldRti which is not auto-detected).
"""
if is_a_sequence(obj):
return SequenceRti(obj, *args, **kwargs)
elif is_a_mapping(obj):
return MappingRti(obj, *args, **kwargs)
elif is_an_array(obj):
return ArrayRti(obj, *args, **kwargs)
elif isinstance(obj, bytearray):
return ArrayRti(np.array(obj), *args, **kwargs)
else:
return ScalarRti(obj, *args, **kwargs) | Creates an RTI given an object. Auto-detects which RTI class to return.
The *args and **kwargs parameters are passed to the RTI constructor.
It is therefor important that all memory RTIs accept the same parameters in the
constructor (with exception of the FieldRti which is not auto-detected). | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L33-L48 |
titusjan/argos | argos/repo/memoryrtis.py | FieldRti._subArrayShape | def _subArrayShape(self):
""" Returns the shape of the sub-array.
An empty tuple is returned for regular fields, which have no sub array.
"""
fieldName = self.nodeName
fieldDtype = self._array.dtype.fields[fieldName][0]
return fieldDtype.shape | python | def _subArrayShape(self):
""" Returns the shape of the sub-array.
An empty tuple is returned for regular fields, which have no sub array.
"""
fieldName = self.nodeName
fieldDtype = self._array.dtype.fields[fieldName][0]
return fieldDtype.shape | Returns the shape of the sub-array.
An empty tuple is returned for regular fields, which have no sub array. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L198-L204 |
titusjan/argos | argos/repo/memoryrtis.py | FieldRti.elementTypeName | def elementTypeName(self):
""" String representation of the element type.
"""
if self._array is None:
return super(FieldRti, self).elementTypeName
else:
fieldName = self.nodeName
return str(self._array.dtype.fields[fieldName][0]) | python | def elementTypeName(self):
""" String representation of the element type.
"""
if self._array is None:
return super(FieldRti, self).elementTypeName
else:
fieldName = self.nodeName
return str(self._array.dtype.fields[fieldName][0]) | String representation of the element type. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L216-L223 |
titusjan/argos | argos/repo/memoryrtis.py | FieldRti.dimensionNames | def dimensionNames(self):
""" Returns a list with the dimension names of the underlying NCDF variable
"""
mainArrayDims = ['Dim{}'.format(dimNr) for dimNr in range(self._array.ndim)]
nSubDims = len(self._subArrayShape)
subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)]
return mainArrayDims + subArrayDims | python | def dimensionNames(self):
""" Returns a list with the dimension names of the underlying NCDF variable
"""
mainArrayDims = ['Dim{}'.format(dimNr) for dimNr in range(self._array.ndim)]
nSubDims = len(self._subArrayShape)
subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)]
return mainArrayDims + subArrayDims | Returns a list with the dimension names of the underlying NCDF variable | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L227-L233 |
titusjan/argos | argos/repo/memoryrtis.py | FieldRti.missingDataValue | def missingDataValue(self):
""" Returns the value to indicate missing data.
"""
value = getMissingDataValue(self._array)
fieldNames = self._array.dtype.names
# If the missing value attibute is a list with the same length as the number of fields,
# return the missing value for field that equals the self.nodeName.
if hasattr(value, '__len__') and len(value) == len(fieldNames):
idx = fieldNames.index(self.nodeName)
return value[idx]
else:
return value | python | def missingDataValue(self):
""" Returns the value to indicate missing data.
"""
value = getMissingDataValue(self._array)
fieldNames = self._array.dtype.names
# If the missing value attibute is a list with the same length as the number of fields,
# return the missing value for field that equals the self.nodeName.
if hasattr(value, '__len__') and len(value) == len(fieldNames):
idx = fieldNames.index(self.nodeName)
return value[idx]
else:
return value | Returns the value to indicate missing data. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L237-L249 |
titusjan/argos | argos/repo/memoryrtis.py | ArrayRti.elementTypeName | def elementTypeName(self):
""" String representation of the element type.
"""
if self._array is None:
return super(ArrayRti, self).elementTypeName
else:
dtype = self._array.dtype
return '<structured>' if dtype.names else str(dtype) | python | def elementTypeName(self):
""" String representation of the element type.
"""
if self._array is None:
return super(ArrayRti, self).elementTypeName
else:
dtype = self._array.dtype
return '<structured>' if dtype.names else str(dtype) | String representation of the element type. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L328-L335 |
titusjan/argos | argos/repo/memoryrtis.py | ArrayRti._fetchAllChildren | def _fetchAllChildren(self):
""" Fetches all fields that this variable contains.
Only variables with a structured data type can have fields.
"""
assert self.canFetchChildren(), "canFetchChildren must be True"
childItems = []
# Add fields in case of an array of structured type.
if self._isStructured:
for fieldName in self._array.dtype.names:
childItem = FieldRti(self._array, nodeName=fieldName, fileName=self.fileName)
childItem._iconColor = self.iconColor
childItems.append(childItem)
return childItems | python | def _fetchAllChildren(self):
""" Fetches all fields that this variable contains.
Only variables with a structured data type can have fields.
"""
assert self.canFetchChildren(), "canFetchChildren must be True"
childItems = []
# Add fields in case of an array of structured type.
if self._isStructured:
for fieldName in self._array.dtype.names:
childItem = FieldRti(self._array, nodeName=fieldName, fileName=self.fileName)
childItem._iconColor = self.iconColor
childItems.append(childItem)
return childItems | Fetches all fields that this variable contains.
Only variables with a structured data type can have fields. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L345-L360 |
titusjan/argos | argos/repo/memoryrtis.py | SyntheticArrayRti._openResources | def _openResources(self):
""" Evaluates the function to result an array
"""
arr = self._fun()
check_is_an_array(arr)
self._array = arr | python | def _openResources(self):
""" Evaluates the function to result an array
"""
arr = self._fun()
check_is_an_array(arr)
self._array = arr | Evaluates the function to result an array | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L400-L405 |
titusjan/argos | argos/repo/memoryrtis.py | SequenceRti._fetchAllChildren | def _fetchAllChildren(self):
""" Adds a child item for each column
"""
childItems = []
for nr, elem in enumerate(self._sequence):
childItem = _createFromObject(elem, "elem-{}".format(nr), self.fileName)
childItem._iconColor = self.iconColor
childItems.append(childItem)
return childItems | python | def _fetchAllChildren(self):
""" Adds a child item for each column
"""
childItems = []
for nr, elem in enumerate(self._sequence):
childItem = _createFromObject(elem, "elem-{}".format(nr), self.fileName)
childItem._iconColor = self.iconColor
childItems.append(childItem)
return childItems | Adds a child item for each column | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L450-L458 |
titusjan/argos | argos/repo/memoryrtis.py | MappingRti._fetchAllChildren | def _fetchAllChildren(self):
""" Adds a child item for each item
"""
childItems = []
logger.debug("{!r} _fetchAllChildren {!r}".format(self, self.fileName))
if self.hasChildren():
for key, value in sorted(self._dictionary.items()):
# TODO: pass the attributes to the children? (probably not)
childItem = _createFromObject(value, str(key), self.fileName)
childItem._iconColor = self.iconColor
childItems.append(childItem)
return childItems | python | def _fetchAllChildren(self):
""" Adds a child item for each item
"""
childItems = []
logger.debug("{!r} _fetchAllChildren {!r}".format(self, self.fileName))
if self.hasChildren():
for key, value in sorted(self._dictionary.items()):
# TODO: pass the attributes to the children? (probably not)
childItem = _createFromObject(value, str(key), self.fileName)
childItem._iconColor = self.iconColor
childItems.append(childItem)
return childItems | Adds a child item for each item | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/memoryrtis.py#L499-L512 |
titusjan/argos | argos/config/intcti.py | IntCti.debugInfo | def debugInfo(self):
""" Returns the string with debugging information
"""
return ("enabled = {}, min = {}, max = {}, step = {}, specVal = {}"
.format(self.enabled, self.minValue, self.maxValue, self.stepSize, self.specialValueText)) | python | def debugInfo(self):
""" Returns the string with debugging information
"""
return ("enabled = {}, min = {}, max = {}, step = {}, specVal = {}"
.format(self.enabled, self.minValue, self.maxValue, self.stepSize, self.specialValueText)) | Returns the string with debugging information | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/intcti.py#L73-L77 |
titusjan/argos | argos/config/intcti.py | IntCti.createEditor | def createEditor(self, delegate, parent, option):
""" Creates a IntCtiEditor.
For the parameters see the AbstractCti constructor documentation.
"""
return IntCtiEditor(self, delegate, parent=parent) | python | def createEditor(self, delegate, parent, option):
""" Creates a IntCtiEditor.
For the parameters see the AbstractCti constructor documentation.
"""
return IntCtiEditor(self, delegate, parent=parent) | Creates a IntCtiEditor.
For the parameters see the AbstractCti constructor documentation. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/intcti.py#L80-L84 |
titusjan/argos | argos/config/intcti.py | IntCtiEditor.finalize | def finalize(self):
""" Called at clean up. Is used to disconnect signals.
"""
self.spinBox.valueChanged.disconnect(self.commitChangedValue)
super(IntCtiEditor, self).finalize() | python | def finalize(self):
""" Called at clean up. Is used to disconnect signals.
"""
self.spinBox.valueChanged.disconnect(self.commitChangedValue)
super(IntCtiEditor, self).finalize() | Called at clean up. Is used to disconnect signals. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/intcti.py#L120-L124 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.finalize | def finalize(self):
""" Is called before destruction (when closing).
Can be used to clean-up resources.
"""
logger.debug("Finalizing: {}".format(self))
# Disconnect signals
self.collector.sigContentsChanged.disconnect(self.collectorContentsChanged)
self._configTreeModel.sigItemChanged.disconnect(self.configContentsChanged)
self.sigInspectorChanged.disconnect(self.inspectorSelectionPane.updateFromInspectorRegItem)
self.customContextMenuRequested.disconnect(self.showContextMenu) | python | def finalize(self):
""" Is called before destruction (when closing).
Can be used to clean-up resources.
"""
logger.debug("Finalizing: {}".format(self))
# Disconnect signals
self.collector.sigContentsChanged.disconnect(self.collectorContentsChanged)
self._configTreeModel.sigItemChanged.disconnect(self.configContentsChanged)
self.sigInspectorChanged.disconnect(self.inspectorSelectionPane.updateFromInspectorRegItem)
self.customContextMenuRequested.disconnect(self.showContextMenu) | Is called before destruction (when closing).
Can be used to clean-up resources. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L105-L115 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.__setupViews | def __setupViews(self):
""" Creates the UI widgets.
"""
self._collector = Collector(self.windowNumber)
self.configWidget = ConfigWidget(self._configTreeModel)
self.repoWidget = RepoWidget(self.argosApplication.repo, self.collector)
# self._configTreeModel.insertItem(self.repoWidget.repoTreeView.config) # No configurable items yet
# Define a central widget that will be the parent of the inspector widget.
# We don't set the inspector directly as the central widget to retain the size when the
# inspector is changed.
widget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(widget)
layout.setContentsMargins(CENTRAL_MARGIN, CENTRAL_MARGIN, CENTRAL_MARGIN, CENTRAL_MARGIN)
layout.setSpacing(CENTRAL_SPACING)
self.setCentralWidget(widget)
# Must be after setInspector since that already draws the inspector
self.collector.sigContentsChanged.connect(self.collectorContentsChanged)
self._configTreeModel.sigItemChanged.connect(self.configContentsChanged) | python | def __setupViews(self):
""" Creates the UI widgets.
"""
self._collector = Collector(self.windowNumber)
self.configWidget = ConfigWidget(self._configTreeModel)
self.repoWidget = RepoWidget(self.argosApplication.repo, self.collector)
# self._configTreeModel.insertItem(self.repoWidget.repoTreeView.config) # No configurable items yet
# Define a central widget that will be the parent of the inspector widget.
# We don't set the inspector directly as the central widget to retain the size when the
# inspector is changed.
widget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(widget)
layout.setContentsMargins(CENTRAL_MARGIN, CENTRAL_MARGIN, CENTRAL_MARGIN, CENTRAL_MARGIN)
layout.setSpacing(CENTRAL_SPACING)
self.setCentralWidget(widget)
# Must be after setInspector since that already draws the inspector
self.collector.sigContentsChanged.connect(self.collectorContentsChanged)
self._configTreeModel.sigItemChanged.connect(self.configContentsChanged) | Creates the UI widgets. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L118-L137 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.__setupMenus | def __setupMenus(self):
""" Sets up the main menu.
"""
if True:
# Don't use self.menuBar(), on OS-X this is not shared across windows.
# See: http://qt-project.org/doc/qt-4.8/qmenubar.html#details
# And:http://qt-project.org/doc/qt-4.8/qmainwindow.html#menuBar
menuBar = QtWidgets.QMenuBar() # Make a menu without parent.
self.setMenuBar(menuBar)
else:
menuBar = self.menuBar()
### File Menu ###
fileMenu = menuBar.addMenu("&File")
fileMenu.addAction("&New Window", self.cloneWindow, QtGui.QKeySequence("Ctrl+N"))
fileMenu.addAction("Close &Window", self.close, QtGui.QKeySequence.Close)
fileMenu.addSeparator()
action = fileMenu.addAction("Browse Directory...",
lambda: self.openFiles(fileMode = QtWidgets.QFileDialog.Directory))
action.setShortcut(QtGui.QKeySequence("Ctrl+B"))
action = fileMenu.addAction("&Open Files...",
lambda: self.openFiles(fileMode = QtWidgets.QFileDialog.ExistingFiles))
action.setShortcut(QtGui.QKeySequence("Ctrl+O"))
openAsMenu = fileMenu.addMenu("Open As")
for rtiRegItem in self.argosApplication.rtiRegistry.items:
#rtiRegItem.tryImportClass()
def createTrigger():
"Function to create a closure with the regItem"
_rtiRegItem = rtiRegItem # keep reference in closure
return lambda: self.openFiles(rtiRegItem=_rtiRegItem,
fileMode = QtWidgets.QFileDialog.ExistingFiles,
caption="Open {}".format(_rtiRegItem.name))
action = QtWidgets.QAction("{}...".format(rtiRegItem.name), self,
enabled=True, # Since this is only executed at start-up, it must be static
#enabled=bool(rtiRegItem.successfullyImported), # TODO: make this work?
triggered=createTrigger())
openAsMenu.addAction(action)
fileMenu.addSeparator()
# for action in self.repoWidget.repoTreeView.topLevelItemActionGroup.actions():
# fileMenu.addAction(action)
#
# for action in self.repoWidget.repoTreeView.currentItemActionGroup.actions():
# fileMenu.addAction(action)
fileMenu.addSeparator()
fileMenu.addAction("E&xit", self.argosApplication.closeAllWindows, QtGui.QKeySequence.Quit)
### View Menu ###
self.viewMenu = menuBar.addMenu("&View")
action = self.viewMenu.addAction("Installed &Plugins...", self.execPluginsDialog)
action.setShortcut(QtGui.QKeySequence("Ctrl+P"))
self.viewMenu.addSeparator()
### Inspector Menu ###
self.execInspectorDialogAction = QtWidgets.QAction("&Browse Inspectors...", self,
triggered=self.execInspectorDialog)
self.execInspectorDialogAction.setShortcut(QtGui.QKeySequence("Ctrl+i"))
self.inspectorActionGroup = self.__createInspectorActionGroup(self)
self.inspectorMenu = menuBar.addMenu("Inspector")
addInspectorActionsToMenu(self.inspectorMenu, self.execInspectorDialogAction,
self.inspectorActionGroup)
### Window Menu ###
self.windowMenu = menuBar.addMenu("&Window")
# The action added to the menu in the repopulateWindowMenu method, which is called by
# the ArgosApplication object every time a window is added or removed.
self.activateWindowAction = QtWidgets.QAction("Window #{}".format(self.windowNumber),
self, triggered=self.activateAndRaise,
checkable=True)
if self.windowNumber <= 9:
self.activateWindowAction.setShortcut(QtGui.QKeySequence("Alt+{}"
.format(self.windowNumber)))
### Help Menu ###
menuBar.addSeparator()
helpMenu = menuBar.addMenu("&Help")
helpMenu.addAction('&About...', self.about)
if DEBUGGING:
helpMenu.addSeparator()
helpMenu.addAction("&Test", self.myTest, "Alt+T")
helpMenu.addAction("Add Test Data", self.addTestData, "Alt+A")
### Context menu ###
# Note that the dock-widgets have a Qt.PreventContextMenu context menu policy.
# Therefor the context menu is only shown in the center widget.
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showContextMenu) | python | def __setupMenus(self):
""" Sets up the main menu.
"""
if True:
# Don't use self.menuBar(), on OS-X this is not shared across windows.
# See: http://qt-project.org/doc/qt-4.8/qmenubar.html#details
# And:http://qt-project.org/doc/qt-4.8/qmainwindow.html#menuBar
menuBar = QtWidgets.QMenuBar() # Make a menu without parent.
self.setMenuBar(menuBar)
else:
menuBar = self.menuBar()
### File Menu ###
fileMenu = menuBar.addMenu("&File")
fileMenu.addAction("&New Window", self.cloneWindow, QtGui.QKeySequence("Ctrl+N"))
fileMenu.addAction("Close &Window", self.close, QtGui.QKeySequence.Close)
fileMenu.addSeparator()
action = fileMenu.addAction("Browse Directory...",
lambda: self.openFiles(fileMode = QtWidgets.QFileDialog.Directory))
action.setShortcut(QtGui.QKeySequence("Ctrl+B"))
action = fileMenu.addAction("&Open Files...",
lambda: self.openFiles(fileMode = QtWidgets.QFileDialog.ExistingFiles))
action.setShortcut(QtGui.QKeySequence("Ctrl+O"))
openAsMenu = fileMenu.addMenu("Open As")
for rtiRegItem in self.argosApplication.rtiRegistry.items:
#rtiRegItem.tryImportClass()
def createTrigger():
"Function to create a closure with the regItem"
_rtiRegItem = rtiRegItem # keep reference in closure
return lambda: self.openFiles(rtiRegItem=_rtiRegItem,
fileMode = QtWidgets.QFileDialog.ExistingFiles,
caption="Open {}".format(_rtiRegItem.name))
action = QtWidgets.QAction("{}...".format(rtiRegItem.name), self,
enabled=True, # Since this is only executed at start-up, it must be static
#enabled=bool(rtiRegItem.successfullyImported), # TODO: make this work?
triggered=createTrigger())
openAsMenu.addAction(action)
fileMenu.addSeparator()
# for action in self.repoWidget.repoTreeView.topLevelItemActionGroup.actions():
# fileMenu.addAction(action)
#
# for action in self.repoWidget.repoTreeView.currentItemActionGroup.actions():
# fileMenu.addAction(action)
fileMenu.addSeparator()
fileMenu.addAction("E&xit", self.argosApplication.closeAllWindows, QtGui.QKeySequence.Quit)
### View Menu ###
self.viewMenu = menuBar.addMenu("&View")
action = self.viewMenu.addAction("Installed &Plugins...", self.execPluginsDialog)
action.setShortcut(QtGui.QKeySequence("Ctrl+P"))
self.viewMenu.addSeparator()
### Inspector Menu ###
self.execInspectorDialogAction = QtWidgets.QAction("&Browse Inspectors...", self,
triggered=self.execInspectorDialog)
self.execInspectorDialogAction.setShortcut(QtGui.QKeySequence("Ctrl+i"))
self.inspectorActionGroup = self.__createInspectorActionGroup(self)
self.inspectorMenu = menuBar.addMenu("Inspector")
addInspectorActionsToMenu(self.inspectorMenu, self.execInspectorDialogAction,
self.inspectorActionGroup)
### Window Menu ###
self.windowMenu = menuBar.addMenu("&Window")
# The action added to the menu in the repopulateWindowMenu method, which is called by
# the ArgosApplication object every time a window is added or removed.
self.activateWindowAction = QtWidgets.QAction("Window #{}".format(self.windowNumber),
self, triggered=self.activateAndRaise,
checkable=True)
if self.windowNumber <= 9:
self.activateWindowAction.setShortcut(QtGui.QKeySequence("Alt+{}"
.format(self.windowNumber)))
### Help Menu ###
menuBar.addSeparator()
helpMenu = menuBar.addMenu("&Help")
helpMenu.addAction('&About...', self.about)
if DEBUGGING:
helpMenu.addSeparator()
helpMenu.addAction("&Test", self.myTest, "Alt+T")
helpMenu.addAction("Add Test Data", self.addTestData, "Alt+A")
### Context menu ###
# Note that the dock-widgets have a Qt.PreventContextMenu context menu policy.
# Therefor the context menu is only shown in the center widget.
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showContextMenu) | Sets up the main menu. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L140-L238 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.__createInspectorActionGroup | def __createInspectorActionGroup(self, parent):
""" Creates an action group with 'set inspector' actions for all installed inspector.
"""
actionGroup = QtWidgets.QActionGroup(parent)
actionGroup.setExclusive(True)
sortedItems = sorted(self.argosApplication.inspectorRegistry.items,
key=lambda item: item.identifier)
shortCutNr = 1
for item in sortedItems:
logger.debug("item: {}".format(item.identifier))
setAndDrawFn = partial(self.setAndDrawInspectorById, item.identifier)
action = QtWidgets.QAction(item.name, self, triggered=setAndDrawFn, checkable=True)
action.setData(item.identifier)
if shortCutNr <= 9 and "debug" not in item.identifier: # TODO: make configurable by the user
action.setShortcut(QtGui.QKeySequence("Ctrl+{}".format(shortCutNr)))
shortCutNr += 1
actionGroup.addAction(action)
return actionGroup | python | def __createInspectorActionGroup(self, parent):
""" Creates an action group with 'set inspector' actions for all installed inspector.
"""
actionGroup = QtWidgets.QActionGroup(parent)
actionGroup.setExclusive(True)
sortedItems = sorted(self.argosApplication.inspectorRegistry.items,
key=lambda item: item.identifier)
shortCutNr = 1
for item in sortedItems:
logger.debug("item: {}".format(item.identifier))
setAndDrawFn = partial(self.setAndDrawInspectorById, item.identifier)
action = QtWidgets.QAction(item.name, self, triggered=setAndDrawFn, checkable=True)
action.setData(item.identifier)
if shortCutNr <= 9 and "debug" not in item.identifier: # TODO: make configurable by the user
action.setShortcut(QtGui.QKeySequence("Ctrl+{}".format(shortCutNr)))
shortCutNr += 1
actionGroup.addAction(action)
return actionGroup | Creates an action group with 'set inspector' actions for all installed inspector. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L241-L261 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.__setupDockWidgets | def __setupDockWidgets(self):
""" Sets up the dock widgets. Must be called after the menu is setup.
"""
#self.dockWidget(self.currentInspectorPane, "Current Inspector", Qt.LeftDockWidgetArea)
self.inspectorSelectionPane = InspectorSelectionPane(self.execInspectorDialogAction,
self.inspectorActionGroup)
self.sigInspectorChanged.connect(self.inspectorSelectionPane.updateFromInspectorRegItem)
self.dockWidget(self.inspectorSelectionPane, "Current Inspector",
area=Qt.LeftDockWidgetArea)
self.dockWidget(self.repoWidget, "Data Repository", Qt.LeftDockWidgetArea)
self.dockWidget(self.collector, "Data Collector", Qt.TopDockWidgetArea)
# TODO: if the title == "Settings" it won't be added to the view menu.
self.dockWidget(self.configWidget, "Application Settings", Qt.RightDockWidgetArea)
self.viewMenu.addSeparator()
propertiesPane = PropertiesPane(self.repoWidget.repoTreeView)
self.dockDetailPane(propertiesPane, area=Qt.LeftDockWidgetArea)
attributesPane = AttributesPane(self.repoWidget.repoTreeView)
self.dockDetailPane(attributesPane, area=Qt.LeftDockWidgetArea)
dimensionsPane = DimensionsPane(self.repoWidget.repoTreeView)
self.dockDetailPane(dimensionsPane, area=Qt.LeftDockWidgetArea)
# Add am extra separator on mac because OS-X adds an 'Enter Full Screen' item
if sys.platform.startswith('darwin'):
self.viewMenu.addSeparator() | python | def __setupDockWidgets(self):
""" Sets up the dock widgets. Must be called after the menu is setup.
"""
#self.dockWidget(self.currentInspectorPane, "Current Inspector", Qt.LeftDockWidgetArea)
self.inspectorSelectionPane = InspectorSelectionPane(self.execInspectorDialogAction,
self.inspectorActionGroup)
self.sigInspectorChanged.connect(self.inspectorSelectionPane.updateFromInspectorRegItem)
self.dockWidget(self.inspectorSelectionPane, "Current Inspector",
area=Qt.LeftDockWidgetArea)
self.dockWidget(self.repoWidget, "Data Repository", Qt.LeftDockWidgetArea)
self.dockWidget(self.collector, "Data Collector", Qt.TopDockWidgetArea)
# TODO: if the title == "Settings" it won't be added to the view menu.
self.dockWidget(self.configWidget, "Application Settings", Qt.RightDockWidgetArea)
self.viewMenu.addSeparator()
propertiesPane = PropertiesPane(self.repoWidget.repoTreeView)
self.dockDetailPane(propertiesPane, area=Qt.LeftDockWidgetArea)
attributesPane = AttributesPane(self.repoWidget.repoTreeView)
self.dockDetailPane(attributesPane, area=Qt.LeftDockWidgetArea)
dimensionsPane = DimensionsPane(self.repoWidget.repoTreeView)
self.dockDetailPane(dimensionsPane, area=Qt.LeftDockWidgetArea)
# Add am extra separator on mac because OS-X adds an 'Enter Full Screen' item
if sys.platform.startswith('darwin'):
self.viewMenu.addSeparator() | Sets up the dock widgets. Must be called after the menu is setup. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L264-L293 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.repopulateWinowMenu | def repopulateWinowMenu(self, actionGroup):
""" Clear the window menu and fills it with the actions of the actionGroup
"""
for action in self.windowMenu.actions():
self.windowMenu.removeAction(action)
for action in actionGroup.actions():
self.windowMenu.addAction(action) | python | def repopulateWinowMenu(self, actionGroup):
""" Clear the window menu and fills it with the actions of the actionGroup
"""
for action in self.windowMenu.actions():
self.windowMenu.removeAction(action)
for action in actionGroup.actions():
self.windowMenu.addAction(action) | Clear the window menu and fills it with the actions of the actionGroup | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L355-L362 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.showContextMenu | def showContextMenu(self, pos):
""" Shows the context menu at position pos.
"""
contextMenu = QtWidgets.QMenu()
addInspectorActionsToMenu(contextMenu, self.execInspectorDialogAction,
self.inspectorActionGroup)
contextMenu.exec_(self.mapToGlobal(pos)) | python | def showContextMenu(self, pos):
""" Shows the context menu at position pos.
"""
contextMenu = QtWidgets.QMenu()
addInspectorActionsToMenu(contextMenu, self.execInspectorDialogAction,
self.inspectorActionGroup)
contextMenu.exec_(self.mapToGlobal(pos)) | Shows the context menu at position pos. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L365-L371 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.dockWidget | def dockWidget(self, widget, title, area):
""" Adds a widget as a docked widget.
Returns the added dockWidget
"""
assert widget.parent() is None, "Widget already has a parent"
dockWidget = QtWidgets.QDockWidget(title, parent=self)
dockWidget.setObjectName("dock_" + string_to_identifier(title))
dockWidget.setWidget(widget)
# Prevent parent context menu (with e.g. 'set inspector" option) to be displayed.
dockWidget.setContextMenuPolicy(Qt.PreventContextMenu)
self.addDockWidget(area, dockWidget)
self.viewMenu.addAction(dockWidget.toggleViewAction())
return dockWidget | python | def dockWidget(self, widget, title, area):
""" Adds a widget as a docked widget.
Returns the added dockWidget
"""
assert widget.parent() is None, "Widget already has a parent"
dockWidget = QtWidgets.QDockWidget(title, parent=self)
dockWidget.setObjectName("dock_" + string_to_identifier(title))
dockWidget.setWidget(widget)
# Prevent parent context menu (with e.g. 'set inspector" option) to be displayed.
dockWidget.setContextMenuPolicy(Qt.PreventContextMenu)
self.addDockWidget(area, dockWidget)
self.viewMenu.addAction(dockWidget.toggleViewAction())
return dockWidget | Adds a widget as a docked widget.
Returns the added dockWidget | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L374-L389 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.dockDetailPane | def dockDetailPane(self, detailPane, title=None, area=None):
""" Creates a dockWidget and add the detailPane with a default title.
By default the detail widget is added to the Qt.LeftDockWidgetArea.
"""
title = detailPane.classLabel() if title is None else title
area = Qt.LeftDockWidgetArea if area is None else area
dockWidget = self.dockWidget(detailPane, title, area)
# TODO: undockDetailPane to disconnect
dockWidget.visibilityChanged.connect(detailPane.dockVisibilityChanged)
if len(self._detailDockWidgets) > 0:
self.tabifyDockWidget(self._detailDockWidgets[-1], dockWidget)
self._detailDockWidgets.append(dockWidget)
return dockWidget | python | def dockDetailPane(self, detailPane, title=None, area=None):
""" Creates a dockWidget and add the detailPane with a default title.
By default the detail widget is added to the Qt.LeftDockWidgetArea.
"""
title = detailPane.classLabel() if title is None else title
area = Qt.LeftDockWidgetArea if area is None else area
dockWidget = self.dockWidget(detailPane, title, area)
# TODO: undockDetailPane to disconnect
dockWidget.visibilityChanged.connect(detailPane.dockVisibilityChanged)
if len(self._detailDockWidgets) > 0:
self.tabifyDockWidget(self._detailDockWidgets[-1], dockWidget)
self._detailDockWidgets.append(dockWidget)
return dockWidget | Creates a dockWidget and add the detailPane with a default title.
By default the detail widget is added to the Qt.LeftDockWidgetArea. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L392-L404 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.updateWindowTitle | def updateWindowTitle(self):
""" Updates the window title frm the window number, inspector, etc
Also updates the Window Menu
"""
self.setWindowTitle("{} #{} | {}-{}".format(self.inspectorName, self.windowNumber,
PROJECT_NAME, self.argosApplication.profile))
#self.activateWindowAction.setText("{} window".format(self.inspectorName, self.windowNumber))
self.activateWindowAction.setText("{} window".format(self.inspectorName)) | python | def updateWindowTitle(self):
""" Updates the window title frm the window number, inspector, etc
Also updates the Window Menu
"""
self.setWindowTitle("{} #{} | {}-{}".format(self.inspectorName, self.windowNumber,
PROJECT_NAME, self.argosApplication.profile))
#self.activateWindowAction.setText("{} window".format(self.inspectorName, self.windowNumber))
self.activateWindowAction.setText("{} window".format(self.inspectorName)) | Updates the window title frm the window number, inspector, etc
Also updates the Window Menu | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L407-L414 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.execInspectorDialog | def execInspectorDialog(self):
""" Opens the inspector dialog box to let the user change the current inspector.
"""
dialog = OpenInspectorDialog(self.argosApplication.inspectorRegistry, parent=self)
dialog.setCurrentInspectorRegItem(self.inspectorRegItem)
dialog.exec_()
if dialog.result():
inspectorRegItem = dialog.getCurrentInspectorRegItem()
if inspectorRegItem is not None:
self.getInspectorActionById(inspectorRegItem.identifier).trigger() | python | def execInspectorDialog(self):
""" Opens the inspector dialog box to let the user change the current inspector.
"""
dialog = OpenInspectorDialog(self.argosApplication.inspectorRegistry, parent=self)
dialog.setCurrentInspectorRegItem(self.inspectorRegItem)
dialog.exec_()
if dialog.result():
inspectorRegItem = dialog.getCurrentInspectorRegItem()
if inspectorRegItem is not None:
self.getInspectorActionById(inspectorRegItem.identifier).trigger() | Opens the inspector dialog box to let the user change the current inspector. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L418-L427 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.getInspectorActionById | def getInspectorActionById(self, identifier):
""" Sets the inspector and draw the contents
Triggers the corresponding action so that it is checked in the menus.
"""
for action in self.inspectorActionGroup.actions():
if action.data() == identifier:
return action
raise KeyError("No action found with ID: {!r}".format(identifier)) | python | def getInspectorActionById(self, identifier):
""" Sets the inspector and draw the contents
Triggers the corresponding action so that it is checked in the menus.
"""
for action in self.inspectorActionGroup.actions():
if action.data() == identifier:
return action
raise KeyError("No action found with ID: {!r}".format(identifier)) | Sets the inspector and draw the contents
Triggers the corresponding action so that it is checked in the menus. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L430-L437 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.setAndDrawInspectorById | def setAndDrawInspectorById(self, identifier):
""" Sets the inspector and draw the contents.
Does NOT trigger any actions, so the check marks in the menus are not updated. To
achieve this, the user must update the actions by hand (or call
getInspectorActionById(identifier).trigger() instead).
"""
self.setInspectorById(identifier)
# Show dialog box if import was unsuccessful.
regItem = self.inspectorRegItem
if regItem and not regItem.successfullyImported:
msg = "Unable to import {} inspector.\n{}".format(regItem.identifier, regItem.exception)
QtWidgets.QMessageBox.warning(self, "Warning", msg)
logger.warn(msg)
self.drawInspectorContents(reason=UpdateReason.INSPECTOR_CHANGED) | python | def setAndDrawInspectorById(self, identifier):
""" Sets the inspector and draw the contents.
Does NOT trigger any actions, so the check marks in the menus are not updated. To
achieve this, the user must update the actions by hand (or call
getInspectorActionById(identifier).trigger() instead).
"""
self.setInspectorById(identifier)
# Show dialog box if import was unsuccessful.
regItem = self.inspectorRegItem
if regItem and not regItem.successfullyImported:
msg = "Unable to import {} inspector.\n{}".format(regItem.identifier, regItem.exception)
QtWidgets.QMessageBox.warning(self, "Warning", msg)
logger.warn(msg)
self.drawInspectorContents(reason=UpdateReason.INSPECTOR_CHANGED) | Sets the inspector and draw the contents.
Does NOT trigger any actions, so the check marks in the menus are not updated. To
achieve this, the user must update the actions by hand (or call
getInspectorActionById(identifier).trigger() instead). | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L440-L456 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.setInspectorById | def setInspectorById(self, identifier):
""" Sets the central inspector widget given a inspector ID.
If identifier is None, the inspector will be unset. Otherwise it will lookup the
inspector class in the registry. It will raise a KeyError if the ID is not found there.
It will do an import of the inspector code if it's loaded for the first time. If the
the inspector class cannot be imported a warning is logged and the inspector is unset.
NOTE: does not draw the new inspector, this is the responsibility of the caller.
Also, the corresponding action is not triggered.
Emits the sigInspectorChanged(self.inspectorRegItem)
"""
logger.info("Setting inspector: {}".format(identifier))
# Use the identifier to find a registered inspector and set self.inspectorRegItem.
# Then create an inspector object from it.
oldInspectorRegItem = self.inspectorRegItem
oldInspector = self.inspector
if not identifier:
inspector = None
self._inspectorRegItem = None
else:
inspectorRegistry = self.argosApplication.inspectorRegistry
inspectorRegItem = inspectorRegistry.getItemById(identifier)
self._inspectorRegItem = inspectorRegItem
if inspectorRegItem is None:
inspector = None
else:
try:
inspector = inspectorRegItem.create(self.collector, tryImport=True)
except ImportError as ex:
# Only log the error. No dialog box or user interaction here because this
# function may be called at startup.
logger.exception("Clearing inspector. Unable to create {!r} because {}"
.format(inspectorRegItem.identifier, ex))
inspector = None
self.getInspectorActionById(identifier).setEnabled(False)
if DEBUGGING:
raise
######################
# Set self.inspector #
######################
check_class(inspector, AbstractInspector, allow_none=True)
logger.debug("Disabling updates.")
self.setUpdatesEnabled(False)
try:
centralLayout = self.centralWidget().layout()
# Delete old inspector
if oldInspector is None: # can be None at start-up
oldConfigPosition = None # Last top level element in the config tree.
else:
self._updateNonDefaultsForInspector(oldInspectorRegItem, oldInspector)
# Remove old inspector configuration from tree
oldConfigPosition = oldInspector.config.childNumber()
configPath = oldInspector.config.nodePath
_, oldConfigIndex = self._configTreeModel.findItemAndIndexPath(configPath)[-1]
self._configTreeModel.deleteItemAtIndex(oldConfigIndex)
oldInspector.finalize() # TODO: before removing config
centralLayout.removeWidget(oldInspector)
oldInspector.deleteLater()
# Set new inspector
self._inspector = inspector
# Update collector widgets and the config tree
oldBlockState = self.collector.blockSignals(True)
try:
if self.inspector is None:
self.collector.clearAndSetComboBoxes([])
else:
# Add and apply config values to the inspector
key = self.inspectorRegItem.identifier
nonDefaults = self._inspectorsNonDefaults.get(key, {})
logger.debug("Setting non defaults: {}".format(nonDefaults))
self.inspector.config.setValuesFromDict(nonDefaults)
self._configTreeModel.insertItem(self.inspector.config, oldConfigPosition)
self.configWidget.configTreeView.expandBranch()
self.collector.clearAndSetComboBoxes(self.inspector.axesNames())
centralLayout.addWidget(self.inspector)
finally:
self.collector.blockSignals(oldBlockState)
finally:
logger.debug("Enabling updates.")
self.setUpdatesEnabled(True)
self.updateWindowTitle()
logger.debug("Emitting sigInspectorChanged({})".format(self.inspectorRegItem))
self.sigInspectorChanged.emit(self.inspectorRegItem) | python | def setInspectorById(self, identifier):
""" Sets the central inspector widget given a inspector ID.
If identifier is None, the inspector will be unset. Otherwise it will lookup the
inspector class in the registry. It will raise a KeyError if the ID is not found there.
It will do an import of the inspector code if it's loaded for the first time. If the
the inspector class cannot be imported a warning is logged and the inspector is unset.
NOTE: does not draw the new inspector, this is the responsibility of the caller.
Also, the corresponding action is not triggered.
Emits the sigInspectorChanged(self.inspectorRegItem)
"""
logger.info("Setting inspector: {}".format(identifier))
# Use the identifier to find a registered inspector and set self.inspectorRegItem.
# Then create an inspector object from it.
oldInspectorRegItem = self.inspectorRegItem
oldInspector = self.inspector
if not identifier:
inspector = None
self._inspectorRegItem = None
else:
inspectorRegistry = self.argosApplication.inspectorRegistry
inspectorRegItem = inspectorRegistry.getItemById(identifier)
self._inspectorRegItem = inspectorRegItem
if inspectorRegItem is None:
inspector = None
else:
try:
inspector = inspectorRegItem.create(self.collector, tryImport=True)
except ImportError as ex:
# Only log the error. No dialog box or user interaction here because this
# function may be called at startup.
logger.exception("Clearing inspector. Unable to create {!r} because {}"
.format(inspectorRegItem.identifier, ex))
inspector = None
self.getInspectorActionById(identifier).setEnabled(False)
if DEBUGGING:
raise
######################
# Set self.inspector #
######################
check_class(inspector, AbstractInspector, allow_none=True)
logger.debug("Disabling updates.")
self.setUpdatesEnabled(False)
try:
centralLayout = self.centralWidget().layout()
# Delete old inspector
if oldInspector is None: # can be None at start-up
oldConfigPosition = None # Last top level element in the config tree.
else:
self._updateNonDefaultsForInspector(oldInspectorRegItem, oldInspector)
# Remove old inspector configuration from tree
oldConfigPosition = oldInspector.config.childNumber()
configPath = oldInspector.config.nodePath
_, oldConfigIndex = self._configTreeModel.findItemAndIndexPath(configPath)[-1]
self._configTreeModel.deleteItemAtIndex(oldConfigIndex)
oldInspector.finalize() # TODO: before removing config
centralLayout.removeWidget(oldInspector)
oldInspector.deleteLater()
# Set new inspector
self._inspector = inspector
# Update collector widgets and the config tree
oldBlockState = self.collector.blockSignals(True)
try:
if self.inspector is None:
self.collector.clearAndSetComboBoxes([])
else:
# Add and apply config values to the inspector
key = self.inspectorRegItem.identifier
nonDefaults = self._inspectorsNonDefaults.get(key, {})
logger.debug("Setting non defaults: {}".format(nonDefaults))
self.inspector.config.setValuesFromDict(nonDefaults)
self._configTreeModel.insertItem(self.inspector.config, oldConfigPosition)
self.configWidget.configTreeView.expandBranch()
self.collector.clearAndSetComboBoxes(self.inspector.axesNames())
centralLayout.addWidget(self.inspector)
finally:
self.collector.blockSignals(oldBlockState)
finally:
logger.debug("Enabling updates.")
self.setUpdatesEnabled(True)
self.updateWindowTitle()
logger.debug("Emitting sigInspectorChanged({})".format(self.inspectorRegItem))
self.sigInspectorChanged.emit(self.inspectorRegItem) | Sets the central inspector widget given a inspector ID.
If identifier is None, the inspector will be unset. Otherwise it will lookup the
inspector class in the registry. It will raise a KeyError if the ID is not found there.
It will do an import of the inspector code if it's loaded for the first time. If the
the inspector class cannot be imported a warning is logged and the inspector is unset.
NOTE: does not draw the new inspector, this is the responsibility of the caller.
Also, the corresponding action is not triggered.
Emits the sigInspectorChanged(self.inspectorRegItem) | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L459-L559 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow._updateNonDefaultsForInspector | def _updateNonDefaultsForInspector(self, inspectorRegItem, inspector):
""" Store the (non-default) config values for the current inspector in a local dictionary.
This dictionary is later used to store value for persistence.
This function must be called after the inspector was drawn because that may update
some derived config values (e.g. ranges)
"""
if inspectorRegItem and inspector:
key = inspectorRegItem.identifier
logger.debug("_updateNonDefaultsForInspector: {} {}"
.format(key, type(inspector)))
self._inspectorsNonDefaults[key] = inspector.config.getNonDefaultsDict()
else:
logger.debug("_updateNonDefaultsForInspector: no inspector") | python | def _updateNonDefaultsForInspector(self, inspectorRegItem, inspector):
""" Store the (non-default) config values for the current inspector in a local dictionary.
This dictionary is later used to store value for persistence.
This function must be called after the inspector was drawn because that may update
some derived config values (e.g. ranges)
"""
if inspectorRegItem and inspector:
key = inspectorRegItem.identifier
logger.debug("_updateNonDefaultsForInspector: {} {}"
.format(key, type(inspector)))
self._inspectorsNonDefaults[key] = inspector.config.getNonDefaultsDict()
else:
logger.debug("_updateNonDefaultsForInspector: no inspector") | Store the (non-default) config values for the current inspector in a local dictionary.
This dictionary is later used to store value for persistence.
This function must be called after the inspector was drawn because that may update
some derived config values (e.g. ranges) | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L562-L575 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.execPluginsDialog | def execPluginsDialog(self):
""" Shows the plugins dialog with the registered plugins
"""
pluginsDialog = PluginsDialog(parent=self,
inspectorRegistry=self.argosApplication.inspectorRegistry,
rtiRegistry=self.argosApplication.rtiRegistry)
pluginsDialog.exec_() | python | def execPluginsDialog(self):
""" Shows the plugins dialog with the registered plugins
"""
pluginsDialog = PluginsDialog(parent=self,
inspectorRegistry=self.argosApplication.inspectorRegistry,
rtiRegistry=self.argosApplication.rtiRegistry)
pluginsDialog.exec_() | Shows the plugins dialog with the registered plugins | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L579-L585 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.configContentsChanged | def configContentsChanged(self, configTreeItem):
""" Slot is called when an item has been changed by setData of the ConfigTreeModel.
Will draw the window contents.
"""
logger.debug("configContentsChanged: {}".format(configTreeItem))
self.drawInspectorContents(reason=UpdateReason.CONFIG_CHANGED,
origin=configTreeItem) | python | def configContentsChanged(self, configTreeItem):
""" Slot is called when an item has been changed by setData of the ConfigTreeModel.
Will draw the window contents.
"""
logger.debug("configContentsChanged: {}".format(configTreeItem))
self.drawInspectorContents(reason=UpdateReason.CONFIG_CHANGED,
origin=configTreeItem) | Slot is called when an item has been changed by setData of the ConfigTreeModel.
Will draw the window contents. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L597-L603 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.drawInspectorContents | def drawInspectorContents(self, reason, origin=None):
""" Draws all contents of this window's inspector.
The reason and origin parameters are passed on to the inspector's updateContents method.
:param reason: string describing the reason for the redraw.
Should preferably be one of the UpdateReason enumeration class, but new values may
be used (which are then ignored by existing inspectors).
:param origin: object with extra infor on the reason
"""
logger.debug("")
logger.debug("-------- Drawing inspector of window: {} --------".format(self.windowTitle()))
if self.inspector:
self.inspector.updateContents(reason=reason, initiator=origin)
else:
logger.debug("No inspector selected")
logger.debug("Finished draw inspector.\n") | python | def drawInspectorContents(self, reason, origin=None):
""" Draws all contents of this window's inspector.
The reason and origin parameters are passed on to the inspector's updateContents method.
:param reason: string describing the reason for the redraw.
Should preferably be one of the UpdateReason enumeration class, but new values may
be used (which are then ignored by existing inspectors).
:param origin: object with extra infor on the reason
"""
logger.debug("")
logger.debug("-------- Drawing inspector of window: {} --------".format(self.windowTitle()))
if self.inspector:
self.inspector.updateContents(reason=reason, initiator=origin)
else:
logger.debug("No inspector selected")
logger.debug("Finished draw inspector.\n") | Draws all contents of this window's inspector.
The reason and origin parameters are passed on to the inspector's updateContents method.
:param reason: string describing the reason for the redraw.
Should preferably be one of the UpdateReason enumeration class, but new values may
be used (which are then ignored by existing inspectors).
:param origin: object with extra infor on the reason | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L606-L621 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.openFiles | def openFiles(self, fileNames=None, rtiRegItem=None, caption=None, fileMode=None):
""" Lets the user select on or more files and opens it.
:param fileNames: If None an open-file dialog allows the user to select files,
otherwise the files are opened directly.
:param rtiRegItem: Open the files as this type of registered RTI. None=autodetect.
:param caption: Optional caption for the file dialog.
:param fileMode: is passed to the file dialog.
:rtype fileMode: QtWidgets.QFileDialog.FileMode constant
"""
if fileNames is None:
dialog = QtWidgets.QFileDialog(self, caption=caption)
if rtiRegItem is None:
nameFilter = 'All files (*);;' # Default show all files.
nameFilter += self.argosApplication.rtiRegistry.getFileDialogFilter()
else:
nameFilter = rtiRegItem.getFileDialogFilter()
nameFilter += ';;All files (*)'
dialog.setNameFilter(nameFilter)
if fileMode:
dialog.setFileMode(fileMode)
if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
fileNames = dialog.selectedFiles()
else:
fileNames = []
fileRootIndex = None
for fileName in fileNames:
rtiClass = rtiRegItem.getClass(tryImport=True) if rtiRegItem else None
fileRootIndex = self.argosApplication.repo.loadFile(fileName, rtiClass=rtiClass)
self.repoWidget.repoTreeView.setExpanded(fileRootIndex, True)
# Select last opened file
if fileRootIndex is not None:
self.repoWidget.repoTreeView.setCurrentIndex(fileRootIndex) | python | def openFiles(self, fileNames=None, rtiRegItem=None, caption=None, fileMode=None):
""" Lets the user select on or more files and opens it.
:param fileNames: If None an open-file dialog allows the user to select files,
otherwise the files are opened directly.
:param rtiRegItem: Open the files as this type of registered RTI. None=autodetect.
:param caption: Optional caption for the file dialog.
:param fileMode: is passed to the file dialog.
:rtype fileMode: QtWidgets.QFileDialog.FileMode constant
"""
if fileNames is None:
dialog = QtWidgets.QFileDialog(self, caption=caption)
if rtiRegItem is None:
nameFilter = 'All files (*);;' # Default show all files.
nameFilter += self.argosApplication.rtiRegistry.getFileDialogFilter()
else:
nameFilter = rtiRegItem.getFileDialogFilter()
nameFilter += ';;All files (*)'
dialog.setNameFilter(nameFilter)
if fileMode:
dialog.setFileMode(fileMode)
if dialog.exec_() == QtWidgets.QFileDialog.Accepted:
fileNames = dialog.selectedFiles()
else:
fileNames = []
fileRootIndex = None
for fileName in fileNames:
rtiClass = rtiRegItem.getClass(tryImport=True) if rtiRegItem else None
fileRootIndex = self.argosApplication.repo.loadFile(fileName, rtiClass=rtiClass)
self.repoWidget.repoTreeView.setExpanded(fileRootIndex, True)
# Select last opened file
if fileRootIndex is not None:
self.repoWidget.repoTreeView.setCurrentIndex(fileRootIndex) | Lets the user select on or more files and opens it.
:param fileNames: If None an open-file dialog allows the user to select files,
otherwise the files are opened directly.
:param rtiRegItem: Open the files as this type of registered RTI. None=autodetect.
:param caption: Optional caption for the file dialog.
:param fileMode: is passed to the file dialog.
:rtype fileMode: QtWidgets.QFileDialog.FileMode constant | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L626-L663 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.trySelectRtiByPath | def trySelectRtiByPath(self, path):
""" Selects a repository tree item given a path, expanding nodes if along the way if needed.
Returns (item, index) if the path was selected successfully, else a warning is logged
and (None, None) is returned.
"""
try:
lastItem, lastIndex = self.repoWidget.repoTreeView.expandPath(path)
self.repoWidget.repoTreeView.setCurrentIndex(lastIndex)
return lastItem, lastIndex
except Exception as ex:
logger.warn("Unable to select {!r} because: {}".format(path, ex))
if DEBUGGING:
raise
return None, None | python | def trySelectRtiByPath(self, path):
""" Selects a repository tree item given a path, expanding nodes if along the way if needed.
Returns (item, index) if the path was selected successfully, else a warning is logged
and (None, None) is returned.
"""
try:
lastItem, lastIndex = self.repoWidget.repoTreeView.expandPath(path)
self.repoWidget.repoTreeView.setCurrentIndex(lastIndex)
return lastItem, lastIndex
except Exception as ex:
logger.warn("Unable to select {!r} because: {}".format(path, ex))
if DEBUGGING:
raise
return None, None | Selects a repository tree item given a path, expanding nodes if along the way if needed.
Returns (item, index) if the path was selected successfully, else a warning is logged
and (None, None) is returned. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L666-L680 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.readViewSettings | def readViewSettings(self, settings=None): # TODO: rename to readProfile?
""" Reads the persistent program settings
:param settings: optional QSettings object which can have a group already opened.
:returns: True if the header state was restored, otherwise returns False
"""
if settings is None:
settings = QtCore.QSettings()
logger.debug("Reading settings from: {}".format(settings.group()))
self.restoreGeometry(settings.value("geometry"))
self.restoreState(settings.value("state"))
self.repoWidget.repoTreeView.readViewSettings('repo_tree/header_state', settings)
self.configWidget.configTreeView.readViewSettings('config_tree/header_state', settings)
#self._configTreeModel.readModelSettings('config_model', settings)
settings.beginGroup('cfg_inspectors')
try:
for key in settings.childKeys():
json = settings.value(key)
self._inspectorsNonDefaults[key] = ctiLoads(json)
finally:
settings.endGroup()
identifier = settings.value("inspector", None)
try:
if identifier:
self.setInspectorById(identifier)
except KeyError as ex:
logger.warn("No inspector with ID {!r}.: {}".format(identifier, ex)) | python | def readViewSettings(self, settings=None): # TODO: rename to readProfile?
""" Reads the persistent program settings
:param settings: optional QSettings object which can have a group already opened.
:returns: True if the header state was restored, otherwise returns False
"""
if settings is None:
settings = QtCore.QSettings()
logger.debug("Reading settings from: {}".format(settings.group()))
self.restoreGeometry(settings.value("geometry"))
self.restoreState(settings.value("state"))
self.repoWidget.repoTreeView.readViewSettings('repo_tree/header_state', settings)
self.configWidget.configTreeView.readViewSettings('config_tree/header_state', settings)
#self._configTreeModel.readModelSettings('config_model', settings)
settings.beginGroup('cfg_inspectors')
try:
for key in settings.childKeys():
json = settings.value(key)
self._inspectorsNonDefaults[key] = ctiLoads(json)
finally:
settings.endGroup()
identifier = settings.value("inspector", None)
try:
if identifier:
self.setInspectorById(identifier)
except KeyError as ex:
logger.warn("No inspector with ID {!r}.: {}".format(identifier, ex)) | Reads the persistent program settings
:param settings: optional QSettings object which can have a group already opened.
:returns: True if the header state was restored, otherwise returns False | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L683-L713 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.saveProfile | def saveProfile(self, settings=None):
""" Writes the view settings to the persistent store
"""
self._updateNonDefaultsForInspector(self.inspectorRegItem, self.inspector)
if settings is None:
settings = QtCore.QSettings()
logger.debug("Writing settings to: {}".format(settings.group()))
settings.beginGroup('cfg_inspectors')
try:
for key, nonDefaults in self._inspectorsNonDefaults.items():
if nonDefaults:
settings.setValue(key, ctiDumps(nonDefaults))
logger.debug("Writing non defaults for {}: {}".format(key, nonDefaults))
finally:
settings.endGroup()
self.configWidget.configTreeView.saveProfile("config_tree/header_state", settings)
self.repoWidget.repoTreeView.saveProfile("repo_tree/header_state", settings)
settings.setValue("geometry", self.saveGeometry())
settings.setValue("state", self.saveState())
identifier = self.inspectorRegItem.identifier if self.inspectorRegItem else ''
settings.setValue("inspector", identifier) | python | def saveProfile(self, settings=None):
""" Writes the view settings to the persistent store
"""
self._updateNonDefaultsForInspector(self.inspectorRegItem, self.inspector)
if settings is None:
settings = QtCore.QSettings()
logger.debug("Writing settings to: {}".format(settings.group()))
settings.beginGroup('cfg_inspectors')
try:
for key, nonDefaults in self._inspectorsNonDefaults.items():
if nonDefaults:
settings.setValue(key, ctiDumps(nonDefaults))
logger.debug("Writing non defaults for {}: {}".format(key, nonDefaults))
finally:
settings.endGroup()
self.configWidget.configTreeView.saveProfile("config_tree/header_state", settings)
self.repoWidget.repoTreeView.saveProfile("repo_tree/header_state", settings)
settings.setValue("geometry", self.saveGeometry())
settings.setValue("state", self.saveState())
identifier = self.inspectorRegItem.identifier if self.inspectorRegItem else ''
settings.setValue("inspector", identifier) | Writes the view settings to the persistent store | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L716-L741 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.cloneWindow | def cloneWindow(self):
""" Opens a new window with the same inspector as the current window.
"""
# Save current window settings.
settings = QtCore.QSettings()
settings.beginGroup(self.argosApplication.windowGroupName(self.windowNumber))
try:
self.saveProfile(settings)
# Create new window with the freshly baked settings of the current window.
name = self.inspectorRegItem.fullName
newWindow = self.argosApplication.addNewMainWindow(settings=settings,
inspectorFullName=name)
finally:
settings.endGroup()
# Select the current item in the new window.
currentItem, _currentIndex = self.repoWidget.repoTreeView.getCurrentItem()
if currentItem:
newWindow.trySelectRtiByPath(currentItem.nodePath)
# Move the new window 24 pixels to the bottom right and raise it to the front.
newGeomRect = newWindow.geometry()
logger.debug("newGeomRect: x={}".format(newGeomRect.x()))
newGeomRect.moveTo(newGeomRect.x() + 24, newGeomRect.y() + 24)
newWindow.setGeometry(newGeomRect)
logger.debug("newGeomRect: x={}".format(newGeomRect.x()))
newWindow.raise_() | python | def cloneWindow(self):
""" Opens a new window with the same inspector as the current window.
"""
# Save current window settings.
settings = QtCore.QSettings()
settings.beginGroup(self.argosApplication.windowGroupName(self.windowNumber))
try:
self.saveProfile(settings)
# Create new window with the freshly baked settings of the current window.
name = self.inspectorRegItem.fullName
newWindow = self.argosApplication.addNewMainWindow(settings=settings,
inspectorFullName=name)
finally:
settings.endGroup()
# Select the current item in the new window.
currentItem, _currentIndex = self.repoWidget.repoTreeView.getCurrentItem()
if currentItem:
newWindow.trySelectRtiByPath(currentItem.nodePath)
# Move the new window 24 pixels to the bottom right and raise it to the front.
newGeomRect = newWindow.geometry()
logger.debug("newGeomRect: x={}".format(newGeomRect.x()))
newGeomRect.moveTo(newGeomRect.x() + 24, newGeomRect.y() + 24)
newWindow.setGeometry(newGeomRect)
logger.debug("newGeomRect: x={}".format(newGeomRect.x()))
newWindow.raise_() | Opens a new window with the same inspector as the current window. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L745-L774 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.activateAndRaise | def activateAndRaise(self):
""" Activates and raises the window.
"""
logger.debug("Activate and raising window: {}".format(self.windowNumber))
self.activateWindow()
self.raise_() | python | def activateAndRaise(self):
""" Activates and raises the window.
"""
logger.debug("Activate and raising window: {}".format(self.windowNumber))
self.activateWindow()
self.raise_() | Activates and raises the window. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L778-L783 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.event | def event(self, ev):
""" Detects the WindowActivate event. Pass all event through to the super class.
"""
if ev.type() == QtCore.QEvent.WindowActivate:
logger.debug("Window activated: {}".format(self.windowNumber))
self.activateWindowAction.setChecked(True)
return super(MainWindow, self).event(ev); | python | def event(self, ev):
""" Detects the WindowActivate event. Pass all event through to the super class.
"""
if ev.type() == QtCore.QEvent.WindowActivate:
logger.debug("Window activated: {}".format(self.windowNumber))
self.activateWindowAction.setChecked(True)
return super(MainWindow, self).event(ev); | Detects the WindowActivate event. Pass all event through to the super class. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L786-L793 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.closeEvent | def closeEvent(self, event):
""" Called when closing this window.
"""
logger.debug("closeEvent")
self.argosApplication.saveSettingsIfNeeded()
self.finalize()
self.argosApplication.removeMainWindow(self)
event.accept()
logger.debug("closeEvent accepted") | python | def closeEvent(self, event):
""" Called when closing this window.
"""
logger.debug("closeEvent")
self.argosApplication.saveSettingsIfNeeded()
self.finalize()
self.argosApplication.removeMainWindow(self)
event.accept()
logger.debug("closeEvent accepted") | Called when closing this window. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L796-L804 |
titusjan/argos | argos/widgets/mainwindow.py | MainWindow.about | def about(self):
""" Shows the about message window.
"""
aboutDialog = AboutDialog(parent=self)
aboutDialog.show()
aboutDialog.addDependencyInfo() | python | def about(self):
""" Shows the about message window.
"""
aboutDialog = AboutDialog(parent=self)
aboutDialog.show()
aboutDialog.addDependencyInfo() | Shows the about message window. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L808-L813 |
titusjan/argos | argos/application.py | ArgosApplication.profileGroupName | def profileGroupName(self, profile=None):
""" Returns the name of the QSetting group for the profile.
Converts to lower case and removes whitespace, interpunction, etc.
Prepends _debug_ if the debugging flag is set
:param profile: profile name. If None the current profile is used.
"""
profile = profile if profile else self.profile
profGroupName = '_debug_' if DEBUGGING else ''
profGroupName += string_to_identifier(profile)
return profGroupName | python | def profileGroupName(self, profile=None):
""" Returns the name of the QSetting group for the profile.
Converts to lower case and removes whitespace, interpunction, etc.
Prepends _debug_ if the debugging flag is set
:param profile: profile name. If None the current profile is used.
"""
profile = profile if profile else self.profile
profGroupName = '_debug_' if DEBUGGING else ''
profGroupName += string_to_identifier(profile)
return profGroupName | Returns the name of the QSetting group for the profile.
Converts to lower case and removes whitespace, interpunction, etc.
Prepends _debug_ if the debugging flag is set
:param profile: profile name. If None the current profile is used. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L169-L179 |
titusjan/argos | argos/application.py | ArgosApplication.windowGroupName | def windowGroupName(self, windowNumber, profile=None):
""" Returns the name of the QSetting group for this window in the this profile.
:param windowNumber: int
:param profile: profile name. If None the current profile is used.
"""
return "{}/window-{:02d}".format(self.profileGroupName(profile=profile), windowNumber) | python | def windowGroupName(self, windowNumber, profile=None):
""" Returns the name of the QSetting group for this window in the this profile.
:param windowNumber: int
:param profile: profile name. If None the current profile is used.
"""
return "{}/window-{:02d}".format(self.profileGroupName(profile=profile), windowNumber) | Returns the name of the QSetting group for this window in the this profile.
:param windowNumber: int
:param profile: profile name. If None the current profile is used. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L182-L188 |
titusjan/argos | argos/application.py | ArgosApplication.deleteProfile | def deleteProfile(self, profile):
""" Removes a profile from the persistent settings
"""
profGroupName = self.profileGroupName(profile)
logger.debug("Resetting profile settings: {}".format(profGroupName))
settings = QtCore.QSettings()
settings.remove(profGroupName) | python | def deleteProfile(self, profile):
""" Removes a profile from the persistent settings
"""
profGroupName = self.profileGroupName(profile)
logger.debug("Resetting profile settings: {}".format(profGroupName))
settings = QtCore.QSettings()
settings.remove(profGroupName) | Removes a profile from the persistent settings | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L191-L197 |
titusjan/argos | argos/application.py | ArgosApplication.deleteAllProfiles | def deleteAllProfiles(self):
""" Returns a list of all profiles
"""
settings = QtCore.QSettings()
for profGroupName in QtCore.QSettings().childGroups():
settings.remove(profGroupName) | python | def deleteAllProfiles(self):
""" Returns a list of all profiles
"""
settings = QtCore.QSettings()
for profGroupName in QtCore.QSettings().childGroups():
settings.remove(profGroupName) | Returns a list of all profiles | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L200-L205 |
titusjan/argos | argos/application.py | ArgosApplication.loadProfile | def loadProfile(self, profile, inspectorFullName=None):
""" Reads the persistent program settings for the current profile.
If inspectorFullName is given, a window with this inspector will be created if it wasn't
already created in the profile. All windows with this inspector will be raised.
"""
settings = QtCore.QSettings()
logger.info("Reading profile {!r} from: {}".format(profile, settings.fileName()))
self._profile = profile
profGroupName = self.profileGroupName(profile)
# Instantiate windows from groups
settings.beginGroup(profGroupName)
try:
for windowGroupName in settings.childGroups():
if windowGroupName.startswith('window'):
settings.beginGroup(windowGroupName)
try:
self.addNewMainWindow(settings=settings)
finally:
settings.endGroup()
finally:
settings.endGroup()
if inspectorFullName is not None:
windows = [win for win in self._mainWindows
if win.inspectorFullName == inspectorFullName]
if len(windows) == 0:
logger.info("Creating window for inspector: {!r}".format(inspectorFullName))
try:
win = self.addNewMainWindow(inspectorFullName=inspectorFullName)
except KeyError:
logger.warn("No inspector found with ID: {}".format(inspectorFullName))
else:
for win in windows:
win.raise_()
if len(self.mainWindows) == 0:
logger.info("No open windows in profile (creating one).")
self.addNewMainWindow(inspectorFullName=DEFAULT_INSPECTOR) | python | def loadProfile(self, profile, inspectorFullName=None):
""" Reads the persistent program settings for the current profile.
If inspectorFullName is given, a window with this inspector will be created if it wasn't
already created in the profile. All windows with this inspector will be raised.
"""
settings = QtCore.QSettings()
logger.info("Reading profile {!r} from: {}".format(profile, settings.fileName()))
self._profile = profile
profGroupName = self.profileGroupName(profile)
# Instantiate windows from groups
settings.beginGroup(profGroupName)
try:
for windowGroupName in settings.childGroups():
if windowGroupName.startswith('window'):
settings.beginGroup(windowGroupName)
try:
self.addNewMainWindow(settings=settings)
finally:
settings.endGroup()
finally:
settings.endGroup()
if inspectorFullName is not None:
windows = [win for win in self._mainWindows
if win.inspectorFullName == inspectorFullName]
if len(windows) == 0:
logger.info("Creating window for inspector: {!r}".format(inspectorFullName))
try:
win = self.addNewMainWindow(inspectorFullName=inspectorFullName)
except KeyError:
logger.warn("No inspector found with ID: {}".format(inspectorFullName))
else:
for win in windows:
win.raise_()
if len(self.mainWindows) == 0:
logger.info("No open windows in profile (creating one).")
self.addNewMainWindow(inspectorFullName=DEFAULT_INSPECTOR) | Reads the persistent program settings for the current profile.
If inspectorFullName is given, a window with this inspector will be created if it wasn't
already created in the profile. All windows with this inspector will be raised. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L208-L248 |
titusjan/argos | argos/application.py | ArgosApplication.saveProfile | def saveProfile(self):
""" Writes the current profile settings to the persistent store
"""
if not self.profile:
logger.warning("No profile defined (no settings saved)")
return
settings = QtCore.QSettings()
logger.debug("Writing settings to: {}".format(settings.fileName()))
profGroupName = self.profileGroupName()
settings.remove(profGroupName) # start with a clean slate
assert self.mainWindows, "no main windows found"
for winNr, mainWindow in enumerate(self.mainWindows):
settings.beginGroup(self.windowGroupName(winNr))
try:
mainWindow.saveProfile(settings)
finally:
settings.endGroup() | python | def saveProfile(self):
""" Writes the current profile settings to the persistent store
"""
if not self.profile:
logger.warning("No profile defined (no settings saved)")
return
settings = QtCore.QSettings()
logger.debug("Writing settings to: {}".format(settings.fileName()))
profGroupName = self.profileGroupName()
settings.remove(profGroupName) # start with a clean slate
assert self.mainWindows, "no main windows found"
for winNr, mainWindow in enumerate(self.mainWindows):
settings.beginGroup(self.windowGroupName(winNr))
try:
mainWindow.saveProfile(settings)
finally:
settings.endGroup() | Writes the current profile settings to the persistent store | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L252-L271 |
titusjan/argos | argos/application.py | ArgosApplication.saveSettings | def saveSettings(self):
""" Saves the persistent settings. Only saves the profile.
"""
try:
self.saveProfile()
except Exception as ex:
# Continue, even if saving the settings fails.
logger.warn(ex)
if DEBUGGING:
raise
finally:
self._settingsSaved = True | python | def saveSettings(self):
""" Saves the persistent settings. Only saves the profile.
"""
try:
self.saveProfile()
except Exception as ex:
# Continue, even if saving the settings fails.
logger.warn(ex)
if DEBUGGING:
raise
finally:
self._settingsSaved = True | Saves the persistent settings. Only saves the profile. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L274-L285 |
titusjan/argos | argos/application.py | ArgosApplication.loadFiles | def loadFiles(self, fileNames, rtiClass=None):
""" Loads files into the repository as repo tree items of class rtiClass.
Auto-detects using the extensions when rtiClass is None
"""
for fileName in fileNames:
self.repo.loadFile(fileName, rtiClass=rtiClass) | python | def loadFiles(self, fileNames, rtiClass=None):
""" Loads files into the repository as repo tree items of class rtiClass.
Auto-detects using the extensions when rtiClass is None
"""
for fileName in fileNames:
self.repo.loadFile(fileName, rtiClass=rtiClass) | Loads files into the repository as repo tree items of class rtiClass.
Auto-detects using the extensions when rtiClass is None | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L296-L301 |
titusjan/argos | argos/application.py | ArgosApplication.addNewMainWindow | def addNewMainWindow(self, settings=None, inspectorFullName=None):
""" Creates and shows a new MainWindow.
If inspectorFullName is set, it will set the identifier from that name.
If the inspector identifier is not found in the registry, a KeyError is raised.
"""
mainWindow = MainWindow(self)
self.mainWindows.append(mainWindow)
self.windowActionGroup.addAction(mainWindow.activateWindowAction)
self.repopulateAllWindowMenus()
if settings:
mainWindow.readViewSettings(settings)
if inspectorFullName:
inspectorId = nameToIdentifier(inspectorFullName)
mainWindow.setInspectorById(inspectorId)
if mainWindow.inspectorRegItem: # can be None at start
inspectorId = mainWindow.inspectorRegItem.identifier
mainWindow.getInspectorActionById(inspectorId).setChecked(True)
logger.info("Created new window with inspector: {}"
.format(mainWindow.inspectorRegItem.fullName))
else:
logger.info("Created new window without inspector")
mainWindow.drawInspectorContents(reason=UpdateReason.NEW_MAIN_WINDOW)
mainWindow.show()
if sys.platform.startswith('darwin'):
# Calling raise before the QApplication.exec_ only shows the last window
# that was added. Therefore we also call activeWindow. However, this may not
# always be desirable. TODO: make optional?
mainWindow.raise_()
pass
return mainWindow | python | def addNewMainWindow(self, settings=None, inspectorFullName=None):
""" Creates and shows a new MainWindow.
If inspectorFullName is set, it will set the identifier from that name.
If the inspector identifier is not found in the registry, a KeyError is raised.
"""
mainWindow = MainWindow(self)
self.mainWindows.append(mainWindow)
self.windowActionGroup.addAction(mainWindow.activateWindowAction)
self.repopulateAllWindowMenus()
if settings:
mainWindow.readViewSettings(settings)
if inspectorFullName:
inspectorId = nameToIdentifier(inspectorFullName)
mainWindow.setInspectorById(inspectorId)
if mainWindow.inspectorRegItem: # can be None at start
inspectorId = mainWindow.inspectorRegItem.identifier
mainWindow.getInspectorActionById(inspectorId).setChecked(True)
logger.info("Created new window with inspector: {}"
.format(mainWindow.inspectorRegItem.fullName))
else:
logger.info("Created new window without inspector")
mainWindow.drawInspectorContents(reason=UpdateReason.NEW_MAIN_WINDOW)
mainWindow.show()
if sys.platform.startswith('darwin'):
# Calling raise before the QApplication.exec_ only shows the last window
# that was added. Therefore we also call activeWindow. However, this may not
# always be desirable. TODO: make optional?
mainWindow.raise_()
pass
return mainWindow | Creates and shows a new MainWindow.
If inspectorFullName is set, it will set the identifier from that name.
If the inspector identifier is not found in the registry, a KeyError is raised. | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L314-L351 |
titusjan/argos | argos/application.py | ArgosApplication.removeMainWindow | def removeMainWindow(self, mainWindow):
""" Removes the mainWindow from the list of windows. Saves the settings
"""
logger.debug("removeMainWindow called")
self.windowActionGroup.removeAction(mainWindow.activateWindowAction)
self.repopulateAllWindowMenus()
self.mainWindows.remove(mainWindow) | python | def removeMainWindow(self, mainWindow):
""" Removes the mainWindow from the list of windows. Saves the settings
"""
logger.debug("removeMainWindow called")
self.windowActionGroup.removeAction(mainWindow.activateWindowAction)
self.repopulateAllWindowMenus()
self.mainWindows.remove(mainWindow) | Removes the mainWindow from the list of windows. Saves the settings | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L354-L362 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.