Exemplo n.º 1
0
    def _sig_path_entry_activate(self, entry, msg, task):
        if 'z_run_cmd' in msg:
            # M-x initiated
            self.get_editor().get_last_line().start_mx_commanding(
                msg['z_run_cmd'])
            return

        if task == 'activate' and msg['return_msg'] == 'Accept':
            # activate key is pressed
            fullpath = io_encap.norm_path(self.path_entry.get_text())
            fn_list = os.path.split(fullpath)

            if io_encap.is_dir(fn_list):
                self.set_folder(fullpath)
            elif io_encap.is_file(fn_list):
                self.open_file(fn_list)
            else:
                self.update_path_entry()
                raise ValueError(
                    'Cannot open "{0}".\n    Make sure the path is spelled correctly.'
                    .format(fullpath))

        elif task == 'cancel' and msg['return_msg'] == 'Quit':
            # cancel key is pressed
            self.update_path_entry()
Exemplo n.º 2
0
    def set_folder(self, fullpath=None):
        # get real path
        if not fullpath:
            new_dirname = zTheme.env['starting_path']
        else:
            new_dirname = io_encap.norm_path(fullpath)

        # test permission
        if not os.access(new_dirname, os.F_OK):
            raise AssertionError('Fatal Error: directory does not exist!')
        if not os.access(new_dirname, os.R_OK):
            raise AssertionError('Permission Denied: directory not readable!')
        if not os.access(new_dirname, os.X_OK):
            raise AssertionError('Permission Denied: directory not navigable!')

        # begin to changing folder
        if self.__on_setting_folder:
            return  # early return
        else:
            self.__on_setting_folder = True

        self.dirname = new_dirname
        self.treeview.dirname = self.dirname

        # fetch file listing
        self.__file_list = []
        self.__dir_list = []
        for non_hidden in [
                fn for fn in os.listdir(self.dirname) if fn[0] <> '.'
        ]:
            fn_list = [self.dirname, non_hidden]
            if io_encap.is_dir(fn_list):
                self.__dir_list.append(non_hidden)
            else:
                self.__file_list.append(non_hidden)

        self.__file_list.sort(key=str.lower)
        self.__dir_list.sort(key=str.lower)
        self.__dir_list = ['..'] + self.__dir_list

        # update model with the listing
        self.treeview.model.clear()
        for fn in self.__dir_list:
            self.treeview.model.append([fn, False])
        for fn in self.__file_list:
            self.treeview.model.append([fn, False])

        self.update_path_entry()

        # clear flags
        for key in self.__cell_data_func_skip:
            self.__cell_data_func_skip[key] = None
        self.__file_name_old = ''

        self.__on_setting_folder = False
Exemplo n.º 3
0
    def set_db(self, db_file):
        if self.__on_init:
            return  # on initializing, early return

        if zDisplayPanel._DB_FILE:
            db_file = zDisplayPanel._DB_FILE  # force switch to overall setting

        # normalize path
        db_file = io_encap.norm_path(db_file)
        if self.__db_file:
            if self.__db_file == db_file:
                return  # no need to change, early return
            else:
                self.disconnect_db()

        if db_file:
            self.__db_file = db_file
            self.connect_db()
        else:
            self.__db_file = None
Exemplo n.º 4
0
# this is the "Major Editing Mode" selector
# each Major Mode is defined as an resource module in "zMajorMode"
# resource folder, or in user's config folder (~/.zPE/)

from zPE.GUI import min_import, GUI_PGK_PATH
from zPE.GUI.io_encap import norm_path, list_dir

from zPE.GUI.conf import CONFIG_PATH, MODE_MAP, DEFAULT_BUFF_MODE_MAP as DEFAULT

import os, sys

SEARCH_PATH = {
    'global': norm_path(os.path.join(GUI_PGK_PATH[0], "zMajorMode")),
    'user': norm_path(CONFIG_PATH['dir']),
}

# BaseMode need to be imported the EXACT SAME WAY as other modes are
_base_ = min_import('zPE.GUI.basemode', ['BaseMode'], 0)


