예제 #1
0
def command_prompt(pymux, variables):
    """
    Enter command prompt.
    """
    client_state = pymux.get_client_state()

    if variables['<command>']:
        # When a 'command' has been given.
        client_state.prompt_text = variables['<message>'] or '(%s)' % variables['<command>'].split()[0]
        client_state.prompt_command = variables['<command>']

        client_state.prompt_mode = True
        client_state.prompt_buffer.reset(Document(
            format_pymux_string(pymux, variables['<default>'] or '')))

        get_app().layout.focus(client_state.prompt_buffer)
    else:
        # Show the ':' prompt.
        client_state.prompt_text = ''
        client_state.prompt_command = ''

        get_app().layout.focus(client_state.command_buffer)

    # Go to insert mode.
    get_app().vi_state.input_mode = InputMode.INSERT
예제 #2
0
파일: view.py 프로젝트: dagraham/etm-mv
 def coroutine():
     dialog = ConfirmDialog("cancel timer", f"item: {item_info}\nelapsed time: {time_str}\n\nclose timer without recording?")
     record_cancel = yield From(show_dialog_as_float(dialog))
     if record_cancel:
         dataview.timer_clear()
         set_text(dataview.show_active_view())
         get_app().invalidate()
    def apply_transformation(
            self, transformation_input: TransformationInput) -> Transformation:

        buffer_control, document, lineno, source_to_display, fragments, _, _ = transformation_input.unpack()

        # When the application is in the 'done' state, don't highlight.
        if get_app().is_done:
            return Transformation(fragments)

        # Get the highlight positions.
        key = (get_app().render_counter, document.text, document.cursor_position)
        positions = self._positions_cache.get(
            key, lambda: self._get_positions_to_highlight(document))

        # Apply if positions were found at this line.
        if positions:
            for row, col in positions:
                if row == lineno:
                    col = source_to_display(col)
                    fragments = explode_text_fragments(fragments)
                    style, text, *_ = fragments[col]

                    if col == document.cursor_position_col:
                        style += ' class:matching-bracket.cursor '
                    else:
                        style += ' class:matching-bracket.other '

                    fragments[col] = (style, text)

        return Transformation(fragments)
예제 #4
0
파일: view.py 프로젝트: dagraham/etm-mv
def data_changed(loop):
    dataview.refreshRelevant()
    dataview.refreshAgenda()
    set_text(dataview.show_active_view())
    dataview.refreshCurrent()
    if dataview.current_row:
        text_area.buffer.cursor_position = text_area.buffer.document.translate_row_col_to_index(dataview.current_row, 0)
    get_app().invalidate()
    def mouse_handler(self, mouse_event: MouseEvent) -> 'NotImplementedOrNone':
        """
        Mouse handler for this control.
        """
        buffer = self.buffer
        position = mouse_event.position

        # Focus buffer when clicked.
        if get_app().layout.current_control == self:
            if self._last_get_processed_line:
                processed_line = self._last_get_processed_line(position.y)

                # Translate coordinates back to the cursor position of the
                # original input.
                xpos = processed_line.display_to_source(position.x)
                index = buffer.document.translate_row_col_to_index(position.y, xpos)

                # Set the cursor position.
                if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
                    buffer.exit_selection()
                    buffer.cursor_position = index

                elif mouse_event.event_type == MouseEventType.MOUSE_UP:
                    # When the cursor was moved to another place, select the text.
                    # (The >1 is actually a small but acceptable workaround for
                    # selecting text in Vi navigation mode. In navigation mode,
                    # the cursor can never be after the text, so the cursor
                    # will be repositioned automatically.)
                    if abs(buffer.cursor_position - index) > 1:
                        buffer.start_selection(selection_type=SelectionType.CHARACTERS)
                        buffer.cursor_position = index

                    # Select word around cursor on double click.
                    # Two MOUSE_UP events in a short timespan are considered a double click.
                    double_click = self._last_click_timestamp and time.time() - self._last_click_timestamp < .3
                    self._last_click_timestamp = time.time()

                    if double_click:
                        start, end = buffer.document.find_boundaries_of_current_word()
                        buffer.cursor_position += start
                        buffer.start_selection(selection_type=SelectionType.CHARACTERS)
                        buffer.cursor_position += end - start
                else:
                    # Don't handle scroll events here.
                    return NotImplemented

        # Not focused, but focusing on click events.
        else:
            if self.focus_on_click() and mouse_event.event_type == MouseEventType.MOUSE_UP:
                # Focus happens on mouseup. (If we did this on mousedown, the
                # up event will be received at the point where this widget is
                # focused and be handled anyway.)
                get_app().layout.current_control = self
            else:
                return NotImplemented

        return None
