Example #1
0
def get_font(section='main', option='font', font_size_delta=0):
    """Get console font properties depending on OS and user options"""
    font = FONT_CACHE.get((section, option))

    if font is None:
        families = CONF.get(section, option + "/family", None)

        if families is None:
            return QFont()

        family = get_family(families)
        weight = QFont.Normal
        italic = CONF.get(section, option + '/italic', False)

        if CONF.get(section, option + '/bold', False):
            weight = QFont.Bold

        size = CONF.get(section, option + '/size', 9) + font_size_delta
        font = QFont(family, size, weight)
        font.setItalic(italic)
        FONT_CACHE[(section, option)] = font

    size = CONF.get(section, option + '/size', 9) + font_size_delta
    font.setPointSize(size)
    return font
Example #2
0
 def set_option(self, option, value):
     """
     Set a plugin option in configuration file
     Use a SIGNAL to call it, e.g.:
     plugin.sig_option_changed.emit('show_all', checked)
     """
     CONF.set(self.CONF_SECTION, str(option), value)
Example #3
0
def _get_run_configurations():
    history_count = CONF.get('run', 'history', 20)
    try:
        return [(filename, options)
                for filename, options in CONF.get('run', 'configurations', [])
                if osp.isfile(filename)][:history_count]
    except ValueError:
        CONF.set('run', 'configurations', [])
        return []
Example #4
0
 def update_margins(self):
     layout = self.layout()
     if self.default_margins is None:
         self.default_margins = layout.getContentsMargins()
     if CONF.get('main', 'use_custom_margin'):
         margin = CONF.get('main', 'custom_margin')
         layout.setContentsMargins(*[margin] * 4)
     else:
         layout.setContentsMargins(*self.default_margins)
Example #5
0
 def external_editor(self, filename, goto=-1):
     """Edit in an external editor
     Recommended: SciTE (e.g. to go to line where an error did occur)"""
     editor_path = CONF.get('internal_console', 'external_editor/path')
     goto_option = CONF.get('internal_console', 'external_editor/gotoline')
     try:
         args = [filename]
         if goto > 0 and goto_option:
             args.append('%s%d'.format(goto_option, goto))
         programs.run_program(editor_path, args)
     except OSError:
         self.write_error("External editor was not found:"
                          " %s\n" % editor_path)
Example #6
0
def set_font(font, section='main', option='font'):
    """Set font"""
    CONF.set(section, option + '/family', to_text_string(font.family()))
    CONF.set(section, option + '/size', float(font.pointSize()))
    CONF.set(section, option + '/italic', int(font.italic()))
    CONF.set(section, option + '/bold', int(font.bold()))
    FONT_CACHE[(section, option)] = font
Example #7
0
    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'))
Example #8
0
def send_args_to_trex(args):
    """
    Simple socket client used to send the args passed to the TRex
    executable to an already running instance.

    Args can be Python scripts or files with these extensions: .spydata, .mat,
    .npy, or .h5, which can be imported by the Variable Explorer.
    """
    port = CONF.get('main', 'open_files_port')

    # Wait ~50 secs for the server to be up
    # Taken from http://stackoverflow.com/a/4766598/438386
    for _x in range(200):
        try:
            for arg in args:
                client = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                       socket.IPPROTO_TCP)
                client.connect(("127.0.0.1", port))
                if is_unicode(arg):
                    arg = arg.encode('utf-8')
                client.send(osp.abspath(arg))
                client.close()
        except socket.error:
            time.sleep(0.25)
            continue
        break
Example #9
0
    def __init__(self, main=None, **kwds):
        """Bind widget to a QMainWindow instance"""
        super(TRexPluginMixin, self).__init__(**kwds)
        assert self.CONF_SECTION is not None
        self.PLUGIN_PATH = os.path.dirname(inspect.getfile(self.__class__))
        self.main = main
        self.default_margins = None
        self.plugin_actions = None
        self.dockwidget = None
        self.mainwindow = None
        self.ismaximized = False
        self.isvisible = False

        # NOTE: Don't use the default option of CONF.get to assign a
        # None shortcut to plugins that don't have one. That will mess
        # the creation of our Keyboard Shortcuts prefs page
        try:
            self.shortcut = CONF.get('shortcuts', '_/switch to %s' % \
                                     self.CONF_SECTION)
        except configparser.NoOptionError:
            self.shortcut = None

        # We decided to create our own toggle action instead of using
        # the one that comes with dockwidget because it's not possible
        # to raise and focus the plugin with it.
        self.toggle_view_action = None
