Esempio n. 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
Esempio n. 2
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 []
Esempio n. 3
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)
Esempio n. 4
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))))
Esempio n. 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)
Esempio n. 6
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'))
Esempio n. 7
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
Esempio n. 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
Esempio n. 9
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)
Esempio n. 10
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
Esempio n. 11
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)
Esempio n. 12
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)
Esempio n. 13
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()
Esempio n. 14
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
Esempio n. 15
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)
Esempio n. 16
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))
Esempio n. 17
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()
Esempio n. 18
0
def get_shortcut(context, name):
    """Get keyboard shortcut (key sequence string)"""
    return CONF.get('shortcuts', '%s/%s' % (context, name))
Esempio n. 19
0
def _set_run_configurations(configurations):
    history_count = CONF.get('run', 'history', 20)
    CONF.set('run', 'configurations', configurations[:history_count])
Esempio n. 20
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.current_radio = None
        self.dedicated_radio = None
        self.systerm_radio = None

        self.runconf = RunConfiguration()
        
        firstrun_o = CONF.get('run', ALWAYS_OPEN_FIRST_RUN_OPTION, False)

        # --- General settings ----
        common_group = QGroupBox(_("General settings"))
        common_layout = QGridLayout()
        common_group.setLayout(common_layout)
        self.clear_var_cb = QCheckBox(CLEAR_ALL_VARIABLES)
        common_layout.addWidget(self.clear_var_cb, 0, 0)
        self.clo_cb = QCheckBox(_("Command line options:"))
        common_layout.addWidget(self.clo_cb, 1, 0)
        self.clo_edit = QLineEdit()
        self.clo_cb.toggled.connect(self.clo_edit.setEnabled)
        self.clo_edit.setEnabled(False)
        common_layout.addWidget(self.clo_edit, 1, 1)
        self.wd_cb = QCheckBox(_("Working directory:"))
        common_layout.addWidget(self.wd_cb, 2, 0)
        wd_layout = QHBoxLayout()
        self.wd_edit = QLineEdit()
        self.wd_cb.toggled.connect(self.wd_edit.setEnabled)
        self.wd_edit.setEnabled(False)
        wd_layout.addWidget(self.wd_edit)
        browse_btn = QPushButton(ima.icon('DirOpenIcon'), '', self)
        browse_btn.setToolTip(_("Select directory"))
        browse_btn.clicked.connect(self.select_directory)
        wd_layout.addWidget(browse_btn)
        common_layout.addLayout(wd_layout, 2, 1)
        self.post_mortem_cb = QCheckBox(_("Enter debugging mode when "
                                          "errors appear during execution"))
        common_layout.addWidget(self.post_mortem_cb)
        

        
        # --- Interpreter ---
        interpreter_group = QGroupBox(_("Console"))
        interpreter_layout = QVBoxLayout()
        interpreter_group.setLayout(interpreter_layout)
        self.current_radio = QRadioButton(CURRENT_INTERPRETER)
        interpreter_layout.addWidget(self.current_radio)
        self.dedicated_radio = QRadioButton(DEDICATED_INTERPRETER)
        interpreter_layout.addWidget(self.dedicated_radio)
        self.systerm_radio = QRadioButton(SYSTERM_INTERPRETER)
        interpreter_layout.addWidget(self.systerm_radio)
        
        # --- Dedicated interpreter ---
        new_group = QGroupBox(_("Dedicated Python console"))
        self.current_radio.toggled.connect(new_group.setDisabled)
        new_layout = QGridLayout()
        new_group.setLayout(new_layout)
        self.interact_cb = QCheckBox(_("Interact with the Python "
                                       "console after execution"))
        new_layout.addWidget(self.interact_cb, 1, 0, 1, -1)
        
        self.show_kill_warning_cb = QCheckBox(_("Show warning when killing"
                                                " running process"))

        new_layout.addWidget(self.show_kill_warning_cb, 2, 0, 1, -1)
        self.pclo_cb = QCheckBox(_("Command line options:"))
        new_layout.addWidget(self.pclo_cb, 3, 0)
        self.pclo_edit = QLineEdit()
        self.pclo_cb.toggled.connect(self.pclo_edit.setEnabled)
        self.pclo_edit.setEnabled(False)
        self.pclo_edit.setToolTip(_("<b>-u</b> is added to the "
                                    "other options you set here"))
        new_layout.addWidget(self.pclo_edit, 3, 1)
        

        # Checkbox to preserve the old behavior, i.e. always open the dialog
        # on first run
        hline = QFrame()
        hline.setFrameShape(QFrame.HLine)
        hline.setFrameShadow(QFrame.Sunken)
        self.firstrun_cb = QCheckBox(ALWAYS_OPEN_FIRST_RUN % _("this dialog"))
        self.firstrun_cb.clicked.connect(self.set_firstrun_o)
        self.firstrun_cb.setChecked(firstrun_o)
        
        layout = QVBoxLayout()
        layout.addWidget(interpreter_group)
        layout.addWidget(common_group)
        layout.addWidget(new_group)
        layout.addWidget(hline)
        layout.addWidget(self.firstrun_cb)
        self.setLayout(layout)