예제 #6
0
                def ready():
                    self._reporter_is_running = False

                    # If the text has not been changed yet in the meantime, set
                    # reporter errors. (We were running in another thread.)
                    if text == self.buffer.text:
                        self.report_errors = report_errors
                        get_app().invalidate()
                    else:
                        # Restart reporter when the text was changed.
                        self.run_reporter()
예제 #7
0
파일: view.py 프로젝트: dagraham/etm-mv
def new_day(loop):
    logger.info(f"new_day currentYrWk: {dataview.currentYrWk}")
    dataview.refreshRelevant()
    dataview.activeYrWk = dataview.currentYrWk
    dataview.refreshAgenda()
    dataview.refreshCurrent()
    dataview.set_active_view('a')
    set_text(dataview.show_active_view())
    get_app().invalidate()
    dataview.handle_backups()
    dataview.possible_archive()
예제 #8
0
    def display_popup(self, title, content):
        """
        Display a pop-up dialog.
        """
        assert isinstance(title, six.text_type)
        assert isinstance(content, six.text_type)

        self.popup_dialog.title = title
        self._popup_textarea.text = content
        self.client_state.display_popup = True
        get_app().layout.focus(self._popup_textarea)
예제 #9
0
파일: view.py 프로젝트: dagraham/etm-mv
def event_handler(loop):
    global current_datetime
    now = pendulum.now()
    current_today = dataview.now.format("YYYYMMDD")
    maybe_alerts(now)
    current_datetime = status_time(now)
    today = now.format("YYYYMMDD")
    if today != current_today:
        logger.debug(f"calling new_day. current_today: {current_today}; today: {today}")
        loop.call_later(0, new_day, loop)
    get_app().invalidate()
    wait = 60 - now.second
    loop.call_later(wait, event_handler, loop)
 def _get_main_buffer(self, buffer_control: 'BufferControl') -> Optional['BufferControl']:
     from prompt_toolkit.layout.controls import BufferControl
     prev_control = get_app().layout.search_target_buffer_control
     if isinstance(prev_control, BufferControl) and \
             prev_control.search_buffer_control == buffer_control:
         return prev_control
     return None
    def _start_timeout(self) -> None:
        """
        Start auto flush timeout. Similar to Vim's `timeoutlen` option.

        Start a background thread with a timer. When this timeout expires and
        no key was pressed in the meantime, we flush all data in the queue and
        call the appropriate key binding handlers.
        """
        timeout = get_app().timeoutlen

        if timeout is None:
            return

        counter = self._keys_pressed

        async def wait() -> None:
            " Wait for timeout. "
            await sleep(timeout)

            if len(self.key_buffer) > 0 and counter == self._keys_pressed:
                # (No keys pressed in the meantime.)
                flush_keys()

        def flush_keys() -> None:
            " Flush keys. "
            self.feed(_Flush)
            self.process_keys()

        # Automatically flush keys.
        # (_daemon needs to be set, otherwise, this will hang the
        # application for .5 seconds before exiting.)
        ensure_future(wait())
 def preferred_height(self, width, max_available_height, wrap_lines,
                      get_line_prefix):
     complete_state = get_app().current_buffer.complete_state
     if complete_state:
         return len(complete_state.completions)
     else:
         return 0