Example #10
0
 def update_font(self):
     """Update font from Preferences"""
     font = self.get_plugin_font()
     for shellwidget in self.shellwidgets:
         shellwidget.shell.set_font(font)
         completion_size = CONF.get('main', 'completion/size')
         comp_widget = shellwidget.shell.completion_widget
         comp_widget.setup_appearance(completion_size, font)
Example #11
0
 def __init__(self, fname=None):
     self.args = None
     self.args_enabled = None
     self.wdir = None
     self.wdir_enabled = None
     self.current = None
     self.systerm = None
     self.interact = None
     self.show_kill_warning =None
     self.post_mortem = None
     self.python_args = None
     self.python_args_enabled = None
     self.clear_namespace = None
     self.set(CONF.get('run', 'defaultconfiguration', default={}))
     if fname is not None and\
        CONF.get('run', WDIR_USE_SCRIPT_DIR_OPTION, True):
         self.wdir = osp.dirname(fname)
         self.wdir_enabled = True
Example #12
0
 def set_trex_breakpoints(self):
     self.clear_all_breaks()
     #------Really deleting all breakpoints:
     for bp in bdb.Breakpoint.bpbynumber:
         if bp:
             bp.deleteMe()
     bdb.Breakpoint.next = 1
     bdb.Breakpoint.bplist = {}
     bdb.Breakpoint.bpbynumber = [None]
     #------
     from trex.config.main import CONF
     CONF.load_from_ini()
     if CONF.get('run', 'breakpoints/enabled', True):
         breakpoints = CONF.get('run', 'breakpoints', {})
         i = 0
         for fname, data in list(breakpoints.items()):
             for linenumber, condition in data:
                 i += 1
                 self.set_break(self.canonic(fname), linenumber,
                                cond=condition)
Example #13
0
 def save_historylog(self):
     """Save current history log (all text in console)"""
     title = _("Save history log")
     self.redirect_stdio.emit(False)
     filename, _selfilter = getsavefilename(
         self, title, self.historylog_filename,
         "%s (*.log)" % _("History logs"))
     self.redirect_stdio.emit(True)
     if filename:
         filename = osp.normpath(filename)
         try:
             encoding.write(to_text_string(self.get_text_with_eol()),
                            filename)
             self.historylog_filename = filename
             CONF.set('main', 'historylog_filename', filename)
         except EnvironmentError as error:
             QMessageBox.critical(
                 self, title,
                 _("<b>Unable to save file '%s'</b>"
                   "<br><br>Error message:<br>%s") %
                 (osp.basename(filename), to_text_string(error)))
Example #14
0
    def __init__(self,
                 parent=None,
                 namespace=None,
                 commands=[],
                 message=None,
                 max_line_count=300,
                 font=None,
                 exitfunc=None,
                 profile=False,
                 multithreaded=True,
                 light_background=True):
        PythonShellWidget.__init__(self, parent,
                                   get_conf_path('history_internal.py'),
                                   profile)

        self.set_light_background(light_background)
        self.multithreaded = multithreaded
        self.setMaximumBlockCount(max_line_count)

        if font is not None:
            self.set_font(font)

        # Allow raw_input support:
        self.input_loop = None
        self.input_mode = False

        # KeyboardInterrupt support
        self.interrupted = False  # used only for not-multithreaded mode
        self.sig_keyboard_interrupt.connect(self.keyboard_interrupt)

        # Code completion / calltips
        getcfg = lambda option: CONF.get('internal_console', option)
        case_sensitive = getcfg('codecompletion/case_sensitive')
        self.set_codecompletion_case(case_sensitive)

        # keyboard events management
        self.eventqueue = []

        # Init interpreter
        self.exitfunc = exitfunc
        self.commands = commands
        self.message = message
        self.interpreter = None
        self.start_interpreter(namespace)

        # Clear status bar
        self.status.emit('')

        # Embedded shell -- requires the monitor (which installs the
        # 'open_in_trex' function in builtins)
        if hasattr(builtins, 'open_in_trex'):
            self.go_to_error.connect(self.open_with_external_trex)