Esempio n. 21
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
Esempio n. 22
0
 def get_color_scheme(self):
     """Get current color scheme"""
     return get_color_scheme(CONF.get('color_schemes', 'selected'))
Esempio n. 23
0
 def get_option(self, option, default=NoDefault):
     """Get a plugin option from configuration file"""
     return CONF.get(self.CONF_SECTION, option, default)
Esempio n. 24
0
def main():
    """
    Start TRex application.

    If single instance mode is turned on (default behavior) and an instance of
    TRex is already running, this will just parse and send command line
    options to the application.
    """
    # Parse command line options
    options, args = get_options()

    # Store variable to be used in self.restart (restart trex instance)
    os.environ['TREX_ARGS'] = str(sys.argv[1:])

    if CONF.get('main', 'single_instance') and not options.new_instance \
      and not options.reset_config_files and not running_in_mac_app():
        # Minimal delay (0.1-0.2 secs) to avoid that several
        # instances started at the same time step in their
        # own foots while trying to create the lock file
        time.sleep(random.randrange(1000, 2000, 90) / 10000.)

        # Lock file creation
        lock_file = get_conf_path('trex.lock')
        lock = lockfile.FilesystemLock(lock_file)

        # Try to lock trex.lock. If it's *possible* to do it, then
        # there is no previous instance running and we can start a
        # new one. If *not*, then there is an instance already
        # running, which is locking that file
        try:
            lock_created = lock.lock()
        except:
            # If locking fails because of errors in the lockfile
            # module, try to remove a possibly stale trex.lock.
            # This is reported to solve all problems with
            # lockfile (See issue 2363)
            try:
                if os.name == 'nt':
                    if osp.isdir(lock_file):
                        import shutil
                        shutil.rmtree(lock_file, ignore_errors=True)
                else:
                    if osp.islink(lock_file):
                        os.unlink(lock_file)
            except:
                pass

            # Then start TRex as usual and *don't* continue
            # executing this script because it doesn't make
            # sense
            from trex.app import mainwindow
            mainwindow.main()
            return

        if lock_created:
            # Start a new instance
            from trex.app import mainwindow
            mainwindow.main()
        else:
            # Pass args to TRex or print an informative
            # message
            if args:
                send_args_to_trex(args)
            else:
                print("TRex is already running. If you want to open a new \n"
                      "instance, please pass to it the --new-instance option")
    else:
        from trex.app import mainwindow
        mainwindow.main()
Esempio n. 25
0
from trex.py3compat import u

#==============================================================================
# General configuration
#==============================================================================

# If your extensions are in another directory, add it here. If the directory
# is relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.append(os.path.abspath('.'))

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.

# We need jsmath to get pretty plain-text latex in docstrings
math = CONF.get('help', 'math', '')

if sphinx_version < "1.1" or not math:
    extensions = ['sphinx.ext.jsmath']
else:
    extensions = ['sphinx.ext.mathjax']

# For scipy and matplotlib docstrings, which need this extension to
# be rendered correctly (see Issue 1138)
extensions.append('sphinx.ext.autosummary')

# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']