예제 #13
0
def completion_is_selected():
    """
    True when the user selected a completion.
    """
    complete_state = get_app().current_buffer.complete_state
    return (complete_state is not None and
            complete_state.current_completion is not None)
    def create_content(self, width, height):
        """
        Create a UIContent object for this control.
        """
        complete_state = get_app().current_buffer.complete_state
        if complete_state:
            completions = complete_state.completions
            index = complete_state.complete_index  # Can be None!

            # Calculate width of completions menu.
            menu_width = self._get_menu_width(width, complete_state)
            menu_meta_width = self._get_menu_meta_width(width - menu_width, complete_state)
            show_meta = self._show_meta(complete_state)

            def get_line(i):
                c = completions[i]
                is_current_completion = (i == index)
                result = _get_menu_item_fragments(
                    c, is_current_completion, menu_width, space_after=True)

                if show_meta:
                    result += self._get_menu_item_meta_fragments(c, is_current_completion, menu_meta_width)
                return result

            return UIContent(get_line=get_line,
                             cursor_position=Point(x=0, y=index or 0),
                             line_count=len(completions))

        return UIContent()
예제 #15
0
def vi_recording_macro():
    " When recording a Vi macro. "
    app = get_app()
    if app.editing_mode != EditingMode.VI:
        return False

    return app.vi_state.recording_register is not None
예제 #16
0
def emacs_insert_mode():
    app = get_app()
    if (app.editing_mode != EditingMode.EMACS
            or app.current_buffer.selection_state
            or app.current_buffer.read_only()):
        return False
    return True
예제 #17
0
def control_is_searchable():
    " When the current UIControl is searchable. "
    from prompt_toolkit.layout.controls import BufferControl
    control = get_app().layout.current_control

    return (isinstance(control, BufferControl) and
            control.search_buffer_control is not None)
예제 #18
0
    def get_client_state(self):
        " Return the active ClientState instance. "
        app = get_app()
        for client_state in self._client_states.values():
            if client_state.app == app:
                return client_state

        raise ValueError('Client state for app %r not found' % (app, ))
예제 #19
0
    def get_connection(self):
        " Return the active Connection instance. "
        app = get_app()
        for connection, client_state in self._client_states.items():
            if client_state.app == app:
                return connection

        raise ValueError('Connection for app %r not found' % (app, ))
예제 #20
0
    def get_previous_active_window(self):
        " The previous active Window or None if unknown. "
        app = get_app()

        try:
            return self._prev_active_window_for_cli[app]
        except KeyError:
            return None
예제 #21
0
    def set_active_window(self, window):
        assert isinstance(window, Window)
        app = get_app()

        previous = self.get_active_window()
        self._prev_active_window_for_cli[app] = previous
        self._active_window_for_cli[app] = window
        self._last_active_window = window
예제 #22
0
def whitespace_or_bracket_after():
    """Check if there is whitespace or a closing
       bracket to the right of the cursor"""
    d = get_app().current_buffer.document
    return bool(
        d.is_cursor_at_the_end_of_line
        or d.current_char.isspace()
        or d.current_char in ")]}"
    )
    def preferred_width(self, max_available_width):
        complete_state = get_app().current_buffer.complete_state
        if complete_state:
            menu_width = self._get_menu_width(500, complete_state)
            menu_meta_width = self._get_menu_meta_width(500, complete_state)

            return menu_width + menu_meta_width
        else:
            return 0
예제 #24
0
def end_of_line():
    """Check if cursor is at the end of a line other than the last line in a
    multiline document
    """
    d = get_app().current_buffer.document
    at_end = d.is_cursor_at_the_end_of_line
    last_line = d.is_cursor_at_the_end

    return bool(at_end and not last_line)
