Debian Codegraph @

src/fenrirscreenreader/commands/onScreenUpdate/66000-prompt_detector.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 # Fenrir TTY screen reader
5 # By Chrys, Storm Dragon, and contributors.
6
7 from fenrirscreenreader.core import debug
8 from fenrirscreenreader.core.i18n import _
9
10
11 class command:
12 def __init__(self):
13 pass
14
15 def initialize(self, environment):
16 self.env = environment
17
18 def shutdown(self):
19 pass
20
21 def get_description(self):
22 return "Detects shell prompts for silence until prompt feature"
23
24 def run(self):
25 # Only run if silence until prompt is active
26 try:
27 if (
28 "silenceUntilPrompt" in self.env["commandBuffer"]
29 and self.env["commandBuffer"]["silenceUntilPrompt"]
30 ):
31 # Check the current line for prompt patterns
32 if self.env["screen"]["new_content_text"]:
33 lines = self.env["screen"]["new_content_text"].split("\n")
34 if lines and self.env["screen"]["new_cursor"]["y"] < len(
35 lines
36 ):
37 current_line = lines[
38 self.env["screen"]["new_cursor"]["y"]
39 ]
40 self.check_for_prompt(current_line)
41 except Exception as e:
42 # Silently ignore errors to avoid disrupting normal operation
43 self.env["runtime"]["DebugManager"].write_debug_out(
44 "prompt_detector run: Error in prompt detection: " + str(e),
45 debug.DebugLevel.ERROR,
46 )
47
48 def check_for_prompt(self, text):
49 """Check if the current line contains a shell prompt pattern"""
50 import re
51
52 # Debug: Print what we're checking
53 self.env["runtime"]["DebugManager"].write_debug_out(
54 "Prompt detector checking: '" + text + "'", debug.DebugLevel.INFO
55 )
56
57 # First check for exact matches from settings (with backward
58 # compatibility)
59 try:
60 exact_matches = self.env["runtime"]["SettingsManager"].get_setting(
61 "prompt", "exact_matches"
62 )
63 if exact_matches:
64 exact_list = [
65 match.strip()
66 for match in exact_matches.split(",")
67 if match.strip()
68 ]
69 for exactMatch in exact_list:
70 if text.strip() == exactMatch:
71 self.env["runtime"]["DebugManager"].write_debug_out(
72 "found exact prompt match: " + exactMatch,
73 debug.DebugLevel.INFO,
74 )
75 self._restore_speech()
76 return True
77 except Exception as e:
78 # Prompt section doesn't exist in settings, skip custom exact
79 # matches
80 pass
81
82 # Get custom patterns from settings (with backward compatibility)
83 prompt_patterns = []
84 try:
85 custom_patterns = self.env["runtime"][
86 "SettingsManager"
87 ].get_setting("prompt", "custom_patterns")
88 # Add custom patterns from settings if they exist
89 if custom_patterns:
90 custom_list = [
91 pattern.strip()
92 for pattern in custom_patterns.split(",")
93 if pattern.strip()
94 ]
95 prompt_patterns.extend(custom_list)
96 except Exception as e:
97 # Prompt section doesn't exist in settings, skip custom patterns
98 pass
99
100 # Add default shell prompt patterns
101 prompt_patterns.extend(
102 [
103 r"^\s*\$\s*$", # Just $ (with whitespace)
104 r"^\s*#\s*$", # Just # (with whitespace)
105 r"^\s*>\s*$", # Just > (with whitespace)
106 r".*@.*[\\\$#>]\s*$",
107 # Contains @ and ends with prompt char (user@host style)
108 r"^\[.*\]\s*[\\\$#>]\s*$", # [anything]$ style prompts
109 # Simple shell names like bash-5.1$
110 r"^[a-zA-Z0-9._-]+[\\\$#>]\s*$",
111 # Interactive prompt patterns
112 # Package manager confirmation prompts
113 r".*\?\s*\[[YyNn]/[YyNn]\]\s*$", # ? [Y/n] or ? [y/N] style
114 r".*\?\s*\[[Yy]es/[Nn]o\]\s*$", # ? [Yes/No] style
115 r".*\?\s*\([YyNn]/[YyNn]\)\s*$", # ? (Y/n) or ? (y/N) style
116 r".*\?\s*\([Yy]es/[Nn]o\)\s*$", # ? (Yes/No) style
117 r".*continue\?\s*\[[YyNn]/[YyNn]\].*$", # "continue? [Y/n]" style
118 r".*ok\s*\[[YyNn]/[YyNn]\].*$", # "Is this ok [y/N]:" style
119 # pacman ":: Proceed? [Y/n]" style
120 r"^::.*\?\s*\[[YyNn]/[YyNn]\].*$",
121 # Authentication prompts
122 # [sudo] password for user:
123 r"^\[[Ss]udo\]\s*[Pp]assword\s*for\s+.*:\s*$",
124 r"^[Pp]assword\s*:\s*$", # Password:
125 r".*[Pp]assword\s*:\s*$", # general password prompts
126 r".*'s\s*[Pp]assword\s*:\s*$", # user's password:
127 r"^[Ee]nter\s+[Pp]assphrase.*:\s*$", # Enter passphrase:
128 # Please enter passphrase:
129 r"^[Pp]lease\s+enter\s+[Pp]assphrase.*:\s*$",
130 # General confirmation and continuation prompts
131 # Press any key to continue
132 r"^[Pp]ress\s+any\s+key\s+to\s+continue.*$",
133 r"^[Aa]re\s+you\s+sure\?\s*.*$", # Are you sure?
134 r"^[Pp]lease\s+confirm.*$", # Please confirm
135 r".*confirm.*\([YyNn]/[YyNn]\).*$", # confirm (y/n)
136 r".*\([Yy]/[Nn]\)\s*$", # ends with (Y/n) or (y/N)
137 ]
138 )
139
140 for pattern in prompt_patterns:
141 try:
142 if re.search(pattern, text.strip()):
143 self.env["runtime"]["DebugManager"].write_debug_out(
144 "found prompt pattern: " + pattern,
145 debug.DebugLevel.INFO,
146 )
147 self._restore_speech()
148 return True
149 except re.error as e:
150 # Invalid regex pattern, skip it and log the error
151 self.env["runtime"]["DebugManager"].write_debug_out(
152 "Invalid prompt pattern: " + pattern + " Error: " + str(e),
153 debug.DebugLevel.ERROR,
154 )
155 continue
156
157 return False
158
159 def _restore_speech(self):
160 """Helper method to restore speech when prompt is detected"""
161 # If speech is already enabled, just clear flags to avoid unnecessary
162 # interrupts on prompt return
163 if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
164 "speech", "enabled"
165 ):
166 self.env["commandBuffer"]["silenceUntilPrompt"] = False
167 if "enableSpeechOnKeypress" in self.env["commandBuffer"]:
168 self.env["commandBuffer"]["enableSpeechOnKeypress"] = False
169 return
170
171 # Disable silence mode
172 self.env["commandBuffer"]["silenceUntilPrompt"] = False
173 # Also disable the keypress-based speech restoration since we're
174 # enabling it now
175 if "enableSpeechOnKeypress" in self.env["commandBuffer"]:
176 self.env["commandBuffer"]["enableSpeechOnKeypress"] = False
177 # Re-enable speech
178 self.env["runtime"]["SettingsManager"].set_setting(
179 "speech", "enabled", "True"
180 )
181 self.env["runtime"]["OutputManager"].present_text(
182 _("Speech restored"), sound_icon="SpeechOn", interrupt=True
183 )
184
185 def set_callback(self, callback):
186 pass