def _check_section_option(self, section, option): """ Private method to check section and option types """ if section is None: section = self.DEFAULT_SECTION_NAME elif not is_text_string(section): raise RuntimeError("Argument 'section' must be a string") if not is_text_string(option): raise RuntimeError("Argument 'option' must be a string") return section
def translate_gettext(x): y = lgettext(x) if is_text_string(y): return y else: return to_text_string(y, "utf-8")
def getobjdir(obj): """ For standard objects, will simply return dir(obj) In special cases (e.g. WrapITK package), will return only string elements of result returned by dir(obj) """ return [item for item in dir(obj) if is_text_string(item)]
def add_pathlist_to_PYTHONPATH(env, pathlist, drop_env=False, ipyconsole=False): # PyQt API 1/2 compatibility-related tests: assert isinstance(env, list) assert all([is_text_string(path) for path in env]) pypath = "PYTHONPATH" pathstr = os.pathsep.join(pathlist) if os.environ.get(pypath) is not None and not drop_env: old_pypath = os.environ[pypath] if not ipyconsole: for index, var in enumerate(env[:]): if var.startswith(pypath+'='): env[index] = var.replace(pypath+'=', pypath+'='+pathstr+os.pathsep) env.append('OLD_PYTHONPATH='+old_pypath) else: pypath = {'PYTHONPATH': pathstr + os.pathsep + old_pypath, 'OLD_PYTHONPATH': old_pypath} return pypath else: if not ipyconsole: env.append(pypath+'='+pathstr) else: return {'PYTHONPATH': pathstr}
def create_toolbutton(parent, text=None, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, autoraise=True, text_beside_icon=False): """Create a QToolButton""" button = QToolButton(parent) if text is not None: button.setText(text) if icon is not None: if is_text_string(icon): icon = get_icon(icon) button.setIcon(icon) if text is not None or tip is not None: button.setToolTip(text if tip is None else tip) if text_beside_icon: button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) button.setAutoRaise(autoraise) if triggered is not None: button.clicked.connect(triggered) if toggled is not None: button.toggled.connect(toggled) button.setCheckable(True) if shortcut is not None: button.setShortcut(shortcut) return button
def go_to(self, url_or_text): """Go to page *address*""" if is_text_string(url_or_text): url = QUrl(url_or_text) else: url = url_or_text self.webview.load(url)
def get_bgcolor(self, index): """Background color depending on value""" column = index.column() if column == 0: color = QColor(BACKGROUND_NONNUMBER_COLOR) color.setAlphaF(BACKGROUND_INDEX_ALPHA) return color if not self.bgcolor_enabled: return value = self.get_value(index.row(), column - 1) if self.max_min_col[column - 1] is None: color = QColor(BACKGROUND_NONNUMBER_COLOR) if is_text_string(value): color.setAlphaF(BACKGROUND_STRING_ALPHA) else: color.setAlphaF(BACKGROUND_MISC_ALPHA) else: if isinstance(value, COMPLEX_NUMBER_TYPES): color_func = abs else: color_func = float vmax, vmin = self.return_max(self.max_min_col, column - 1) hue = (BACKGROUND_NUMBER_MINHUE + BACKGROUND_NUMBER_HUERANGE * (vmax - color_func(value)) / (vmax - vmin)) hue = float(abs(hue)) if hue > 1: hue = 1 color = QColor.fromHsvF(hue, BACKGROUND_NUMBER_SATURATION, BACKGROUND_NUMBER_VALUE, BACKGROUND_NUMBER_ALPHA) return color
def value_to_display(value, minmax=False): """Convert value for display purpose""" try: numeric_numpy_types = (int64, int32, float64, float32, complex128, complex64) if isinstance(value, recarray): fields = value.names display = 'Field names: ' + ', '.join(fields) elif isinstance(value, MaskedArray): display = 'Masked array' elif isinstance(value, ndarray): if minmax: try: display = 'Min: %r\nMax: %r' % (value.min(), value.max()) except (TypeError, ValueError): display = repr(value) else: display = repr(value) elif isinstance(value, (list, tuple, dict, set)): display = CollectionsRepr.repr(value) elif isinstance(value, Image): display = '%s Mode: %s' % (address(value), value.mode) elif isinstance(value, DataFrame): cols = value.columns cols = [to_text_string(c) for c in cols] display = 'Column names: ' + ', '.join(list(cols)) elif isinstance(value, NavigableString): # Fixes Issue 2448 display = to_text_string(value) elif isinstance(value, DatetimeIndex): display = value.summary() elif is_binary_string(value): try: display = to_text_string(value, 'utf8') except: display = value elif is_text_string(value): display = value elif isinstance(value, NUMERIC_TYPES) or isinstance(value, bool) or \ isinstance(value, datetime.date) or \ isinstance(value, numeric_numpy_types): display = repr(value) else: # Note: Don't trust on repr's. They can be inefficient and # so freeze TRex quite easily # display = repr(value) type_str = to_text_string(type(value)) display = type_str[1:-1] except: type_str = to_text_string(type(value)) display = type_str[1:-1] # Truncate display at 80 chars to avoid freezing TRex # because of large displays if len(display) > 80: display = display[:80].rstrip() + ' ...' return display
def create_python_script_action(parent, text, icon, package, module, args=[]): """Create action to run a GUI based Python script""" if is_text_string(icon): icon = get_icon(icon) if programs.python_script_exists(package, module): return create_action(parent, text, icon=icon, triggered=lambda: programs.run_python_script( package, module, args))
def load_config(self): """Load configuration: opened projects & tree widget state""" expanded_state = self.get_option('expanded_state', None) # Sometimes the expanded state option may be truncated in .ini file # (for an unknown reason), in this case it would be converted to a # string by 'userconfig': if is_text_string(expanded_state): expanded_state = None if expanded_state is not None: self.treewidget.set_expanded_state(expanded_state)
def set_eol_chars(self, text): """Set widget end-of-line (EOL) characters from text (analyzes text)""" if not is_text_string(text): # testing for QString (PyQt API#1) text = to_text_string(text) eol_chars = sourcecode.get_eol_chars(text) is_document_modified = eol_chars is not None and self.eol_chars is not None self.eol_chars = eol_chars if is_document_modified: self.document().setModified(True) if self.sig_eol_chars_changed is not None: self.sig_eol_chars_changed.emit(eol_chars)
def eval(self, text): """ Evaluate text and return (obj, valid) where *obj* is the object represented by *text* and *valid* is True if object evaluation did not raise any exception """ assert is_text_string(text) try: return eval(text, self.locals), True except: return None, False
def _eval(self, text): """ Evaluate text and return (obj, valid) where *obj* is the object represented by *text* and *valid* is True if object evaluation did not raise any exception """ assert is_text_string(text) ns = self._get_current_namespace(with_magics=True) try: return eval(text, ns), True except: return None, False
def _set(self, section, option, value, verbose): """ Private set method """ if not self.has_section(section): self.add_section(section) if not is_text_string(value): value = repr(value) if verbose: print('%s[ %s ] = %s' % (section, option, value)) # trex: test-skip cp.ConfigParser.set(self, section, option, value)
def create_program_action(parent, text, name, icon=None, nt_name=None): """Create action to run a program""" if is_text_string(icon): icon = get_icon(icon) if os.name == 'nt' and nt_name is not None: name = nt_name path = programs.find_program(name) if path is not None: return create_action(parent, text, icon=icon, triggered=lambda: programs.run_program(name))
def append_to_history(self, filename, command): """ Append an entry to history filename Slot for append_to_history signal emitted by shell instance """ if not is_text_string(filename): # filename is a QString filename = to_text_string(filename.toUtf8(), 'utf-8') command = to_text_string(command) index = self.filenames.index(filename) self.editors[index].append(command) if self.get_option('go_to_eof'): self.editors[index].set_cursor_position('eof') self.tabwidget.setCurrentIndex(index)
def create_action(parent, text, shortcut=None, icon=None, tip=None, toggled=None, triggered=None, data=None, menurole=None, context=Qt.WindowShortcut): """Create a QAction""" action = TRexAction(text, parent) if triggered is not None: action.triggered.connect(triggered) if toggled is not None: action.toggled.connect(toggled) action.setCheckable(True) if icon is not None: if is_text_string(icon): icon = get_icon(icon) action.setIcon(icon) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if data is not None: action.setData(to_qvariant(data)) if menurole is not None: action.setMenuRole(menurole) # Workround for Mac because setting context=Qt.WidgetShortcut # there doesn't have any effect if sys.platform == 'darwin': action._shown_shortcut = None if context == Qt.WidgetShortcut: if shortcut is not None: action._shown_shortcut = shortcut else: # This is going to be filled by # main.register_shortcut action._shown_shortcut = 'missing' else: if shortcut is not None: action.setShortcut(shortcut) action.setShortcutContext(context) else: if shortcut is not None: action.setShortcut(shortcut) action.setShortcutContext(context) return action
def send_to_process(self, text): if not is_text_string(text): text = to_text_string(text) if text[:-1] in ["clear", "cls", "CLS"]: self.shell.clear() self.send_to_process(os.linesep) return if not text.endswith('\n'): text += '\n' if os.name == 'nt': self.process.write(text.encode('cp850')) else: self.process.write(LOCALE_CODEC.fromUnicode(text)) self.process.waitForBytesWritten(-1)
def create_mainwindow(self): """ Create a QMainWindow instance containing this plugin Note: this method is currently not used """ self.mainwindow = mainwindow = QMainWindow() mainwindow.setAttribute(Qt.WA_DeleteOnClose) icon = self.get_plugin_icon() if is_text_string(icon): icon = self.get_icon(icon) mainwindow.setWindowIcon(icon) mainwindow.setWindowTitle(self.get_plugin_title()) mainwindow.setCentralWidget(self) self.refresh_plugin() return mainwindow
def runfile(self, filename, args=None): """ Run filename args: command line arguments (string) """ if args is not None and not is_text_string(args): raise TypeError("expected a character buffer object") self.namespace['__file__'] = filename sys.argv = [filename] if args is not None: for arg in args.split(): sys.argv.append(arg) self.execfile(filename) sys.argv = [''] self.namespace.pop('__file__')
def __init__(self, parent, history_filename, profile=False, initial_message=None): """ parent : specifies the parent widget """ ConsoleBaseWidget.__init__(self, parent) SaveHistoryMixin.__init__(self) # Prompt position: tuple (line, index) self.current_prompt_pos = None self.new_input_line = True # History self.histidx = None self.hist_wholeline = False assert is_text_string(history_filename) self.history_filename = history_filename self.history = self.load_history() # Session self.historylog_filename = CONF.get('main', 'historylog_filename', get_conf_path('history.log')) # Context menu self.menu = None self.setup_context_menu() # Simple profiling test self.profile = profile # Buffer to increase performance of write/flush operations self.__buffer = [] if initial_message: self.__buffer.append(initial_message) self.__timestamp = 0.0 self.__flushtimer = QTimer(self) self.__flushtimer.setSingleShot(True) self.__flushtimer.timeout.connect(self.flush) # Give focus to widget self.setFocus() # Cursor width self.setCursorWidth(CONF.get('main', 'cursor/width'))
def create_dialog(obj, obj_name): """Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that he can monkey patch oedit to show eMZed related data) """ # Local import from trex.widgets.variableexplorer.texteditor import TextEditor from trex.widgets.variableexplorer.utils import (ndarray, FakeObject, Image, is_known_type, DataFrame, Series) from trex.widgets.variableexplorer.collectionseditor import CollectionsEditor from trex.widgets.variableexplorer.arrayeditor import ArrayEditor if DataFrame is not FakeObject: from trex.widgets.variableexplorer.dataframeeditor import DataFrameEditor conv_func = lambda data: data readonly = not is_known_type(obj) if isinstance(obj, ndarray) and ndarray is not FakeObject: dialog = ArrayEditor() if not dialog.setup_and_check(obj, title=obj_name, readonly=readonly): return elif isinstance(obj, Image) and Image is not FakeObject \ and ndarray is not FakeObject: dialog = ArrayEditor() import numpy as np data = np.array(obj) if not dialog.setup_and_check(data, title=obj_name, readonly=readonly): return from trex.pil_patch import Image conv_func = lambda data: Image.fromarray(data, mode=obj.mode) elif isinstance(obj, (DataFrame, Series)) and DataFrame is not FakeObject: dialog = DataFrameEditor() if not dialog.setup_and_check(obj): return elif is_text_string(obj): dialog = TextEditor(obj, title=obj_name, readonly=readonly) else: dialog = CollectionsEditor() dialog.setup(obj, title=obj_name, readonly=readonly) def end_func(dialog): return conv_func(dialog.get_value()) return dialog, end_func
def shell_split(text): """ Split the string `text` using shell-like syntax This avoids breaking single/double-quoted strings (e.g. containing strings with spaces). This function is almost equivalent to the shlex.split function (see standard library `shlex`) except that it is supporting unicode strings (shlex does not support unicode until Python 2.7.3). """ assert is_text_string(text) # in case a QString is passed... pattern = r'(\s+|(?<!\\)".*?(?<!\\)"|(?<!\\)\'.*?(?<!\\)\')' out = [] for token in re.split(pattern, text): if token.strip(): out.append(token.strip('"').strip("'")) return out
def get(self): valuelist = [] for index, (label, value) in enumerate(self.data): field = self.widgets[index] if label is None: # Separator / Comment continue elif tuple_to_qfont(value) is not None: value = field.get_font() elif is_text_string(value): if isinstance(field, QTextEdit): value = to_text_string(field.toPlainText()).replace( u"\u2029", os.linesep) else: value = to_text_string(field.text()) elif isinstance(value, (list, tuple)): index = int(field.currentIndex()) if isinstance(value[0], int): # Return an int index, if initialization was an int value = index else: value = value[index + 1] if isinstance(value, (list, tuple)): value = value[0] elif isinstance(value, bool): value = field.checkState() == Qt.Checked elif isinstance(value, float): value = float(field.text()) elif isinstance(value, int): value = int(field.value()) elif isinstance(value, datetime.datetime): value = field.dateTime() try: value = value.toPyDateTime() # PyQt except AttributeError: value = value.toPython() # PySide elif isinstance(value, datetime.date): value = field.date() try: value = value.toPyDate() # PyQt except AttributeError: value = value.toPython() # PySide else: value = eval(str(field.text())) valuelist.append(value) return valuelist
def display_to_value(value, default_value, ignore_errors=True): """Convert back to value""" from qtpy.compat import from_qvariant value = from_qvariant(value, to_text_string) try: np_dtype = get_numpy_dtype(default_value) if isinstance(default_value, bool): # We must test for boolean before NumPy data types # because `bool` class derives from `int` class try: value = bool(float(value)) except ValueError: value = value.lower() == "true" elif np_dtype is not None: if 'complex' in str(type(default_value)): value = np_dtype(complex(value)) else: value = np_dtype(value) elif is_binary_string(default_value): value = to_binary_string(value, 'utf8') elif is_text_string(default_value): value = to_text_string(value) elif isinstance(default_value, complex): value = complex(value) elif isinstance(default_value, float): value = float(value) elif isinstance(default_value, int): try: value = int(value) except ValueError: value = float(value) elif isinstance(default_value, datetime.datetime): value = datestr_to_datetime(value) elif isinstance(default_value, datetime.date): value = datestr_to_datetime(value).date() elif ignore_errors: value = try_to_eval(value) else: value = eval(value) except (ValueError, SyntaxError): if ignore_errors: value = try_to_eval(value) else: return default_value return value
def text_to_qcolor(text): """ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated """ color = QColor() text = str(text) if not is_text_string(text): return color if text.startswith('#') and len(text) == 7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color elif text not in list(QColor.colorNames()): return color color.setNamedColor(text) return color
def oedit(obj, modal=True, namespace=None): """Edit the object 'obj' in a GUI-based editor and return the edited copy (if Cancel is pressed, return None) The object 'obj' is a container Supported container types: dict, list, tuple, str/unicode or numpy.array (instantiate a new QApplication if necessary, so it can be called directly from the interpreter) """ # Local import from trex.utils.qthelpers import qapplication app = qapplication() if modal: obj_name = '' else: assert is_text_string(obj) obj_name = obj if namespace is None: namespace = globals() keeper.set_namespace(namespace) obj = namespace[obj_name] # keep QApplication reference alive in the Python interpreter: namespace['__qapp__'] = app result = create_dialog(obj, obj_name) if result is None: return dialog, end_func = result if modal: if dialog.exec_(): return end_func(dialog) else: keeper.create_dialog(dialog, obj_name, end_func) import os if os.name == 'nt': app.exec_()
def setData(self, index, value, role=Qt.EditRole, change_type=None): """Cell content change""" column = index.column() row = index.row() if change_type is not None: try: value = self.data(index, role=Qt.DisplayRole) val = from_qvariant(value, str) if change_type is bool: val = bool_false_check(val) self.df.iloc[row, column - 1] = change_type(val) except ValueError: self.df.iloc[row, column - 1] = change_type('0') else: val = from_qvariant(value, str) current_value = self.get_value(row, column - 1) if isinstance(current_value, bool): val = bool_false_check(val) supported_types = ( bool, ) + REAL_NUMBER_TYPES + COMPLEX_NUMBER_TYPES if (isinstance(current_value, supported_types) or is_text_string(current_value)): try: self.df.iloc[row, column - 1] = current_value.__class__(val) except ValueError as e: QMessageBox.critical(self.dialog, "Error", "Value error: %s" % str(e)) return False else: QMessageBox.critical( self.dialog, "Error", "The type of the cell is not a supported " "type") return False self.max_min_col_update() return True
def set(self, section, option, value, verbose=False, save=True): """ Set an option section=None: attribute a default section name """ section = self._check_section_option(section, option) default_value = self.get_default(section, option) if default_value is NoDefault: # This let us save correctly string value options with # no config default that contain non-ascii chars in default_value = value self.set_default(section, option, default_value) if isinstance(default_value, bool): value = bool(value) elif isinstance(default_value, float): value = float(value) elif isinstance(default_value, int): value = int(value) elif not is_text_string(default_value): value = repr(value) self._set(section, option, value, verbose) if save: self._save()
def send_to_process(self, text): if not self.is_running(): return if not is_text_string(text): text = to_text_string(text) if self.mpl_backend == 0 and os.name == 'nt' and \ self.introspection_socket is not None: communicate(self.introspection_socket, "toggle_inputhook_flag(True)") # # Socket-based alternative (see input hook in sitecustomize.py): # while self.local_server.hasPendingConnections(): # self.local_server.nextPendingConnection().write('go!') if any([text == cmd for cmd in ['%ls', '%pwd', '%scientific']]) or \ any([text.startswith(cmd) for cmd in ['%cd ', '%clear ']]): text = 'evalsc(r"%s")\n' % text if not text.endswith('\n'): text += '\n' self.process.write(to_binary_string(text, 'utf8')) self.process.waitForBytesWritten(-1) # Eventually write prompt faster (when hitting Enter continuously) # -- necessary/working on Windows only: if os.name == 'nt': self.write_error()