Example #15
0
def set_color_scheme(name, color_scheme, replace=True):
    """Set syntax color scheme"""
    section = "color_schemes"
    names = CONF.get("color_schemes", "names", [])
    for key in sh.COLOR_SCHEME_KEYS:
        option = "%s/%s" % (name, key)
        value = CONF.get(section, option, default=None)
        if value is None or replace or name not in names:
            CONF.set(section, option, color_scheme[key])
    names.append(to_text_string(name))
    CONF.set(section, "names", sorted(list(set(names))))
Example #16
0
def icon(name, resample=False, icon_path=None):
    theme = CONF.get('main', 'icon_theme')
    if theme == 'trex 3':
        if not _resource['loaded']:
            qta.load_font('trex',
                          'trex.ttf',
                          'trex-charmap.json',
                          directory=_resource['directory'])
            _resource['loaded'] = True
        args, kwargs = _qtaargs[name]
        return qta.icon(*args, **kwargs)
    elif theme == 'trex 2':
        icon = get_icon(name + '.png', resample=resample)
        if icon_path:
            icon_path = osp.join(icon_path, name + '.png')
            if osp.isfile(icon_path):
                icon = QIcon(icon_path)
        return icon if icon is not None else QIcon()
Example #17
0
    def load_history(self):
        """Load history from a .py file in user home directory"""
        if osp.isfile(self.history_filename):
            rawhistory, _ = encoding.readlines(self.history_filename)
            rawhistory = [line.replace('\n', '') for line in rawhistory]
            if rawhistory[1] != self.INITHISTORY[1]:
                rawhistory[1] = self.INITHISTORY[1]
        else:
            rawhistory = self.INITHISTORY
        history = [line for line in rawhistory \
                   if line and not line.startswith('#')]

        # Truncating history to X entries:
        while len(history) >= CONF.get('historylog', 'max_entries'):
            del history[0]
            while rawhistory[0].startswith('#'):
                del rawhistory[0]
            del rawhistory[0]
        # Saving truncated history:
        encoding.writelines(rawhistory, self.history_filename)
        return history
Example #18
0
 def apply_plugin_settings(self, options):
     """Apply configuration file's plugin settings"""
     showtime_n = 'show_elapsed_time'
     showtime_o = self.get_option(showtime_n)
     icontext_n = 'show_icontext'
     icontext_o = self.get_option(icontext_n)
     calltips_n = 'calltips'
     calltips_o = self.get_option(calltips_n)
     help_n = 'connect_to_oi'
     help_o = CONF.get('help', 'connect/python_console')
     wrap_n = 'wrap'
     wrap_o = self.get_option(wrap_n)
     compauto_n = 'codecompletion/auto'
     compauto_o = self.get_option(compauto_n)
     case_comp_n = 'codecompletion/case_sensitive'
     case_comp_o = self.get_option(case_comp_n)
     compenter_n = 'codecompletion/enter_key'
     compenter_o = self.get_option(compenter_n)
     mlc_n = 'max_line_count'
     mlc_o = self.get_option(mlc_n)
     for shellwidget in self.shellwidgets:
         if showtime_n in options:
             shellwidget.set_elapsed_time_visible(showtime_o)
         if icontext_n in options:
             shellwidget.set_icontext_visible(icontext_o)
         if calltips_n in options:
             shellwidget.shell.set_calltips(calltips_o)
         if help_n in options:
             if isinstance(shellwidget, ExternalPythonShell):
                 shellwidget.shell.set_help_enabled(help_o)
         if wrap_n in options:
             shellwidget.shell.toggle_wrap_mode(wrap_o)
         if compauto_n in options:
             shellwidget.shell.set_codecompletion_auto(compauto_o)
         if case_comp_n in options:
             shellwidget.shell.set_codecompletion_case(case_comp_o)
         if compenter_n in options:
             shellwidget.shell.set_codecompletion_enter(compenter_o)
         if mlc_n in options:
             shellwidget.shell.setMaximumBlockCount(mlc_o)