def load_mode(path):
    for fn in list_dir(path):
        [mn, ext] = os.path.splitext(fn)  # Handles no-extension files, etc.
        if ext == '.py':
            cn = mn.title() + 'Mode'
            try:
                _cls_ = min_import(mn, [cn], -1, path)
                _obj_ = _cls_()
            except:
                sys.stderr.write(
                    'warn: {0}: Fail to load Major Mode Module.\n'.format(cn))
Exemplo n.º 5
0
 def set_db_all(db_file):
     if db_file:
         zDisplayPanel._DB_FILE = io_encap.norm_path(db_file)
     else:
         zDisplayPanel._DB_FILE = None
    def _sig_key_pressed(self, widget, event, task, init_widget=None):
        #        self.__debug_print_maps()

        if event.type != gtk.gdk.KEY_PRESS:
            return False

        if event.is_modifier:
            return False

        ### generate stroke
        ctrl_mod_mask = gtk.gdk.CONTROL_MASK | gtk.gdk.MOD1_MASK

        # check and re-map punctuation mark
        key_name = gtk.gdk.keyval_name(event.keyval)
        if key_name in PUNCT_KEY_MAP:
            # punctuation
            key_name = PUNCT_KEY_MAP[key_name]

        elif key_name.upper() in FUNC_KEY_MAP:
            # function key
            if event.state & gtk.gdk.SHIFT_MASK:
                # only check SHIFT modifier when a function key is pressed
                key_name = 'S-' + key_name

        elif len(key_name) == 1 and key_name.isalpha():
            # letters
            if (event.state & gtk.gdk.LOCK_MASK) == gtk.gdk.LOCK_MASK:
                key_name = key_name.swapcase()

        if (event.state & ctrl_mod_mask) == ctrl_mod_mask:
            stroke = 'C-M-' + key_name

        elif event.state & gtk.gdk.CONTROL_MASK:
            stroke = 'C-' + key_name

        elif event.state & gtk.gdk.MOD1_MASK:
            stroke = 'M-' + key_name

        else:
            stroke = key_name

        if task == 'func':
            self.__entry_entering = True

        # initialize the editable flag
        try:
            w_editable = widget.get_editable()
        except:
            w_editable = None

        ### style-regardless checkings
        # check Cancelling
        if is_sp_func_key(stroke, 'CANCEL', self.get_style()):
            # with any style, this means 'cancel'
            if not init_widget or task != 'func':
                # init_widget not set, or in regular mode (non-mx-mode)
                init_widget = widget
            self.emit('z_cancel', self.__build_msg(init_widget, stroke,
                                                   'Quit'))
            self.__update_last_cmd('Quit')

            # on cancelling, reset all modes
            self.__combo_entering = False
            self.__combo_content = ''

            self.__entry_entering = False
            self.__entry_content = ''

            return True
        # no Cancelling

        # check Activating
        if (not self.__combo_entering and  # must not on combo-entering, and
                is_sp_func_key(stroke, 'ACTIVATE',
                               self.get_style())  # the activate kay is pressed
            ):
            if task == 'text':
                return False  # pass 'Enter' to the widget to handle

            elif task == 'func':
                # is on M-x commanding
                self.__entry_content = widget.get_text(
                )  # update the content backup
                if not init_widget:  # set the responing widget
                    init_widget = widget

                local_is_enabled_func = init_widget.listener.is_enabled_func
                local_func_callback_map = init_widget.listener.func_callback_map

                if self.__is_enabled_func(self.__entry_content,
                                          local_is_enabled_func):
                    # is a valid functionality

                    if self.__entry_content in local_func_callback_map:
                        # has registered function
                        self.__z_activate_callback = local_func_callback_map[
                            self.__entry_content]
                        self.emit(
                            'z_activate',
                            self.__build_msg(init_widget, stroke, 'Accept'))
                        self.__z_activate_callback = None

                    elif self.__entry_content in zStrokeListener.global_func_callback_map:
                        # has globally registered function
                        self.__z_activate_callback = zStrokeListener.global_func_callback_map[
                            self.__entry_content]
                        self.emit(
                            'z_activate',
                            self.__build_msg(init_widget, stroke, 'Accept'))
                        self.__z_activate_callback = None
                    else:
                        self.emit(
                            'z_cancel',
                            self.__build_msg(
                                init_widget, stroke,
                                '(function `{0}` not implemented)'.format(
                                    self.__entry_content)))
                else:
                    self.emit(
                        'z_cancel',
                        self.__build_msg(
                            init_widget, stroke,
                            '({0}: no such function)'.format(
                                self.__entry_content)))

                # record the function the init_widget is trying to invoke
                init_widget.listener.__update_last_cmd(self.__entry_content)

                # M-x cmd emitted, reset entering mode
                self.__entry_entering = False
                self.__entry_content = ''

                return True

            # must be 'file', 'dir', or 'path'
            path_entered = widget.get_text()
            if path_entered:
                # normalize path
                if '"' in path_entered:
                    path_entered = path_entered.replace('"', '')
                path_entered = io_encap.norm_path(path_entered)
                widget.set_text(path_entered)

                if ((task == 'file' and not os.path.isdir(path_entered))
                        or (task == 'dir' and not os.path.isfile(path_entered))
                        or (task == 'path')):
                    self.emit('z_activate',
                              self.__build_msg(widget, stroke, 'Accept'))
                    self.__update_last_cmd('Activate')

                elif self.__is_enabled_func('complete-list'):
                    # list completion is enabled, execute it if mapped
                    if 'complete-list' in self.func_callback_map:
                        self.func_callback_map['complete-list']()
                    elif 'complete-list' in zStrokeListener.global_func_callback_map:
                        zStrokeListener.global_func_callback_map[
                            'complete-list']()

            return True
        # no Activating

        ### style-specific checkings
        if self.get_style() == 'emacs':
            # style::emacs

            # check C-q Escaping
            if self.__escaping:  # this should guarantee no combo is entering
                try:
                    if w_editable:
                        if self.__is_printable(stroke):
                            insertion = stroke

                        elif stroke.upper() in self.__ctrl_char_map:
                            insertion = self.__ctrl_char_map[stroke.upper()]

                        else:
                            insertion = ''  # ignore the rest ctrl chars

                        self.__insert_text(widget, insertion)
                    else:
                        pass  # no need to handle C-q escaping when the widget is not editable
                except:
                    pass  # if anything goes wrong, give up the escaping

                self.__escaping = False
                return True
            # no C-q Escaping

            # check M-x Commanding input
            if (not self.__combo_entering and self.__entry_entering):
                # on M-x Commanding, Commanding *MUST NOT* be initiated
                if self.__is_printable(stroke):
                    # regular keypress
                    self.__insert_text(widget, stroke)
                    return True
                elif self.__is_space(stroke):
                    # space
                    self.__insert_text(widget, ' ')
                    return True
                else:
                    # leave the rest checking to commanding
                    pass
            # no active M-x Commanding, or stroke is passed on

            # check initiated Commanding
            if not self.__combo_entering:
                # initiating stroke, check reserved bindings (M-x and C-q)
                if stroke == 'M-x':
                    self.emit('z_activate', {'z_run_cmd': widget})
                    return True

                elif stroke == 'C-q':
                    # start C-q Escaping
                    if w_editable:
                        self.__escaping = True
                    else:
                        pass  # no need to handle C-q escaping when the widget is not editable
                    return True

                # not reserved bindings, check forbidden bindings (printable)
                elif self.__is_printable(stroke):
                    # is a printable
                    if w_editable:
                        self.__insert_text(widget, stroke)
                    else:
                        self.emit('z_activate',
                                  self.__build_msg(widget, stroke, ''))
                    return True

                # not any reserved or forbidden bindings
                # initiate Commanding
                self.__combo_entering = True
                self.__combo_focus_widget = widget
                self.__combo_focus_widget_id = widget.connect(
                    'focus-out-event', self._sig_kp_focus_out)
            # Commanding initiated

            # on commanding
            # retrieve previous combo, if there is any
            if self.__combo_content:
                # appand previous combo to stroke
                stroke = '{0} {1}'.format(self.__combo_content, stroke)

            # validate stroke sequence
            key_binding = zStrokeListener.__key_func_binding  # make a reference

            if stroke in key_binding and self.__is_enabled_func(
                    key_binding[stroke]):
                # is a valid functionality
                self.__combo_content = stroke
                self.__kp_focus_out_rm()  # release focus requirement

                if key_binding[stroke] in self.func_callback_map:
                    # has registered functions
                    self.__z_activate_callback = self.func_callback_map[
                        key_binding[stroke]]
                    self.emit('z_activate',
                              self.__build_msg(widget, stroke, ''))
                    self.__z_activate_callback = None

                elif key_binding[
                        stroke] in zStrokeListener.global_func_callback_map:
                    # has globally registered function
                    self.__z_activate_callback = zStrokeListener.global_func_callback_map[
                        key_binding[stroke]]
                    self.emit('z_activate',
                              self.__build_msg(widget, stroke, ''))
                    self.__z_activate_callback = None
                else:
                    self.emit(
                        'z_cancel',
                        self.__build_msg(
                            widget, stroke,
                            '(function `{0}` not implemented)'.format(
                                key_binding[stroke])))

                # record the function the widget is trying to invoke
                self.__update_last_cmd(key_binding[stroke])

                # cmd emitted, reset combo mode
                self.__combo_entering = False
                self.__combo_content = ''

                return True
            else:
                # not a valid stroke sequence so far
                found = False
                for key in key_binding:
                    if key.startswith(stroke):
                        # part of a valid stroke sequence
                        self.emit('z_activate',
                                  self.__build_msg(widget, stroke, 'z_combo'))

                        found = True
                        break

                if found:
                    self.__combo_content = stroke
                    return True
                else:
                    # not a valid stroke sequence *AT ALL*
                    self.__kp_focus_out_rm()  # release focus requirement

                    if not self.__combo_content:
                        # initiate stroke, do not eat it
                        self.__combo_entering = False

                        if self.__is_space(stroke):
                            # space
                            if w_editable:
                                self.__insert_text(widget, ' ')
                            else:
                                self.emit('z_activate',
                                          self.__build_msg(widget, ' ', ''))
                            return True
                        else:
                            # not regular keypress nor space, pass it to the widget
                            self.__update_last_cmd(None)
                            return False
                    else:
                        # has previous combo, eat the current combo
                        self.emit(
                            'z_cancel',
                            self.__build_msg(widget, stroke,
                                             stroke + ' is undefined!'))
                        self.__update_last_cmd(None)

                        # cmd terminated, reset combo mode
                        self.__combo_entering = False
                        self.__combo_content = ''

                        return True

        elif self.get_style() == 'vi':
            # style::vi
            return False  # not implemetad yet

        else:
            # style::other
            key_binding = zStrokeListener.__key_func_binding  # make a reference

            if (stroke in key_binding and  # is a binded key stroke
                    self.__is_enabled_func(
                        key_binding[stroke])  # is a valid functionality
                ):
                if key_binding[stroke] in self.func_callback_map:
                    # has registered functions
                    self.__z_activate_callback = self.func_callback_map[
                        key_binding[stroke]]
                    self.emit('z_activate',
                              self.__build_msg(widget, stroke, ''))
                    self.__z_activate_callback = None

                elif key_binding[
                        stroke] in zStrokeListener.global_func_callback_map:
                    # has globally registered function
                    self.__z_activate_callback = zStrokeListener.global_func_callback_map[
                        key_binding[stroke]]
                    self.emit('z_activate',
                              self.__build_msg(widget, stroke, ''))
                    self.__z_activate_callback = None
                else:
                    self.emit(
                        'z_cancel',
                        self.__build_msg(
                            widget, stroke,
                            '(function `{0}` not implemented)'.format(
                                key_binding[stroke])))
                # record the function the widget is trying to invoke
                self.__update_last_cmd(key_binding[stroke])

                return True
            else:
                if self.__is_printable(stroke):
                    # regular keypress
                    if w_editable:
                        self.__insert_text(widget, stroke)
                    else:
                        self.emit('z_activate',
                                  self.__build_msg(widget, stroke, ''))
                    return True
                elif self.__is_space(stroke):
                    # space
                    if w_editable:
                        self.__insert_text(widget, ' ')
                    else:
                        self.emit('z_activate',
                                  self.__build_msg(widget, ' ', ''))
                    return True
                else:
                    # not regular keypress nor space, pass it to the widget
                    self.__update_last_cmd(None)
                    return False

        raise LookupError(
            '{0}: key stroke not captured or processed.\n\tPlease report this as a bug.'
            .format(stroke))
