Files
douyi_guaji_main/gui/components/text_search.py
T

100 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""通用文本 widget 搜索函数。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``_generic_search_widget``,
被运行日志和行为日志两处搜索功能共用,本身是纯函数(不依赖 ``main()`` 闭包变量),
适合直接迁到模块顶层。
行为不变:在 widget 中根据 search_var 搜索并高亮;返回更新后的当前匹配索引。
"""
from __future__ import annotations
import tkinter as tk
from typing import List, Tuple
def generic_search_widget(
widget: tk.Text,
search_var: tk.StringVar,
matches_list: List[Tuple[str, str]],
current_index: int,
direction: int = 1,
) -> int:
"""通用的文本控件搜索函数:在 widget 中根据 search_var 搜索并高亮。
- widget: 文本控件(ScrolledText)
- search_var: tk.StringVar (包含搜索词)
- matches_list: 可变列表,用来保存匹配区间 (start_index, end_index)
- current_index: 当前匹配的索引(整数),返回更新后的索引
- direction: 1 为下一个,-1 为上一个
"""
search_text = search_var.get().strip()
if not search_text:
try:
widget.tag_remove("search_highlight", "1.0", "end")
widget.tag_remove("search_current", "1.0", "end")
except Exception:
pass
matches_list.clear()
return -1
content = widget.get("1.0", "end-1c")
if not content:
return -1
try:
widget.tag_remove("search_highlight", "1.0", "end")
widget.tag_remove("search_current", "1.0", "end")
except Exception:
pass
try:
widget.tag_config("search_highlight", background="yellow")
widget.tag_config("search_current", background="orange")
except Exception:
pass
matches_list.clear()
start_pos = 0
search_text_lower = search_text.lower()
content_lower = content.lower()
while True:
pos = content_lower.find(search_text_lower, start_pos)
if pos == -1:
break
line_start = content[:pos].rfind("\n") + 1
line_num = content[:pos].count("\n") + 1
col_num = pos - line_start
start_index = f"{line_num}.{col_num}"
end_index = f"{line_num}.{col_num + len(search_text)}"
matches_list.append((start_index, end_index))
start_pos = pos + 1
if not matches_list:
return -1
for s, e in matches_list:
try:
widget.tag_add("search_highlight", s, e)
except Exception:
pass
if direction == 1:
current_index = (current_index + 1) % len(matches_list)
else:
current_index = (current_index - 1) % len(matches_list)
try:
s, e = matches_list[current_index]
widget.tag_add("search_current", s, e)
widget.see(s)
widget.mark_set("insert", s)
except Exception:
pass
return current_index