# MathJax load path (doesn't have effect for sphinx 1.0-)
mathjax_path = 'MathJax/MathJax.js'
Esempio n. 26
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
Esempio n. 27
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)
Esempio n. 28
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_()
Esempio n. 29
0
def kernel_config():
    """Create a config object with IPython kernel options."""
    from IPython.core.application import get_ipython_dir
    from traitlets.config.loader import Config, load_pyconfig_files
    if not IS_EXT_INTERPRETER:
        from trex.config.main import CONF
        from trex.utils.programs import is_module_installed
    else:
        # We add "trex" to sys.path for external interpreters,
        # so this works!
        # See create_kernel_spec of plugins/ipythonconsole
        from config.main import CONF
        from utils.programs import is_module_installed

    # ---- IPython config ----
    try:
        profile_path = osp.join(get_ipython_dir(), 'profile_default')
        cfg = load_pyconfig_files(
            ['ipython_config.py', 'ipython_kernel_config.py'], profile_path)
    except:
        cfg = Config()

    # ---- TRex config ----
    spy_cfg = Config()

    # Until we implement Issue 1052
    spy_cfg.InteractiveShell.xmode = 'Plain'

    # Run lines of code at startup
    run_lines_o = CONF.get('ipython_console', 'startup/run_lines')
    if run_lines_o:
        spy_cfg.IPKernelApp.exec_lines = [
            x.strip() for x in run_lines_o.split(',')
        ]
    else:
        spy_cfg.IPKernelApp.exec_lines = []

    # Clean terminal arguments input
    clear_argv = "import sys;sys.argv = [''];del sys"
    spy_cfg.IPKernelApp.exec_lines.append(clear_argv)

    # Pylab configuration
    mpl_backend = None
    mpl_installed = is_module_installed('matplotlib')
    pylab_o = CONF.get('ipython_console', 'pylab')

    if mpl_installed and pylab_o:
        # Get matplotlib backend
        backend_o = CONF.get('ipython_console', 'pylab/backend')
        if backend_o == 1:
            if is_module_installed('PyQt5'):
                auto_backend = 'qt5'
            elif is_module_installed('PyQt4'):
                auto_backend = 'qt4'
            elif is_module_installed('_tkinter'):
                auto_backend = 'tk'
            else:
                auto_backend = 'inline'
        else:
            auto_backend = ''
        backends = {
            0: 'inline',
            1: auto_backend,
            2: 'qt5',
            3: 'qt4',
            4: 'osx',
            5: 'gtk3',
            6: 'gtk',
            7: 'wx',
            8: 'tk'
        }
        mpl_backend = backends[backend_o]

        # Automatically load Pylab and Numpy, or only set Matplotlib
        # backend
        autoload_pylab_o = CONF.get('ipython_console', 'pylab/autoload')
        if autoload_pylab_o:
            spy_cfg.IPKernelApp.exec_lines.append(
                "%pylab {0}".format(mpl_backend))
        else:
            spy_cfg.IPKernelApp.exec_lines.append(
                "%matplotlib {0}".format(mpl_backend))

        # Inline backend configuration
        if mpl_backend == 'inline':
            # Figure format
            format_o = CONF.get('ipython_console',
                                'pylab/inline/figure_format', 0)
            formats = {0: 'png', 1: 'svg'}
            spy_cfg.InlineBackend.figure_format = formats[format_o]

            # Resolution
            if is_module_installed('ipykernel', '<4.5'):
                dpi_option = 'savefig.dpi'
            else:
                dpi_option = 'figure.dpi'

            spy_cfg.InlineBackend.rc = {
                'figure.figsize': (6.0, 4.0),
                dpi_option: 72,
                'font.size': 10,
                'figure.subplot.bottom': .125,
                'figure.facecolor': 'white',
                'figure.edgecolor': 'white'
            }
            resolution_o = CONF.get('ipython_console',
                                    'pylab/inline/resolution')
            spy_cfg.InlineBackend.rc[dpi_option] = resolution_o

            # Figure size
            width_o = float(CONF.get('ipython_console', 'pylab/inline/width'))
            height_o = float(CONF.get('ipython_console',
                                      'pylab/inline/height'))
            spy_cfg.InlineBackend.rc['figure.figsize'] = (width_o, height_o)

    # Run a file at startup
    use_file_o = CONF.get('ipython_console', 'startup/use_run_file')
    run_file_o = CONF.get('ipython_console', 'startup/run_file')
    if use_file_o and run_file_o:
        spy_cfg.IPKernelApp.file_to_run = run_file_o

    # Autocall
    autocall_o = CONF.get('ipython_console', 'autocall')
    spy_cfg.ZMQInteractiveShell.autocall = autocall_o

    # To handle the banner by ourselves in IPython 3+
    spy_cfg.ZMQInteractiveShell.banner1 = ''

    # Greedy completer
    greedy_o = CONF.get('ipython_console', 'greedy_completer')
    spy_cfg.IPCompleter.greedy = greedy_o

    # Sympy loading
    sympy_o = CONF.get('ipython_console', 'symbolic_math')
    if sympy_o and is_module_installed('sympy'):
        lines = sympy_config(mpl_backend)
        spy_cfg.IPKernelApp.exec_lines.append(lines)

    # Merge IPython and TRex configs. TRex prefs will have prevalence
    # over IPython ones
    cfg._merge(spy_cfg)
    return cfg