예제 #25
0
def tab_insert_indent():
    """Check if <Tab> should insert indent instead of starting autocompletion.
    Checks if there are only whitespaces before the cursor - if so indent
    should be inserted, otherwise autocompletion.

    """
    before_cursor = get_app().current_buffer.document.current_line_before_cursor

    return bool(before_cursor.isspace())
 def _get_formatted_text_cached(self) -> StyleAndTextTuples:
     """
     Get fragments, but only retrieve fragments once during one render run.
     (This function is called several times during one rendering, because
     we also need those for calculating the dimensions.)
     """
     return self._fragment_cache.get(
         get_app().render_counter,
         lambda: to_formatted_text(self.text, self.style))
예제 #27
0
            def test():
                # Consider focused when any window inside this container is
                # focused.
                current_window = get_app().layout.current_window

                for c in walk(value):
                    if isinstance(c, Window) and c == current_window:
                        return True
                return False
예제 #28
0
def whitespace_or_bracket_before():
    """Check if there is whitespace or an opening
       bracket to the left of the cursor"""
    d = get_app().current_buffer.document
    return bool(
        d.cursor_position == 0
        or d.char_before_cursor.isspace()
        or d.char_before_cursor in "([{"
    )
        def get_formatted_text():
            arg = get_app().key_processor.arg or ''
            if arg == '-':
                arg = '-1'

            return [
                ('class:arg-toolbar', 'Repeat: '),
                ('class:arg-toolbar.text', arg),
            ]
    def preferred_height(
            self, width: int, max_available_height: int, wrap_lines: bool,
            get_line_prefix: Optional[GetLinePrefixCallable]) -> Optional[int]:

        complete_state = get_app().current_buffer.complete_state
        if complete_state:
            return len(complete_state.completions)
        else:
            return 0
예제 #31
0
 def any_completion_has_meta() -> bool:
     complete_state = get_app().current_buffer.complete_state
     return complete_state is not None and any(
         c.display_meta for c in complete_state.completions)
예제 #32
0
def cursor_at_begin():
    return get_app().current_buffer.cursor_position == 0
예제 #33
0
def exit_clicked():
    get_app().exit()
예제 #34
0
 def prase_complete():
     app = get_app()
     return prase_text_complete(app.current_buffer.text)
예제 #35
0
        def _(event):
            """Exit interactive mode"""

            get_app().exit(exception=pwncat.manager.InteractiveExit())
예제 #36
0
def on_f10_pressed(event=None):
    """Callback funkce volaná při stisku klávesy F10."""
    get_app().layout.focus(menu.window)
예제 #37
0
def cursor_at_end():
    app = get_app()
    return app.current_buffer.cursor_position == len(app.current_buffer.text)
예제 #38
0
def text_is_empty():
    app = get_app()
    return not app.current_buffer.text
예제 #39
0
def _do_exit() -> None:
  application_current.get_app().exit()
예제 #40
0
 def hide(self) -> None:
   self._visible = False
   if self.focus_element_on_hide:
     application_current.get_app().layout.focus(self.focus_element_on_hide)
예제 #41
0
 def show(self) -> None:
   self._visible = True
   if self.focus_element_on_show:
     application_current.get_app().layout.focus(self.focus_element_on_show)
예제 #42
0
 def size_received(rows: int, columns: int) -> None:
     """ TelnetProtocolParser 'size_received' callback """
     self.size = Size(rows=rows, columns=columns)
     get_app()._on_resize()
 def suggestion_available():
     app = get_app()
     return (app.current_buffer.suggestion is not None
             and app.current_buffer.document.is_cursor_at_the_end)
