The stdin object user code will reference In user code, sys.stdin.read() asks the user for interactive input, so this class returns control to the UI to get that input.
| 97 | |
| 98 | |
| 99 | class FakeStdin: |
| 100 | """The stdin object user code will reference |
| 101 | |
| 102 | In user code, sys.stdin.read() asks the user for interactive input, |
| 103 | so this class returns control to the UI to get that input.""" |
| 104 | |
| 105 | def __init__( |
| 106 | self, |
| 107 | coderunner: CodeRunner, |
| 108 | repl: "BaseRepl", |
| 109 | configured_edit_keys: AbstractEdits | None = None, |
| 110 | ): |
| 111 | self.coderunner = coderunner |
| 112 | self.repl = repl |
| 113 | self.has_focus = False # whether FakeStdin receives keypress events |
| 114 | self.current_line = "" |
| 115 | self.cursor_offset = 0 |
| 116 | self.old_num_lines = 0 |
| 117 | self.readline_results: list[str] = [] |
| 118 | if configured_edit_keys is not None: |
| 119 | self.rl_char_sequences = configured_edit_keys |
| 120 | else: |
| 121 | self.rl_char_sequences = edit_keys |
| 122 | |
| 123 | def process_event(self, e: events.Event | str) -> None: |
| 124 | assert self.has_focus |
| 125 | |
| 126 | logger.debug("fake input processing event %r", e) |
| 127 | if isinstance(e, events.Event): |
| 128 | if isinstance(e, events.PasteEvent): |
| 129 | for ee in e.events: |
| 130 | if ee not in self.rl_char_sequences: |
| 131 | self.add_input_character(ee) |
| 132 | elif isinstance(e, events.SigIntEvent): |
| 133 | self.coderunner.sigint_happened_in_main_context = True |
| 134 | self.has_focus = False |
| 135 | self.current_line = "" |
| 136 | self.cursor_offset = 0 |
| 137 | self.repl.run_code_and_maybe_finish() |
| 138 | elif e in self.rl_char_sequences: |
| 139 | self.cursor_offset, self.current_line = self.rl_char_sequences[e]( |
| 140 | self.cursor_offset, self.current_line |
| 141 | ) |
| 142 | elif e == "<Ctrl-d>": |
| 143 | if not len(self.current_line): |
| 144 | self.repl.send_to_stdin("\n") |
| 145 | self.has_focus = False |
| 146 | self.current_line = "" |
| 147 | self.cursor_offset = 0 |
| 148 | self.repl.run_code_and_maybe_finish(for_code="") |
| 149 | elif e in ("\n", "\r", "<Ctrl-j>", "<Ctrl-m>"): |
| 150 | line = f"{self.current_line}\n" |
| 151 | self.repl.send_to_stdin(line) |
| 152 | self.has_focus = False |
| 153 | self.current_line = "" |
| 154 | self.cursor_offset = 0 |
| 155 | self.repl.run_code_and_maybe_finish(for_code=line) |
| 156 | elif e != "<ESC>": # add normal character |