Debian Codegraph @

src/fenrirscreenreader/core/diffReviewManager.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 import os
8 import re
9
10 from fenrirscreenreader.core import debug
11 from fenrirscreenreader.core.i18n import _
12
13
14 class DiffReviewManager:
15 def __init__(self):
16 self.env = None
17 self.active = False
18 self.loaded_path = ""
19 self.lines = []
20 self.line_meta = []
21 self.file_sections = []
22 self.hunk_sections = []
23 self.file_starts = []
24 self.hunk_starts = []
25 self.added_lines = []
26 self.removed_lines = []
27 self.current_line = -1
28 self.bindings_backup = None
29 self.raw_bindings_backup = None
30 self.total_added = 0
31 self.total_removed = 0
32 self.current_char = 0
33
34 def initialize(self, environment):
35 self.env = environment
36
37 def shutdown(self):
38 if self.active:
39 self._restore_bindings()
40 self.active = False
41
42 def is_active(self):
43 return self.active
44
45 def has_loaded_diff(self):
46 return len(self.lines) > 0
47
48 def get_loaded_path(self):
49 return self.loaded_path
50
51 def toggle_mode(self):
52 if self.active:
53 self.disable_mode()
54 self.present_mode_message(
55 _("Diff review mode disabled."),
56 )
57 return False
58
59 clipboard_path = self._get_clipboard_path_or_none()
60 if (
61 clipboard_path
62 and (
63 (not self.has_loaded_diff())
64 or (self.loaded_path != clipboard_path)
65 )
66 ):
67 if not self.load_file(clipboard_path):
68 return False
69 elif not self.has_loaded_diff():
70 self.present_error(
71 _("Clipboard does not contain full path to diff file.")
72 )
73 return False
74
75 enabled = self.enable_mode()
76 if enabled:
77 self.present_mode_message(
78 _("Diff review mode enabled."),
79 )
80 return enabled
81
82 def enable_mode(self):
83 if self.active:
84 return True
85 if not self.has_loaded_diff():
86 return False
87 self._install_diff_bindings()
88 self.active = True
89 return True
90
91 def disable_mode(self):
92 if not self.active:
93 return
94 self._restore_bindings()
95 self.active = False
96
97 def load_from_clipboard(self):
98 clipboard_path = self._get_clipboard_path_or_none()
99 if not clipboard_path:
100 self.present_error(
101 _("Clipboard does not contain full path to diff file.")
102 )
103 return False
104
105 return self.load_file(clipboard_path)
106
107 def reload_file(self):
108 if not self.loaded_path:
109 self.present_error(_("No diff file loaded."))
110 return False
111 return self.load_file(self.loaded_path)
112
113 def load_file(self, file_path):
114 normalized_path = os.path.abspath(os.path.expanduser(file_path))
115 if not os.path.exists(normalized_path):
116 self.present_error(
117 _("Diff file not found: ") + normalized_path
118 )
119 return False
120 if os.path.isdir(normalized_path):
121 self.present_error(
122 _("Diff path is a directory: ") + normalized_path
123 )
124 return False
125 if not os.access(normalized_path, os.R_OK):
126 self.present_error(
127 _("Cannot read diff file: ") + normalized_path
128 )
129 return False
130
131 try:
132 with open(normalized_path, "r", encoding="utf-8", errors="replace") as diff_file:
133 file_lines = diff_file.read().splitlines()
134 except Exception as load_error:
135 self._write_debug(
136 "DiffReviewManager load_file: " + str(load_error),
137 debug.DebugLevel.ERROR,
138 )
139 self.present_error(
140 _("Failed to load diff file: ") + normalized_path
141 )
142 return False
143
144 self.present_mode_message(
145 _("Loading ") + normalized_path + ".",
146 )
147 self._parse_lines(file_lines, normalized_path)
148 self.present_mode_message(
149 _("Diff loaded. ")
150 + str(len(self.file_sections))
151 + _(" files changed. ")
152 + str(self.total_added)
153 + _(" additions. ")
154 + str(self.total_removed)
155 + _(" removals."),
156 )
157 return True
158
159 def _parse_lines(self, file_lines, loaded_path):
160 self.lines = file_lines
161 self.loaded_path = loaded_path
162 self.line_meta = []
163 self.file_sections = []
164 self.hunk_sections = []
165 self.file_starts = []
166 self.hunk_starts = []
167 self.added_lines = []
168 self.removed_lines = []
169 self.current_line = -1
170 self.total_added = 0
171 self.total_removed = 0
172 self.current_char = 0
173
174 has_git_header = any(
175 line.startswith("diff --git ") for line in self.lines
176 )
177
178 current_file_index = -1
179 current_hunk_index = -1
180 for line_index, line in enumerate(self.lines):
181 role = self._classify_line(line)
182
183 if self._starts_new_file_section(
184 line=line,
185 has_git_header=has_git_header,
186 ):
187 current_file_index = self._add_file_section(line_index)
188 current_hunk_index = -1
189
190 if (
191 current_file_index == -1
192 and role
193 in {
194 "hunk_header",
195 "added_line",
196 "removed_line",
197 "context_line",
198 "note_line",
199 }
200 ):
201 current_file_index = self._add_file_section(line_index)
202
203 if role == "hunk_header":
204 if current_file_index == -1:
205 current_file_index = self._add_file_section(line_index)
206 current_hunk_index = self._add_hunk_section(
207 line_index=line_index,
208 file_index=current_file_index,
209 )
210
211 if role in {"added_line", "removed_line"} and current_hunk_index == -1:
212 if current_file_index == -1:
213 current_file_index = self._add_file_section(line_index)
214 current_hunk_index = self._add_hunk_section(
215 line_index=line_index,
216 file_index=current_file_index,
217 )
218
219 if role == "added_line":
220 self.added_lines.append(line_index)
221 self.total_added += 1
222 if current_file_index != -1:
223 self.file_sections[current_file_index]["added_count"] += 1
224 if current_hunk_index != -1:
225 self.hunk_sections[current_hunk_index]["added_count"] += 1
226 elif role == "removed_line":
227 self.removed_lines.append(line_index)
228 self.total_removed += 1
229 if current_file_index != -1:
230 self.file_sections[current_file_index]["removed_count"] += 1
231 if current_hunk_index != -1:
232 self.hunk_sections[current_hunk_index]["removed_count"] += 1
233
234 self.line_meta.append(
235 {
236 "role": role,
237 "file_index": current_file_index,
238 "hunk_index": current_hunk_index,
239 }
240 )
241
242 for file_index, file_section in enumerate(self.file_sections):
243 file_hunks = file_section["hunk_indices"]
244 for local_position, hunk_index in enumerate(file_hunks, start=1):
245 self.hunk_sections[hunk_index]["position_in_file"] = local_position
246 self.hunk_sections[hunk_index]["hunks_in_file"] = len(file_hunks)
247
248 def _classify_line(self, line):
249 if line.startswith("\\ No newline at end of file"):
250 return "note_line"
251 if self._is_file_header(line):
252 return "file_header"
253 if line.startswith("@@"):
254 return "hunk_header"
255 if line.startswith("+") and not line.startswith("+++ "):
256 return "added_line"
257 if line.startswith("-") and not line.startswith("--- "):
258 return "removed_line"
259 return "context_line"
260
261 def _get_clipboard_path_or_none(self):
262 if self.env["runtime"]["MemoryManager"].is_index_list_empty(
263 "clipboardHistory"
264 ):
265 return None
266
267 clipboard_value = self.env["runtime"]["MemoryManager"].get_index_list_element(
268 "clipboardHistory"
269 )
270 if not isinstance(clipboard_value, str):
271 return None
272
273 clipboard_path = clipboard_value.strip().strip("\"'")
274 clipboard_path = os.path.expanduser(clipboard_path)
275 if not os.path.isabs(clipboard_path):
276 return None
277 return os.path.abspath(clipboard_path)
278
279 def _is_file_header(self, line):
280 file_header_prefixes = (
281 "diff --git ",
282 "--- ",
283 "+++ ",
284 "index ",
285 "old mode ",
286 "new mode ",
287 "deleted file mode ",
288 "new file mode ",
289 "rename from ",
290 "rename to ",
291 "similarity index ",
292 "dissimilarity index ",
293 "Binary files ",
294 )
295 return line.startswith(file_header_prefixes)
296
297 def _starts_new_file_section(self, line, has_git_header):
298 if has_git_header:
299 return line.startswith("diff --git ")
300 return line.startswith("--- ")
301
302 def _add_file_section(self, line_index):
303 file_section = {
304 "start_line": line_index,
305 "added_count": 0,
306 "removed_count": 0,
307 "hunk_indices": [],
308 }
309 self.file_sections.append(file_section)
310 self.file_starts.append(line_index)
311 return len(self.file_sections) - 1
312
313 def _add_hunk_section(self, line_index, file_index):
314 hunk_section = {
315 "start_line": line_index,
316 "file_index": file_index,
317 "added_count": 0,
318 "removed_count": 0,
319 "position_in_file": 0,
320 "hunks_in_file": 0,
321 }
322 self.hunk_sections.append(hunk_section)
323 self.hunk_starts.append(line_index)
324 hunk_index = len(self.hunk_sections) - 1
325 if file_index != -1:
326 self.file_sections[file_index]["hunk_indices"].append(hunk_index)
327 return hunk_index
328
329 def next_file_section(self):
330 self._jump_to_anchor(
331 anchors=self.file_starts,
332 previous=False,
333 empty_message=_("No file sections in loaded diff."),
334 edge_message=_("No further file sections."),
335 announce_role="file",
336 )
337
338 def prev_file_section(self):
339 self._jump_to_anchor(
340 anchors=self.file_starts,
341 previous=True,
342 empty_message=_("No file sections in loaded diff."),
343 edge_message=_("No previous file sections."),
344 announce_role="file",
345 )
346
347 def next_hunk(self):
348 self._jump_to_anchor(
349 anchors=self.hunk_starts,
350 previous=False,
351 empty_message=_("No hunks in loaded diff."),
352 edge_message=_("No further hunks."),
353 announce_role="hunk",
354 )
355
356 def prev_hunk(self):
357 self._jump_to_anchor(
358 anchors=self.hunk_starts,
359 previous=True,
360 empty_message=_("No hunks in loaded diff."),
361 edge_message=_("No previous hunks."),
362 announce_role="hunk",
363 )
364
365 def next_added(self):
366 self._jump_to_anchor(
367 anchors=self.added_lines,
368 previous=False,
369 empty_message=_("No added lines in loaded diff."),
370 edge_message=_("No further added lines."),
371 announce_role="added",
372 )
373
374 def prev_added(self):
375 self._jump_to_anchor(
376 anchors=self.added_lines,
377 previous=True,
378 empty_message=_("No added lines in loaded diff."),
379 edge_message=_("No previous added lines."),
380 announce_role="added",
381 )
382
383 def next_removed(self):
384 self._jump_to_anchor(
385 anchors=self.removed_lines,
386 previous=False,
387 empty_message=_("No removed lines in loaded diff."),
388 edge_message=_("No further removed lines."),
389 announce_role="removed",
390 )
391
392 def prev_removed(self):
393 self._jump_to_anchor(
394 anchors=self.removed_lines,
395 previous=True,
396 empty_message=_("No removed lines in loaded diff."),
397 edge_message=_("No previous removed lines."),
398 announce_role="removed",
399 )
400
401 def present_summary(self):
402 if not self.has_loaded_diff():
403 self.present_mode_message(_("No diff file loaded."))
404 return
405
406 summary = (
407 _("Diff summary. Files changed: ")
408 + str(len(self.file_sections))
409 + _(". Additions: ")
410 + str(self.total_added)
411 + _(". Removals: ")
412 + str(self.total_removed)
413 + "."
414 )
415
416 if self.current_line >= 0 and self.current_line < len(self.line_meta):
417 location = self._build_location_text(self.current_line)
418 if location:
419 summary += " " + location
420
421 self.present_mode_message(summary)
422
423 def present_key_help(self):
424 help_text = _(
425 "Diff keys: h next hunk, shift h previous hunk, a next addition, "
426 "shift a previous addition, d next removal, shift d previous removal, "
427 "f next file section, shift f previous file section, up previous line, "
428 "down next line, left previous character, right next character, "
429 "control left previous word, control right next word, s summary, "
430 "escape exit diff mode."
431 )
432 self.present_mode_message(help_text)
433
434 def next_line(self):
435 if not self.has_loaded_diff():
436 self.present_mode_message(_("No diff file loaded."))
437 return
438 if self.current_line < 0:
439 self.current_line = 0
440 self.current_char = 0
441 self._announce_current_line()
442 return
443 if self.current_line >= len(self.lines) - 1:
444 self.present_mode_message(_("End of diff."))
445 return
446 self.current_line += 1
447 self.current_char = 0
448 self._announce_current_line()
449
450 def prev_line(self):
451 if not self.has_loaded_diff():
452 self.present_mode_message(_("No diff file loaded."))
453 return
454 if self.current_line < 0:
455 self.current_line = 0
456 self.current_char = 0
457 self._announce_current_line()
458 return
459 if self.current_line <= 0:
460 self.present_mode_message(_("Start of diff."))
461 return
462 self.current_line -= 1
463 self.current_char = 0
464 self._announce_current_line()
465
466 def next_char(self):
467 if not self._ensure_current_line():
468 return
469 line_text = self.lines[self.current_line]
470 if len(line_text) == 0:
471 self.present_mode_message(_("blank"))
472 return
473 if self.current_char >= len(line_text) - 1:
474 self.present_mode_message(_("End of line."))
475 return
476 self.current_char += 1
477 self._announce_current_char()
478
479 def prev_char(self):
480 if not self._ensure_current_line():
481 return
482 line_text = self.lines[self.current_line]
483 if len(line_text) == 0:
484 self.present_mode_message(_("blank"))
485 return
486 if self.current_char <= 0:
487 self.present_mode_message(_("Start of line."))
488 return
489 self.current_char -= 1
490 self._announce_current_char()
491
492 def next_word(self):
493 if not self._ensure_current_line():
494 return
495 line_text = self.lines[self.current_line]
496 word_spans = self._get_word_spans(line_text)
497 if len(word_spans) == 0:
498 self.present_mode_message(_("No words on this line."))
499 return
500
501 next_word_start = None
502 for start, end in word_spans:
503 if start > self.current_char:
504 next_word_start = start
505 break
506 if start <= self.current_char < end:
507 continue
508
509 if next_word_start is None:
510 self.present_mode_message(_("No next word on this line."))
511 return
512
513 self.current_char = next_word_start
514 self._announce_word_at_current_char()
515
516 def prev_word(self):
517 if not self._ensure_current_line():
518 return
519 line_text = self.lines[self.current_line]
520 word_spans = self._get_word_spans(line_text)
521 if len(word_spans) == 0:
522 self.present_mode_message(_("No words on this line."))
523 return
524
525 prev_word_start = None
526 for start, end in word_spans:
527 if end - 1 < self.current_char:
528 prev_word_start = start
529 elif start <= self.current_char < end:
530 break
531 else:
532 break
533
534 if prev_word_start is None:
535 self.present_mode_message(_("No previous word on this line."))
536 return
537
538 self.current_char = prev_word_start
539 self._announce_word_at_current_char()
540
541 def _jump_to_anchor(
542 self,
543 anchors,
544 previous,
545 empty_message,
546 edge_message,
547 announce_role,
548 ):
549 if not self.has_loaded_diff():
550 self.present_mode_message(_("No diff file loaded."))
551 return
552
553 if len(anchors) == 0:
554 self.present_mode_message(empty_message)
555 return
556
557 new_line = self._find_next_anchor(anchors, previous)
558 if new_line is None:
559 self.present_mode_message(edge_message)
560 return
561
562 self.current_line = new_line
563 self.current_char = 0
564 self._announce_line(announce_role, new_line)
565
566 def _find_next_anchor(self, anchors, previous):
567 if self.current_line < 0:
568 if previous:
569 return anchors[-1]
570 return anchors[0]
571
572 if previous:
573 for anchor_line in reversed(anchors):
574 if anchor_line < self.current_line:
575 return anchor_line
576 return None
577
578 for anchor_line in anchors:
579 if anchor_line > self.current_line:
580 return anchor_line
581 return None
582
583 def _announce_line(self, announce_role, line_index):
584 line_text = self.lines[line_index] if line_index < len(self.lines) else ""
585 line_meta = self.line_meta[line_index]
586 role = line_meta["role"]
587 verbosity = self._get_diff_verbosity()
588
589 if announce_role == "file":
590 self._announce_file_section(line_index, line_meta)
591 return
592 if announce_role == "hunk":
593 self._announce_hunk_section(line_index, line_meta, line_text)
594 return
595
596 if role == "added_line":
597 base_message = _("Added line.")
598 elif role == "removed_line":
599 base_message = _("Removed line.")
600 else:
601 base_message = _("Diff line.")
602
603 message = base_message + " " + self._build_location_text(line_index)
604 if verbosity == "verbose":
605 content = self._line_content_for_speech(line_text, role)
606 message = message + " " + content
607 self.present_mode_message(message)
608
609 def _announce_current_line(self):
610 if self.current_line < 0 or self.current_line >= len(self.lines):
611 self.present_mode_message(_("No diff file loaded."))
612 return
613 line_text = self.lines[self.current_line]
614 role = self.line_meta[self.current_line]["role"]
615
616 if role == "context_line":
617 formatted_classic_diff = self._format_classic_diff_command(line_text)
618 if formatted_classic_diff:
619 self.present_mode_message(formatted_classic_diff)
620 return
621
622 role_prefix = {
623 "added_line": _("Added"),
624 "removed_line": _("Removed"),
625 "hunk_header": _("Hunk header"),
626 "file_header": _("File header"),
627 "note_line": _("Note"),
628 "context_line": "",
629 }.get(role, _("Line"))
630 if line_text.strip() == "":
631 if role_prefix:
632 self.present_mode_message(role_prefix + ": " + _("blank"))
633 else:
634 self.present_mode_message(_("blank"))
635 return
636 if role_prefix:
637 line_text = self._normalize_diff_line_content(line_text, role)
638 if line_text.strip() == "":
639 self.present_mode_message(role_prefix + ": " + _("blank"))
640 return
641 if role in {"added_line", "removed_line"} and line_text in {
642 _("added"),
643 _("removed"),
644 }:
645 self.present_mode_message(line_text)
646 return
647 self.present_mode_message(role_prefix + ": " + line_text)
648 else:
649 self.present_mode_message(line_text)
650
651 def _format_classic_diff_command(self, line_text):
652 match = re.match(r"^(\d+)(?:,(\d+))?([acd])(\d+)(?:,(\d+))?$", line_text.strip())
653 if not match:
654 return None
655
656 old_start = int(match.group(1))
657 old_end = int(match.group(2) or match.group(1))
658 op = match.group(3)
659 new_start = int(match.group(4))
660 new_end = int(match.group(5) or match.group(4))
661
662 if op == "c":
663 return self._format_line_span(old_start, old_end) + " " + _("changed")
664 if op == "d":
665 return self._format_line_span(old_start, old_end) + " " + _("deleted")
666 if op == "a":
667 return self._format_line_span(new_start, new_end) + " " + _("added")
668 return None
669
670 def _format_line_span(self, start_line, end_line):
671 if start_line == end_line:
672 return _("line ") + str(start_line)
673 return (
674 _("lines ")
675 + str(start_line)
676 + _(" through ")
677 + str(end_line)
678 )
679
680 def _announce_current_char(self):
681 if self.current_line < 0 or self.current_line >= len(self.lines):
682 self.present_mode_message(_("No diff file loaded."))
683 return
684 line_text = self.lines[self.current_line]
685 if len(line_text) == 0:
686 self.present_mode_message(_("blank"))
687 return
688 if self.current_char < 0:
689 self.current_char = 0
690 if self.current_char >= len(line_text):
691 self.current_char = len(line_text) - 1
692 char_value = line_text[self.current_char]
693 if char_value == " ":
694 self.present_mode_message(_("space"))
695 return
696 self.env["runtime"]["OutputManager"].present_text(
697 char_value,
698 interrupt=True,
699 ignore_punctuation=True,
700 announce_capital=True,
701 )
702
703 def _announce_word_at_current_char(self):
704 if self.current_line < 0 or self.current_line >= len(self.lines):
705 self.present_mode_message(_("No diff file loaded."))
706 return
707 line_text = self.lines[self.current_line]
708 for start, end in self._get_word_spans(line_text):
709 if start <= self.current_char < end:
710 self.present_mode_message(line_text[start:end])
711 return
712 self.present_mode_message(_("No word at current position."))
713
714 def _ensure_current_line(self):
715 if not self.has_loaded_diff():
716 self.present_mode_message(_("No diff file loaded."))
717 return False
718 if self.current_line < 0:
719 self.current_line = 0
720 self.current_char = 0
721 if self.current_line >= len(self.lines):
722 self.current_line = len(self.lines) - 1
723 self.current_char = 0
724 return True
725
726 def _get_word_spans(self, line_text):
727 return [match.span() for match in re.finditer(r"\S+", line_text)]
728
729 def _announce_file_section(self, line_index, line_meta):
730 file_index = line_meta["file_index"]
731 if file_index == -1 or file_index >= len(self.file_sections):
732 self.present_mode_message(_("File section."))
733 return
734 file_section = self.file_sections[file_index]
735 message = (
736 _("File section ")
737 + str(file_index + 1)
738 + _(" of ")
739 + str(len(self.file_sections))
740 + _(". Plus ")
741 + str(file_section["added_count"])
742 + _(", minus ")
743 + str(file_section["removed_count"])
744 + "."
745 )
746 self.present_mode_message(message)
747
748 def _announce_hunk_section(self, line_index, line_meta, line_text):
749 hunk_index = line_meta["hunk_index"]
750 if hunk_index == -1 or hunk_index >= len(self.hunk_sections):
751 self.present_mode_message(_("Hunk section."))
752 return
753
754 hunk_section = self.hunk_sections[hunk_index]
755 file_index = hunk_section["file_index"]
756 file_position = file_index + 1 if file_index >= 0 else 0
757 hunk_position = hunk_section["position_in_file"]
758 hunk_total = hunk_section["hunks_in_file"]
759
760 message = (
761 _("Hunk ")
762 + str(hunk_position)
763 + _(" of ")
764 + str(hunk_total)
765 + _(" in file ")
766 + str(file_position)
767 + _(" of ")
768 + str(len(self.file_sections))
769 + _(". Plus ")
770 + str(hunk_section["added_count"])
771 + _(", minus ")
772 + str(hunk_section["removed_count"])
773 + "."
774 )
775
776 if self._get_diff_verbosity() == "verbose":
777 message += " " + self._line_content_for_speech(line_text, "hunk_header")
778
779 self.present_mode_message(message)
780
781 def _line_content_for_speech(self, line_text, role):
782 line_text = self._normalize_diff_line_content(line_text, role)
783 if line_text.strip() == "":
784 return _("blank")
785 return line_text
786
787 def _normalize_diff_line_content(self, line_text, role):
788 if role == "added_line":
789 stripped_line = line_text.lstrip("+")
790 if stripped_line.strip() == "" and line_text.startswith("+"):
791 return _("added")
792 return stripped_line
793 if role == "removed_line":
794 stripped_line = line_text.lstrip("-")
795 if stripped_line.strip() == "" and line_text.startswith("-"):
796 return _("removed")
797 return stripped_line
798 return line_text
799
800 def _build_location_text(self, line_index):
801 if line_index < 0 or line_index >= len(self.line_meta):
802 return ""
803 line_meta = self.line_meta[line_index]
804 file_index = line_meta["file_index"]
805 hunk_index = line_meta["hunk_index"]
806 location_parts = []
807
808 if file_index != -1 and file_index < len(self.file_sections):
809 location_parts.append(
810 _("File ")
811 + str(file_index + 1)
812 + _(" of ")
813 + str(len(self.file_sections))
814 + ".")
815
816 if hunk_index != -1 and hunk_index < len(self.hunk_sections):
817 hunk_info = self.hunk_sections[hunk_index]
818 location_parts.append(
819 _("Hunk ")
820 + str(hunk_info["position_in_file"])
821 + _(" of ")
822 + str(hunk_info["hunks_in_file"])
823 + "."
824 )
825
826 return " ".join(location_parts)
827
828 def _get_diff_verbosity(self):
829 verbosity = self.env["runtime"]["SettingsManager"].get_setting(
830 "general", "diff_verbosity"
831 ).lower()
832 if verbosity not in {"compact", "verbose"}:
833 return "compact"
834 return verbosity
835
836 def present_error(self, message):
837 self.present_mode_message(message)
838
839 def present_mode_message(self, message):
840 self.env["runtime"]["OutputManager"].present_text(
841 message,
842 interrupt=True,
843 )
844
845 def _install_diff_bindings(self):
846 self.bindings_backup = self.env["bindings"].copy()
847 self.raw_bindings_backup = self.env["rawBindings"].copy()
848
849 diff_bindings = {
850 str([1, ["KEY_H"]]): "DIFF_NEXT_HUNK",
851 str([1, sorted(["KEY_SHIFT", "KEY_H"])]): "DIFF_PREV_HUNK",
852 str([1, ["KEY_A"]]): "DIFF_NEXT_ADDED",
853 str([1, sorted(["KEY_SHIFT", "KEY_A"])]): "DIFF_PREV_ADDED",
854 str([1, ["KEY_D"]]): "DIFF_NEXT_REMOVED",
855 str([1, sorted(["KEY_SHIFT", "KEY_D"])]): "DIFF_PREV_REMOVED",
856 str([1, ["KEY_F"]]): "DIFF_NEXT_FILE_SECTION",
857 str([1, sorted(["KEY_SHIFT", "KEY_F"])]): "DIFF_PREV_FILE_SECTION",
858 str([1, ["KEY_S"]]): "DIFF_SUMMARY",
859 str([1, ["KEY_F1"]]): "DIFF_KEY_HELP",
860 str([1, ["KEY_UP"]]): "DIFF_PREV_LINE",
861 str([1, ["KEY_DOWN"]]): "DIFF_NEXT_LINE",
862 str([1, ["KEY_LEFT"]]): "DIFF_PREV_CHAR",
863 str([1, ["KEY_RIGHT"]]): "DIFF_NEXT_CHAR",
864 str([1, sorted(["KEY_CTRL", "KEY_LEFT"])]): "DIFF_PREV_WORD",
865 str([1, sorted(["KEY_CTRL", "KEY_RIGHT"])]): "DIFF_NEXT_WORD",
866 str([1, ["KEY_ESC"]]): "EXIT_DIFF_MODE",
867 str([1, sorted(["KEY_FENRIR", "KEY_CTRL", "KEY_D"])]): "TOGGLE_DIFF_MODE",
868 }
869
870 diff_raw_bindings = {
871 shortcut: [1, keys]
872 for shortcut, keys in [
873 (str([1, ["KEY_H"]]), ["KEY_H"]),
874 (str([1, sorted(["KEY_SHIFT", "KEY_H"])]), sorted(["KEY_SHIFT", "KEY_H"])),
875 (str([1, ["KEY_A"]]), ["KEY_A"]),
876 (str([1, sorted(["KEY_SHIFT", "KEY_A"])]), sorted(["KEY_SHIFT", "KEY_A"])),
877 (str([1, ["KEY_D"]]), ["KEY_D"]),
878 (str([1, sorted(["KEY_SHIFT", "KEY_D"])]), sorted(["KEY_SHIFT", "KEY_D"])),
879 (str([1, ["KEY_F"]]), ["KEY_F"]),
880 (str([1, sorted(["KEY_SHIFT", "KEY_F"])]), sorted(["KEY_SHIFT", "KEY_F"])),
881 (str([1, ["KEY_S"]]), ["KEY_S"]),
882 (str([1, ["KEY_F1"]]), ["KEY_F1"]),
883 (str([1, ["KEY_UP"]]), ["KEY_UP"]),
884 (str([1, ["KEY_DOWN"]]), ["KEY_DOWN"]),
885 (str([1, ["KEY_LEFT"]]), ["KEY_LEFT"]),
886 (str([1, ["KEY_RIGHT"]]), ["KEY_RIGHT"]),
887 (
888 str([1, sorted(["KEY_CTRL", "KEY_LEFT"])]),
889 sorted(["KEY_CTRL", "KEY_LEFT"]),
890 ),
891 (
892 str([1, sorted(["KEY_CTRL", "KEY_RIGHT"])]),
893 sorted(["KEY_CTRL", "KEY_RIGHT"]),
894 ),
895 (str([1, ["KEY_ESC"]]), ["KEY_ESC"]),
896 (
897 str([1, sorted(["KEY_FENRIR", "KEY_CTRL", "KEY_D"])]),
898 sorted(["KEY_FENRIR", "KEY_CTRL", "KEY_D"]),
899 ),
900 ]
901 }
902
903 self.env["bindings"] = diff_bindings
904 self.env["rawBindings"] = diff_raw_bindings
905
906 def _restore_bindings(self):
907 if self.bindings_backup is not None:
908 self.env["bindings"] = self.bindings_backup
909 if self.raw_bindings_backup is not None:
910 self.env["rawBindings"] = self.raw_bindings_backup
911 self.bindings_backup = None
912 self.raw_bindings_backup = None
913
914 def _write_debug(self, message, level):
915 self.env["runtime"]["DebugManager"].write_debug_out(
916 message, level
917 )