예제 #44
0
    def create_content(self, width: int, height: int) -> UIContent:
        all_fragments: StyleAndTextTuples = []

        complete_state = get_app().current_buffer.complete_state
        if complete_state:
            completions = complete_state.completions
            index = complete_state.complete_index  # Can be None!

            # Width of the completions without the left/right arrows in the margins.
            content_width = width - 6

            # Booleans indicating whether we stripped from the left/right
            cut_left = False
            cut_right = False

            # Create Menu content.
            fragments: StyleAndTextTuples = []

            for i, c in enumerate(completions):
                # When there is no more place for the next completion
                if fragment_list_len(fragments) + len(c.display_text) >= content_width:
                    # If the current one was not yet displayed, page to the next sequence.
                    if i <= (index or 0):
                        fragments = []
                        cut_left = True
                    # If the current one is visible, stop here.
                    else:
                        cut_right = True
                        break

                fragments.extend(
                    to_formatted_text(
                        c.display_text,
                        style=(
                            "class:completion-toolbar.completion.current"
                            if i == index
                            else "class:completion-toolbar.completion"
                        ),
                    )
                )
                fragments.append(("", " "))

            # Extend/strip until the content width.
            fragments.append(("", " " * (content_width - fragment_list_len(fragments))))
            fragments = fragments[:content_width]

            # Return fragments
            all_fragments.append(("", " "))
            all_fragments.append(
                ("class:completion-toolbar.arrow", "<" if cut_left else " ")
            )
            all_fragments.append(("", " "))

            all_fragments.extend(fragments)

            all_fragments.append(("", " "))
            all_fragments.append(
                ("class:completion-toolbar.arrow", ">" if cut_right else " ")
            )
            all_fragments.append(("", " "))

        def get_line(i: int) -> StyleAndTextTuples:
            return all_fragments

        return UIContent(get_line=get_line, line_count=1)
    def request_absolute_cursor_position(self) -> None:
        """
        Get current cursor position.

        We do this to calculate the minimum available height that we can
        consume for rendering the prompt. This is the available space below te
        cursor.

        For vt100: Do CPR request. (answer will arrive later.)
        For win32: Do API call. (Answer comes immediately.)
        """
        # Only do this request when the cursor is at the top row. (after a
        # clear or reset). We will rely on that in `report_absolute_cursor_row`.
        assert self._cursor_pos.y == 0

        # In full-screen mode, always use the total height as min-available-height.
        if self.full_screen:
            self._min_available_height = self.output.get_size().rows
            return

        # For Win32, we have an API call to get the number of rows below the
        # cursor.
        try:
            self._min_available_height = self.output.get_rows_below_cursor_position(
            )
            return
        except NotImplementedError:
            pass

        # Use CPR.
        if self.cpr_support == CPR_Support.NOT_SUPPORTED:
            return

        def do_cpr() -> None:
            # Asks for a cursor position report (CPR).
            self._waiting_for_cpr_futures.append(Future())
            self.output.ask_for_cpr()

        if self.cpr_support == CPR_Support.SUPPORTED:
            do_cpr()
            return

        # If we don't know whether CPR is supported, only do a request if
        # none is pending, and test it, using a timer.
        if self.waiting_for_cpr:
            return

        do_cpr()

        async def timer() -> None:
            await sleep(self.CPR_TIMEOUT)

            # Not set in the meantime -> not supported.
            if self.cpr_support == CPR_Support.UNKNOWN:
                self.cpr_support = CPR_Support.NOT_SUPPORTED

                if self.cpr_not_supported_callback:
                    # Make sure to call this callback in the main thread.
                    self.cpr_not_supported_callback()

        get_app().create_background_task(timer())
예제 #46
0
 def app(self):
     return get_app()