Example #19
0
 def set(self, options):
     self.args = options.get('args', '')
     self.args_enabled = options.get('args/enabled', False)
     if CONF.get('run', WDIR_USE_FIXED_DIR_OPTION, False):
         default_wdir = CONF.get('run', WDIR_FIXED_DIR_OPTION, getcwd())
         self.wdir = options.get('workdir', default_wdir)
         self.wdir_enabled = True
     else:
         self.wdir = options.get('workdir', getcwd())
         self.wdir_enabled = options.get('workdir/enabled', False)
     self.current = options.get('current',
                        CONF.get('run', CURRENT_INTERPRETER_OPTION, True))
     self.systerm = options.get('systerm',
                        CONF.get('run', SYSTERM_INTERPRETER_OPTION, False))
     self.interact = options.get('interact',
                        CONF.get('run', 'interact', False))
     self.show_kill_warning = options.get('show_kill_warning', 
                        CONF.get('run', 'show_kill_warning', False))
     self.post_mortem = options.get('post_mortem',
                        CONF.get('run', 'post_mortem', False))
     self.python_args = options.get('python_args', '')
     self.python_args_enabled = options.get('python_args/enabled', False)
     self.clear_namespace = options.get('clear_namespace',  
                                 CONF.get('run', 'clear_namespace', False))
