select_link.py
68 lines · 2277 bytes
1import curses
2import re
3
4def load_links(filename):
5 links = []
6 with open(filename, 'r') as file:
7 content = file.read()
8 # Regex to match the name and URL pairs
9 matches = re.findall(r'(\S+)\s*>\s*(https?://\S+)', content)
10 links = [(name, url) for name, url in matches]
11 return links
12
13def display_links(stdscr, links):
14 curses.curs_set(0) # Hide the cursor
15 stdscr.clear()
16 h, w = stdscr.getmaxyx()
17 max_height = h - 1
18 start = 0
19 selected_index = 0
20
21 while True:
22 stdscr.clear()
23 for i in range(start, min(start + max_height, len(links))):
24 if i == selected_index:
25 stdscr.attron(curses.A_REVERSE) # Highlight the selected item
26 stdscr.addstr(i - start, 0, links[i][0])
27 if i == selected_index:
28 stdscr.attroff(curses.A_REVERSE) # Remove highlight after the line
29 stdscr.addstr(max_height, 0, "Use arrow keys to scroll, Enter to select, q to quit")
30 stdscr.refresh()
31
32 key = stdscr.getch()
33
34 if key == curses.KEY_DOWN:
35 if selected_index < len(links) - 1:
36 selected_index += 1
37 if selected_index >= start + max_height:
38 start += 1
39 elif key == curses.KEY_UP:
40 if selected_index > 0:
41 selected_index -= 1
42 if selected_index < start:
43 start -= 1
44 elif key == curses.KEY_ENTER or key == 10: # Enter key
45 stdscr.clear()
46 stdscr.addstr(0, 0, f"Selected URL: {links[selected_index][1]}")
47 # print("done")
48 with open("scripts/tmp/link", "w") as temp:
49 temp.write(links[selected_index][1])
50 stdscr.refresh()
51 # stdscr.getch() # Wait for any key press to exit
52 return links[selected_index][1]
53 break
54 elif key == ord('q'):
55 break
56
57def main(stdscr):
58 filename = 'scripts/tmp/links' # Replace with your file name
59 links = load_links(filename)
60 print("printed", display_links(stdscr, links))
61 print("done")
62
63# print(display_links(stdscr,links))
64if __name__ == "__main__":
65 try:
66 curses.wrapper(main)
67 except:
68 pass