예제 #47
0
    def create_content(self, width: int, height: int) -> UIContent:
        """
        Create a UIContent object for this menu.
        """
        complete_state = get_app().current_buffer.complete_state
        if complete_state is None:
            return UIContent()

        column_width = self._get_column_width(complete_state)
        self._render_pos_to_completion = {}

        _T = TypeVar("_T")

        def grouper(n: int,
                    iterable: Iterable[_T],
                    fillvalue: Optional[_T] = None) -> Iterable[List[_T]]:
            "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
            args = [iter(iterable)] * n
            return zip_longest(fillvalue=fillvalue, *args)

        def is_current_completion(completion: Completion) -> bool:
            "Returns True when this completion is the currently selected one."
            return (complete_state is not None
                    and complete_state.complete_index is not None
                    and c == complete_state.current_completion)

        # Space required outside of the regular columns, for displaying the
        # left and right arrow.
        HORIZONTAL_MARGIN_REQUIRED = 3

        # There should be at least one column, but it cannot be wider than
        # the available width.
        column_width = min(width - HORIZONTAL_MARGIN_REQUIRED, column_width)

        # However, when the columns tend to be very wide, because there are
        # some very wide entries, shrink it anyway.
        if column_width > self.suggested_max_column_width:
            # `column_width` can still be bigger that `suggested_max_column_width`,
            # but if there is place for two columns, we divide by two.
            column_width //= column_width // self.suggested_max_column_width

        visible_columns = max(1,
                              (width - self._required_margin) // column_width)

        columns_ = list(grouper(height, complete_state.completions))
        rows_ = list(zip(*columns_))

        # Make sure the current completion is always visible: update scroll offset.
        selected_column = (complete_state.complete_index or 0) // height
        self.scroll = min(
            selected_column,
            max(self.scroll, selected_column - visible_columns + 1))

        render_left_arrow = self.scroll > 0
        render_right_arrow = self.scroll < len(rows_[0]) - visible_columns

        # Write completions to screen.
        fragments_for_line = []

        for row_index, row in enumerate(rows_):
            fragments: StyleAndTextTuples = []
            middle_row = row_index == len(rows_) // 2

            # Draw left arrow if we have hidden completions on the left.
            if render_left_arrow:
                fragments.append(
                    ("class:scrollbar", "<" if middle_row else " "))
            elif render_right_arrow:
                # Reserve one column empty space. (If there is a right
                # arrow right now, there can be a left arrow as well.)
                fragments.append(("", " "))

            # Draw row content.
            for column_index, c in enumerate(
                    row[self.scroll:][:visible_columns]):
                if c is not None:
                    fragments += _get_menu_item_fragments(
                        c,
                        is_current_completion(c),
                        column_width,
                        space_after=False)

                    # Remember render position for mouse click handler.
                    for x in range(column_width):
                        self._render_pos_to_completion[(
                            column_index * column_width + x, row_index)] = c
                else:
                    fragments.append(("class:completion", " " * column_width))

            # Draw trailing padding for this row.
            # (_get_menu_item_fragments only returns padding on the left.)
            if render_left_arrow or render_right_arrow:
                fragments.append(("class:completion", " "))

            # Draw right arrow if we have hidden completions on the right.
            if render_right_arrow:
                fragments.append(
                    ("class:scrollbar", ">" if middle_row else " "))
            elif render_left_arrow:
                fragments.append(("class:completion", " "))

            # Add line.
            fragments_for_line.append(
                to_formatted_text(fragments, style="class:completion-menu"))

        self._rendered_rows = height
        self._rendered_columns = visible_columns
        self._total_columns = len(columns_)
        self._render_left_arrow = render_left_arrow
        self._render_right_arrow = render_right_arrow
        self._render_width = (column_width * visible_columns +
                              render_left_arrow + render_right_arrow + 1)

        def get_line(i: int) -> StyleAndTextTuples:
            return fragments_for_line[i]

        return UIContent(get_line=get_line, line_count=len(rows_))
예제 #48
0
def auto_match():
    return get_app().session.auto_match
예제 #49
0
 def is_searching() -> bool:
     return self.control in get_app().layout.search_links
예제 #50
0
    def create_content(self,
                       width: int,
                       height: int,
                       preview_search: bool = False) -> UIContent:
        """
        Create a UIContent.
        """
        buffer = self.buffer

        # Get the document to be shown. If we are currently searching (the
        # search buffer has focus, and the preview_search filter is enabled),
        # then use the search document, which has possibly a different
        # text/cursor position.)
        search_control = self.search_buffer_control
        preview_now = preview_search or bool(
            # Only if this feature is enabled.
            self.preview_search() and

            # And something was typed in the associated search field.
            search_control and search_control.buffer.text and

            # And we are searching in this control. (Many controls can point to
            # the same search field, like in Pyvim.)
            get_app().layout.search_target_buffer_control == self)

        if preview_now and search_control is not None:
            ss = self.search_state

            document = buffer.document_for_search(
                SearchState(text=search_control.buffer.text,
                            direction=ss.direction,
                            ignore_case=ss.ignore_case))
        else:
            document = buffer.document

        get_processed_line = self._create_get_processed_line_func(
            document, width, height)
        self._last_get_processed_line = get_processed_line

        def translate_rowcol(row: int, col: int) -> Point:
            " Return the content column for this coordinate. "
            return Point(x=get_processed_line(row).source_to_display(col),
                         y=row)

        def get_line(i: int) -> StyleAndTextTuples:
            " Return the fragments for a given line number. "
            fragments = get_processed_line(i).fragments

            # Add a space at the end, because that is a possible cursor
            # position. (When inserting after the input.) We should do this on
            # all the lines, not just the line containing the cursor. (Because
            # otherwise, line wrapping/scrolling could change when moving the
            # cursor around.)
            fragments = fragments + [('', ' ')]
            return fragments

        content = UIContent(get_line=get_line,
                            line_count=document.line_count,
                            cursor_position=translate_rowcol(
                                document.cursor_position_row,
                                document.cursor_position_col))

        # If there is an auto completion going on, use that start point for a
        # pop-up menu position. (But only when this buffer has the focus --
        # there is only one place for a menu, determined by the focused buffer.)
        if get_app().layout.current_control == self:
            menu_position = self.menu_position(
            ) if self.menu_position else None
            if menu_position is not None:
                assert isinstance(menu_position, int)
                menu_row, menu_col = buffer.document.translate_index_to_position(
                    menu_position)
                content.menu_position = translate_rowcol(menu_row, menu_col)
            elif buffer.complete_state:
                # Position for completion menu.
                # Note: We use 'min', because the original cursor position could be
                #       behind the input string when the actual completion is for
                #       some reason shorter than the text we had before. (A completion
                #       can change and shorten the input.)
                menu_row, menu_col = buffer.document.translate_index_to_position(
                    min(
                        buffer.cursor_position, buffer.complete_state.
                        original_document.cursor_position))
                content.menu_position = translate_rowcol(menu_row, menu_col)
            else:
                content.menu_position = None

        return content
예제 #51
0
def has_complete_index():
    app = get_app()
    cs = app.current_buffer.complete_state
    return cs and cs.complete_index is not None
예제 #52
0
    def mouse_handler(self, mouse_event: MouseEvent) -> 'NotImplementedOrNone':
        """
        Mouse handler for this control.
        """
        buffer = self.buffer
        position = mouse_event.position

        # Focus buffer when clicked.
        if get_app().layout.current_control == self:
            if self._last_get_processed_line:
                processed_line = self._last_get_processed_line(position.y)

                # Translate coordinates back to the cursor position of the
                # original input.
                xpos = processed_line.display_to_source(position.x)
                index = buffer.document.translate_row_col_to_index(
                    position.y, xpos)

                # Set the cursor position.
                if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
                    buffer.exit_selection()
                    buffer.cursor_position = index

                elif mouse_event.event_type == MouseEventType.MOUSE_UP:
                    # When the cursor was moved to another place, select the text.
                    # (The >1 is actually a small but acceptable workaround for
                    # selecting text in Vi navigation mode. In navigation mode,
                    # the cursor can never be after the text, so the cursor
                    # will be repositioned automatically.)
                    if abs(buffer.cursor_position - index) > 1:
                        buffer.start_selection(
                            selection_type=SelectionType.CHARACTERS)
                        buffer.cursor_position = index

                    # Select word around cursor on double click.
                    # Two MOUSE_UP events in a short timespan are considered a double click.
                    double_click = self._last_click_timestamp and time.time(
                    ) - self._last_click_timestamp < .3
                    self._last_click_timestamp = time.time()

                    if double_click:
                        start, end = buffer.document.find_boundaries_of_current_word(
                        )
                        buffer.cursor_position += start
                        buffer.start_selection(
                            selection_type=SelectionType.CHARACTERS)
                        buffer.cursor_position += end - start
                else:
                    # Don't handle scroll events here.
                    return NotImplemented

        # Not focused, but focusing on click events.
        else:
            if self.focus_on_click(
            ) and mouse_event.event_type == MouseEventType.MOUSE_UP:
                # Focus happens on mouseup. (If we did this on mousedown, the
                # up event will be received at the point where this widget is
                # focused and be handled anyway.)
                get_app().layout.current_control = self
            else:
                return NotImplemented

        return None
예제 #53
0
def do_exit():
    get_app().exit()
예제 #54
0
def do_copy():
    data = text_field.buffer.copy_selection()
    get_app().clipboard.set_data(data)
예제 #55
0
 def _ctrl_c(event):
     get_app().exit(result=False)
예제 #56
0
파일: ctserial.py 프로젝트: wguest/ctserial
def get_statusbar_text():
    sep = ' - '
    mode = 'mode:' + get_app().mode
    device = 'connected:' + get_app().connection.port
    output_format = 'output:' + get_app().output_format
    return sep.join([mode, device, output_format])
예제 #57
0
 def _enter(event):
     get_app().exit(result=True)
예제 #58
0
    def get_height_for_line(self,
                            lineno: int,
                            width: int,
                            get_line_prefix: Optional[GetLinePrefixCallable],
                            slice_stop: Optional[int] = None) -> int:
        """
        Return the height that a given line would need if it is rendered in a
        space with the given width (using line wrapping).

        :param get_line_prefix: None or a `Window.get_line_prefix` callable
            that returns the prefix to be inserted before this line.
        :param slice_stop: Wrap only "line[:slice_stop]" and return that
            partial result. This is needed for scrolling the window correctly
            when line wrapping.
        :returns: The computed height.
        """
        # Instead of using `get_line_prefix` as key, we use render_counter
        # instead. This is more reliable, because this function could still be
        # the same, while the content would change over time.
        key = get_app().render_counter, lineno, width, slice_stop

        try:
            return self._line_heights_cache[key]
        except KeyError:
            if width == 0:
                height = 10**8
            else:
                # Calculate line width first.
                line = fragment_list_to_text(
                    self.get_line(lineno))[:slice_stop]
                text_width = get_cwidth(line)

                if get_line_prefix:
                    # Add prefix width.
                    text_width += fragment_list_width(
                        to_formatted_text(get_line_prefix(lineno, 0)))

                    # Slower path: compute path when there's a line prefix.
                    height = 1

                    # Keep wrapping as long as the line doesn't fit.
                    # Keep adding new prefixes for every wrapped line.
                    while text_width > width:
                        height += 1
                        text_width -= width

                        fragments2 = to_formatted_text(
                            get_line_prefix(lineno, height - 1))
                        prefix_width = get_cwidth(
                            fragment_list_to_text(fragments2))

                        if prefix_width >= width:  # Prefix doesn't fit.
                            height = 10**8
                            break

                        text_width += prefix_width
                else:
                    # Fast path: compute height when there's no line prefix.
                    try:
                        quotient, remainder = divmod(text_width, width)
                    except ZeroDivisionError:
                        height = 10**8
                    else:
                        if remainder:
                            quotient += 1  # Like math.ceil.
                        height = max(1, quotient)

            # Cache and return
            self._line_heights_cache[key] = height
            return height
예제 #59
0
def on_exit_selected(event=None):
    """Callback funkce volaná při stisku klávesy Esc."""
    get_app().exit()
예제 #60
0
def auto_indentation():
    return get_app().session.auto_indentation