Example #20
0
    def start(self,
              fname,
              wdir=None,
              args='',
              interact=False,
              debug=False,
              python=True,
              python_args='',
              post_mortem=True):
        """
        Start new console

        fname:
          string: filename of script to run
          None: open an interpreter
        wdir: working directory
        args: command line options of the Python script
        interact: inspect script interactively after its execution
        debug: run pdb
        python: True: Python interpreter, False: terminal
        python_args: additionnal Python interpreter command line options
                   (option "-u" is mandatory, see widgets.externalshell package)
        """
        # Note: fname is None <=> Python interpreter
        if fname is not None and not is_text_string(fname):
            fname = to_text_string(fname)
        if wdir is not None and not is_text_string(wdir):
            wdir = to_text_string(wdir)

        if fname is not None and fname in self.filenames:
            index = self.filenames.index(fname)
            if self.get_option('single_tab'):
                old_shell = self.shellwidgets[index]
                if old_shell.is_running():
                    runconfig = get_run_configuration(fname)
                    if runconfig is None or runconfig.show_kill_warning:
                        if PYQT5:
                            answer = QMessageBox.question(
                                self, self.get_plugin_title(),
                                _("%s is already running in a separate process.\n"
                                  "Do you want to kill the process before starting "
                                  "a new one?") % osp.basename(fname),
                                QMessageBox.Yes | QMessageBox.Cancel)
                        else:
                            mb = QMessageBox(self)
                            answer = mb.question(
                                mb, self.get_plugin_title(),
                                _("%s is already running in a separate process.\n"
                                  "Do you want to kill the process before starting "
                                  "a new one?") % osp.basename(fname),
                                QMessageBox.Yes | QMessageBox.Cancel)
                    else:
                        answer = QMessageBox.Yes

                    if answer == QMessageBox.Yes:
                        old_shell.process.kill()
                        old_shell.process.waitForFinished()
                    else:
                        return
                self.close_console(index)
        else:
            index = self.tabwidget.count()

        # Creating a new external shell
        pythonpath = self.main.get_trex_pythonpath()
        light_background = self.get_option('light_background')
        show_elapsed_time = self.get_option('show_elapsed_time')
        if python:
            if CONF.get('main_interpreter', 'default'):
                pythonexecutable = get_python_executable()
                external_interpreter = False
            else:
                pythonexecutable = CONF.get('main_interpreter', 'executable')
                external_interpreter = True
            if self.get_option('pythonstartup/default'):
                pythonstartup = None
            else:
                pythonstartup = self.get_option('pythonstartup', None)
            monitor_enabled = self.get_option('monitor/enabled')
            mpl_backend = self.get_option('matplotlib/backend/value')
            ets_backend = self.get_option('ets_backend')
            qt_api = self.get_option('qt/api')
            if qt_api not in ('pyqt', 'pyside', 'pyqt5'):
                qt_api = None
            merge_output_channels = self.get_option('merge_output_channels')
            colorize_sys_stderr = self.get_option('colorize_sys_stderr')
            umr_enabled = CONF.get('main_interpreter', 'umr/enabled')
            umr_namelist = CONF.get('main_interpreter', 'umr/namelist')
            umr_verbose = CONF.get('main_interpreter', 'umr/verbose')
            ar_timeout = CONF.get('variable_explorer', 'autorefresh/timeout')
            ar_state = CONF.get('variable_explorer', 'autorefresh')

            sa_settings = None
            shellwidget = ExternalPythonShell(
                self,
                fname,
                wdir,
                interact,
                debug,
                post_mortem=post_mortem,
                path=pythonpath,
                python_args=python_args,
                arguments=args,
                stand_alone=sa_settings,
                pythonstartup=pythonstartup,
                pythonexecutable=pythonexecutable,
                external_interpreter=external_interpreter,
                umr_enabled=umr_enabled,
                umr_namelist=umr_namelist,
                umr_verbose=umr_verbose,
                ets_backend=ets_backend,
                monitor_enabled=monitor_enabled,
                mpl_backend=mpl_backend,
                qt_api=qt_api,
                merge_output_channels=merge_output_channels,
                colorize_sys_stderr=colorize_sys_stderr,
                autorefresh_timeout=ar_timeout,
                autorefresh_state=ar_state,
                light_background=light_background,
                menu_actions=self.menu_actions,
                show_buttons_inside=False,
                show_elapsed_time=show_elapsed_time)
            shellwidget.sig_pdb.connect(
                lambda fname, lineno, shellwidget=shellwidget: self.
                pdb_has_stopped(fname, lineno, shellwidget))
            self.register_widget_shortcuts(shellwidget.shell)
        else:
            if os.name == 'posix':
                cmd = 'gnome-terminal'
                args = []
                if programs.is_program_installed(cmd):
                    if wdir:
                        args.extend(['--working-directory=%s' % wdir])
                    programs.run_program(cmd, args)
                    return
                cmd = 'konsole'
                if programs.is_program_installed(cmd):
                    if wdir:
                        args.extend(['--workdir', wdir])
                    programs.run_program(cmd, args)
                    return
            shellwidget = ExternalSystemShell(
                self,
                wdir,
                path=pythonpath,
                light_background=light_background,
                menu_actions=self.menu_actions,
                show_buttons_inside=False,
                show_elapsed_time=show_elapsed_time)

        # Code completion / calltips
        shellwidget.shell.setMaximumBlockCount(
            self.get_option('max_line_count'))
        shellwidget.shell.set_font(self.get_plugin_font())
        shellwidget.shell.toggle_wrap_mode(self.get_option('wrap'))
        shellwidget.shell.set_calltips(self.get_option('calltips'))
        shellwidget.shell.set_codecompletion_auto(
            self.get_option('codecompletion/auto'))
        shellwidget.shell.set_codecompletion_case(
            self.get_option('codecompletion/case_sensitive'))
        shellwidget.shell.set_codecompletion_enter(
            self.get_option('codecompletion/enter_key'))
        if python and self.help is not None:
            shellwidget.shell.set_help(self.help)
            shellwidget.shell.set_help_enabled(
                CONF.get('help', 'connect/python_console'))
        if self.historylog is not None:
            self.historylog.add_history(shellwidget.shell.history_filename)
            shellwidget.shell.append_to_history.connect(
                self.historylog.append_to_history)
            shellwidget.shell.go_to_error.connect(self.go_to_error)
            shellwidget.shell.focus_changed.connect(
                lambda: self.focus_changed.emit())
        if python:
            if self.main.editor is not None:
                shellwidget.open_file.connect(self.open_file_in_trex)
            if fname is None:
                self.python_count += 1
                tab_name = "Python %d" % self.python_count
                tab_icon1 = ima.icon('python')
                tab_icon2 = ima.icon('python_t')
                self.filenames.insert(index, fname)
            else:
                self.filenames.insert(index, fname)
                tab_name = self.get_tab_text(fname)
                self.update_tabs_text()
                tab_icon1 = ima.icon('run')
                tab_icon2 = ima.icon('terminated')
        else:
            fname = id(shellwidget)
            if os.name == 'nt':
                tab_name = _("Command Window")
            else:
                tab_name = _("Terminal")
            self.terminal_count += 1
            tab_name += (" %d" % self.terminal_count)
            tab_icon1 = ima.icon('cmdprompt')
            tab_icon2 = ima.icon('cmdprompt_t')
            self.filenames.insert(index, fname)
        self.shellwidgets.insert(index, shellwidget)
        self.icons.insert(index, (tab_icon1, tab_icon2))
        if index is None:
            index = self.tabwidget.addTab(shellwidget, tab_name)
        else:
            self.tabwidget.insertTab(index, shellwidget, tab_name)

        shellwidget.started.connect(
            lambda sid=id(shellwidget): self.process_started(sid))
        shellwidget.sig_finished.connect(
            lambda sid=id(shellwidget): self.process_finished(sid))
        self.find_widget.set_editor(shellwidget.shell)
        self.tabwidget.setTabToolTip(index, fname if wdir is None else wdir)
        self.tabwidget.setCurrentIndex(index)
        if self.dockwidget and not self.ismaximized:
            self.dockwidget.setVisible(True)
            self.dockwidget.raise_()

        shellwidget.set_icontext_visible(self.get_option('show_icontext'))

        # Start process and give focus to console
        shellwidget.start_shell()