def read_rc():
    init_rc()
    __CK_CONFIG()

    label = None
    for line in open(CONFIG_PATH['gui_rc'], 'r'):
        if line.isspace():  # skip empty line
            continue

        line = line[:-1]  # get rid of the '\n'

        if line in ['[MISC]', '[FONT]', '[COLOR_MAP]', '[ENV]']:
            label = line[1:-1]  # retrieve the top-level key
            continue

        if not label:
            continue  # no top-level key so far, skip the line

        (k, v) = re.split('[ \t]*=[ \t]*', line, maxsplit=1)

        if label == 'MISC':
            if k in [
                    'tab_on',
                    'tab_grouped',
                    'debug_mode',
            ]:
                if v and v not in STR_FALSE:
                    Config[label][k] = 1
                else:
                    Config[label][k] = 0

            elif k == 'key_binding':
                if v in DEFAULT_FUNC_KEY_BIND_KEY:
                    Config[label][k] = v
                else:
                    Config[label][k] = DEFAULT['MISC']['KEY_BINDING']
                    sys.stderr.write(
                        'CONFIG WARNING: {0}: Invalid key binding style.\n'.
                        format(v))

            elif k == 'kill_ring_sz':
                try:
                    v = int(v)
                    if v >= 1:
                        Config[label][k] = v
                    else:
                        sys.stderr.write(
                            'CONFIG WARNING: {0}: Kill-ring size must be at least 1.\n'
                            .format(v))
                except ValueError:
                    Config[label][k] = DEFAULT['MISC']['KILL_RING_SZ']
                    sys.stderr.write(
                        'CONFIG WARNING: {0}: Invalid kill-ring size.\n'.
                        format(v))

        elif label == 'FONT':
            if k == 'name':
                found = False
                for font in MONO_FONT:
                    if font == v:
                        Config[label][k] = v
                        found = True
                        break

                if not found:
                    sys.stderr.write(
                        'CONFIG WARNING: {0}: Invalid font name.\n'.format(v))

            elif k == 'size':
                try:
                    Config[label][k] = int(v)
                except ValueError:
                    Config[label][k] = DEFAULT['FONT_SZ']
                    sys.stderr.write(
                        'CONFIG WARNING: {0}: Invalid font size.\n'.format(v))

        elif label == 'COLOR_MAP':
            if v.lower() in COLOR_LIST:
                v_ty = 'name'
                v = COLOR_LIST[v]
            else:
                v_ty = 'code'

            v = v.upper()  # convert hex color code to all upper case
            if not re.match('#[0-9A-F]{6}', v):
                sys.stderr.write(
                    'CONFIG WARNING: {0}: Invalid color {1}.\n'.format(
                        v, v_ty))
                continue

            # valid color, check key
            if k in Config[label]:
                Config[label][k] = v
            else:
                sys.stderr.write(
                    'CONFIG WARNING: {0}: Invalid color mapping.\n'.format(k))

        elif label == 'ENV':
            if k == 'starting_path':
                tmp_v = io_encap.norm_path(v)
                if os.path.isdir(tmp_v):
                    Config[label][k] = tmp_v
                else:
                    Config[label][k] = io_encap.norm_path(
                        DEFAULT['ENV']['STARTING_PATH'])
                    sys.stderr.write(
                        'CONFIG WARNING: {0}: Invalid starting path.\n'.format(
                            v))
    write_rc()