Example #21
0
def set_shortcut(context, name, keystr):
    """Set keyboard shortcut (key sequence string)"""
    CONF.set('shortcuts', '%s/%s' % (context, name), keystr)
Example #22
0
def get_shortcut(context, name):
    """Get keyboard shortcut (key sequence string)"""
    return CONF.get('shortcuts', '%s/%s' % (context, name))
Example #23
0
    def setup_page(self):
        interface_group = QGroupBox(_("Interface"))
        newcb = self.create_checkbox
        singletab_box = newcb(_("One tab per script"), 'single_tab')
        showtime_box = newcb(_("Show elapsed time"), 'show_elapsed_time')
        icontext_box = newcb(_("Show icons and text"), 'show_icontext')

        # Interface Group
        interface_layout = QVBoxLayout()
        interface_layout.addWidget(singletab_box)
        interface_layout.addWidget(showtime_box)
        interface_layout.addWidget(icontext_box)
        interface_group.setLayout(interface_layout)

        # Source Code Group
        display_group = QGroupBox(_("Source code"))
        buffer_spin = self.create_spinbox(_("Buffer: "),
                                          _(" lines"),
                                          'max_line_count',
                                          min_=0,
                                          max_=1000000,
                                          step=100,
                                          tip=_("Set maximum line count"))
        wrap_mode_box = newcb(_("Wrap lines"), 'wrap')
        merge_channels_box = newcb(
            _("Merge process standard output/error channels"),
            'merge_output_channels',
            tip=_("Merging the output channels of the process means that\n"
                  "the standard error won't be written in red anymore,\n"
                  "but this has the effect of speeding up display."))
        colorize_sys_stderr_box = newcb(
            _("Colorize standard error channel using ANSI escape codes"),
            'colorize_sys_stderr',
            tip=_("This method is the only way to have colorized standard\n"
                  "error channel when the output channels have been "
                  "merged."))
        merge_channels_box.toggled.connect(colorize_sys_stderr_box.setEnabled)
        merge_channels_box.toggled.connect(colorize_sys_stderr_box.setChecked)
        colorize_sys_stderr_box.setEnabled(
            self.get_option('merge_output_channels'))

        display_layout = QVBoxLayout()
        display_layout.addWidget(buffer_spin)
        display_layout.addWidget(wrap_mode_box)
        display_layout.addWidget(merge_channels_box)
        display_layout.addWidget(colorize_sys_stderr_box)
        display_group.setLayout(display_layout)

        # Background Color Group
        bg_group = QGroupBox(_("Background color"))
        bg_label = QLabel(
            _("This option will be applied the next time "
              "a Python console or a terminal is opened."))
        bg_label.setWordWrap(True)
        lightbg_box = newcb(_("Light background (white color)"),
                            'light_background')
        bg_layout = QVBoxLayout()
        bg_layout.addWidget(bg_label)
        bg_layout.addWidget(lightbg_box)
        bg_group.setLayout(bg_layout)

        # Advanced settings
        source_group = QGroupBox(_("Source code"))
        completion_box = newcb(_("Automatic code completion"),
                               'codecompletion/auto')
        case_comp_box = newcb(_("Case sensitive code completion"),
                              'codecompletion/case_sensitive')
        comp_enter_box = newcb(_("Enter key selects completion"),
                               'codecompletion/enter_key')
        calltips_box = newcb(_("Display balloon tips"), 'calltips')

        source_layout = QVBoxLayout()
        source_layout.addWidget(completion_box)
        source_layout.addWidget(case_comp_box)
        source_layout.addWidget(comp_enter_box)
        source_layout.addWidget(calltips_box)
        source_group.setLayout(source_layout)

        # PYTHONSTARTUP replacement
        pystartup_group = QGroupBox(_("PYTHONSTARTUP replacement"))
        pystartup_bg = QButtonGroup(pystartup_group)
        pystartup_label = QLabel(
            _("This option will override the "
              "PYTHONSTARTUP environment variable which\n"
              "defines the script to be executed during "
              "the Python console startup."))
        def_startup_radio = self.create_radiobutton(
            _("Default PYTHONSTARTUP script"),
            'pythonstartup/default',
            button_group=pystartup_bg)
        cus_startup_radio = self.create_radiobutton(
            _("Use the following startup script:"),
            'pythonstartup/custom',
            button_group=pystartup_bg)
        pystartup_file = self.create_browsefile('', 'pythonstartup', '',
                                                filters=_("Python scripts")+\
                                                " (*.py)")
        def_startup_radio.toggled.connect(pystartup_file.setDisabled)
        cus_startup_radio.toggled.connect(pystartup_file.setEnabled)

        pystartup_layout = QVBoxLayout()
        pystartup_layout.addWidget(pystartup_label)
        pystartup_layout.addWidget(def_startup_radio)
        pystartup_layout.addWidget(cus_startup_radio)
        pystartup_layout.addWidget(pystartup_file)
        pystartup_group.setLayout(pystartup_layout)

        # Monitor Group
        monitor_group = QGroupBox(_("Monitor"))
        monitor_label = QLabel(
            _("The monitor provides introspection "
              "features to console: code completion, "
              "calltips and variable explorer. "
              "Because it relies on several modules, "
              "disabling the monitor may be useful "
              "to accelerate console startup."))
        monitor_label.setWordWrap(True)
        monitor_box = newcb(_("Enable monitor"), 'monitor/enabled')
        for obj in (completion_box, case_comp_box, comp_enter_box,
                    calltips_box):
            monitor_box.toggled.connect(obj.setEnabled)
            obj.setEnabled(self.get_option('monitor/enabled'))

        monitor_layout = QVBoxLayout()
        monitor_layout.addWidget(monitor_label)
        monitor_layout.addWidget(monitor_box)
        monitor_group.setLayout(monitor_layout)

        # Qt Group
        opts = [
            (_("Default library"), 'default'),
            ('PyQt5', 'pyqt5'),
            ('PyQt4', 'pyqt'),
            ('PySide', 'pyside'),
        ]
        qt_group = QGroupBox(_("Qt-Python Bindings"))
        qt_setapi_box = self.create_combobox(
            _("Library:") + "   ",
            opts,
            'qt/api',
            default='default',
            tip=_("This option will act on<br> "
                  "libraries such as Matplotlib, guidata "
                  "or ETS"))

        qt_layout = QVBoxLayout()
        qt_layout.addWidget(qt_setapi_box)
        qt_group.setLayout(qt_layout)

        # Matplotlib Group
        mpl_group = QGroupBox(_("Graphics"))
        mpl_label = QLabel(
            _("Decide which backend to use to display graphics. "
              "If unsure, please select the <b>Automatic</b> "
              "backend.<br><br>"
              "<b>Note:</b> We support a very limited number "
              "of backends in our Python consoles. If you "
              "prefer to work with a different one, please use "
              "an IPython console."))
        mpl_label.setWordWrap(True)

        backends = [(_("Automatic"), 0), (_("None"), 1)]
        if not os.name == 'nt' and programs.is_module_installed('_tkinter'):
            backends.append(("Tkinter", 2))
        backends = tuple(backends)

        mpl_backend_box = self.create_combobox(
            _("Backend:") + "   ",
            backends,
            'matplotlib/backend/value',
            tip=_("This option will be applied the "
                  "next time a console is opened."))

        mpl_installed = programs.is_module_installed('matplotlib')
        mpl_layout = QVBoxLayout()
        mpl_layout.addWidget(mpl_label)
        mpl_layout.addWidget(mpl_backend_box)
        mpl_group.setLayout(mpl_layout)
        mpl_group.setEnabled(mpl_installed)

        # ETS Group
        ets_group = QGroupBox(_("Enthought Tool Suite"))
        ets_label = QLabel(
            _("Enthought Tool Suite (ETS) supports "
              "PyQt4 (qt4) and wxPython (wx) graphical "
              "user interfaces."))
        ets_label.setWordWrap(True)
        ets_edit = self.create_lineedit(_("ETS_TOOLKIT:"),
                                        'ets_backend',
                                        alignment=Qt.Horizontal)

        ets_layout = QVBoxLayout()
        ets_layout.addWidget(ets_label)
        ets_layout.addWidget(ets_edit)
        ets_group.setLayout(ets_layout)

        if CONF.get('main_interpreter', 'default'):
            interpreter = get_python_executable()
        else:
            interpreter = CONF.get('main_interpreter', 'executable')
        ets_group.setEnabled(
            programs.is_module_installed("enthought.etsconfig.api",
                                         interpreter=interpreter))

        tabs = QTabWidget()
        tabs.addTab(self.create_tab(interface_group, display_group, bg_group),
                    _("Display"))
        tabs.addTab(self.create_tab(monitor_group, source_group),
                    _("Introspection"))
        tabs.addTab(self.create_tab(pystartup_group), _("Advanced settings"))
        tabs.addTab(self.create_tab(qt_group, mpl_group, ets_group),
                    _("External modules"))

        vlayout = QVBoxLayout()
        vlayout.addWidget(tabs)
        self.setLayout(vlayout)
Example #24
0
def get_color_scheme(name):
    """Get syntax color scheme"""
    color_scheme = {}
    for key in sh.COLOR_SCHEME_KEYS:
        color_scheme[key] = CONF.get("color_schemes", "%s/%s" % (name, key))
    return color_scheme
Example #25
0
def reset_shortcuts():
    """Reset keyboard shortcuts to default values"""
    CONF.reset_to_defaults(section='shortcuts')
Example #26
0
def iter_shortcuts():
    """Iterate over keyboard shortcuts"""
    for option in CONF.options('shortcuts'):
        context, name = option.split("/", 1)
        yield context, name, get_shortcut(context, name)
Example #27
0
 def _load_all_breakpoints(self):
     bp_dict = CONF.get('run', 'breakpoints', {})
     for filename in list(bp_dict.keys()):
         if not osp.isfile(filename):
             bp_dict.pop(filename)
     return bp_dict
Example #28
0
 def get_option(self, option, default=NoDefault):
     """Get a plugin option from configuration file"""
     return CONF.get(self.CONF_SECTION, option, default)
Example #29
0
 def traceback_available(self):
     """Traceback is available in the internal console: showing the 
     internal console automatically to warn the user"""
     if CONF.get('main', 'show_internal_console_if_traceback', False):
         self.dockwidget.show()
         self.dockwidget.raise_()
Example #30
0
 def get_color_scheme(self):
     """Get current color scheme"""
     return get_color_scheme(CONF.get('color_schemes', 'selected'))