-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsweep.py
executable file
·2058 lines (1787 loc) · 63.6 KB
/
sweep.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Asynchronous JSON-RPC implementation to communicate with sweep command"""
# pyright: strict
from __future__ import annotations
import asyncio
import base64
import inspect
import json
import os
import socket
import sys
import tempfile
import time
import warnings
from abc import ABC, abstractmethod
from asyncio import CancelledError, Future, StreamReader, StreamWriter
from asyncio.subprocess import Process
from asyncio.tasks import Task
from collections import defaultdict, deque
from collections.abc import (
AsyncGenerator,
AsyncIterator,
Awaitable,
Callable,
Coroutine,
Generator,
Iterable,
)
from contextlib import asynccontextmanager
from dataclasses import dataclass
from enum import Enum
from functools import partial
from typing import (
Any,
Literal,
NamedTuple,
Protocol,
TypedDict,
Unpack,
cast,
final,
override,
runtime_checkable,
)
__all__ = [
"Align",
"Bind",
"BindHandler",
"Candidate",
"Container",
"Direction",
"Event",
"Field",
"Flex",
"Icon",
"IconFrame",
"Image",
"Justify",
"Size",
"sweep",
"Sweep",
"SweepBind",
"SweepEvent",
"SweepSelect",
"SweepSize",
"SweepWindow",
"Text",
"View",
"ViewRef",
"WindowId",
]
# ------------------------------------------------------------------------------
# Sweep
# ------------------------------------------------------------------------------
class Size(NamedTuple):
height: int
width: int
@staticmethod
def from_json(obj: Any) -> Size:
height = None
width = None
if isinstance(obj, list):
obj = cast(list[Any], obj)
height, width = obj
elif isinstance(obj, dict):
obj = cast(dict[str, Any], obj)
height = obj.get("height")
width = obj.get("width")
if (
not isinstance(height, int)
or not isinstance(width, int)
or height < 0
or width < 0
):
raise ValueError(f"Invalid Size: {obj}")
return Size(height, width)
@dataclass
class SweepSelect[I]:
"""Event generated on item(s) select"""
uid: WindowId
items: list[I]
class SweepBind(NamedTuple):
"""Event generated on bound key press"""
uid: WindowId
tag: str
key: str | None
@override
def __repr__(self):
return f"SweepBind(tag={self.tag}, key={self.key})"
class SweepSize(NamedTuple):
cells: Size
pixels: Size
pixels_per_cell: Size
def cells_in_pixels(self, cells: Size) -> Size:
return Size(
height=self.pixels_per_cell.height * cells.height,
width=self.pixels_per_cell.width * cells.width,
)
@staticmethod
def from_json(obj: Any) -> SweepSize:
if not isinstance(obj, dict):
raise ValueError(f"Invalid SweepSize: {obj}")
obj = cast(dict[str, Any], obj)
cells = Size.from_json(obj.get("cells"))
pixels = Size.from_json(obj.get("pixels"))
pixels_per_cell = Size.from_json(obj.get("pixels_per_cell"))
return SweepSize(cells, pixels, pixels_per_cell)
@dataclass
class SweepWindow:
"""Fired on window transition"""
type: Literal["closed", "opened", "switched"]
uid_from: WindowId | None
uid_to: WindowId
@staticmethod
def from_json(type: str, obj: Any) -> SweepWindow:
if not isinstance(obj, dict):
raise ValueError(f"Invalid SweepWindow: {obj}")
if type not in ("closed", "opened", "switched"):
raise ValueError(f"Invalid SweepWindow type: {type}")
obj = cast(dict[str, Any], obj)
return SweepWindow(type=type, uid_from=obj.get("from"), uid_to=obj.get("to"))
@dataclass
class Field:
"""Filed structure used to construct `Candidate`"""
text: str = ""
glyph: Icon | None = None
view: View | None = None
active: bool = True
face: str | None = None
ref: int | None = None
@override
def __repr__(self) -> str:
attrs: list[str] = []
if self.text:
attrs.append(f"text={repr(self.text)}")
if not self.active:
attrs.append(f"active={self.active}")
if self.glyph is not None:
attrs.append(f"glyph={self.glyph}")
if self.view is not None:
attrs.append(f"view={self.view}")
if self.face is not None:
attrs.append(f"face={self.face}")
if self.ref is not None:
attrs.append(f"ref={self.ref}")
return f'Field({", ".join(attrs)})'
def to_json(self) -> dict[str, Any]:
"""Convert field to JSON"""
obj: dict[str, Any] = {}
if self.text:
obj["text"] = self.text
if not self.active:
obj["active"] = False
if self.glyph:
obj["glyph"] = self.glyph.to_json()
if self.view:
obj["view"] = self.view.to_json()
if self.face:
obj["face"] = self.face
if self.ref is not None:
obj["ref"] = self.ref
return obj
@staticmethod
def from_json(obj: Any) -> Field | None:
"""Create field from JSON object"""
if not isinstance(obj, dict):
return
obj = cast(dict[str, Any], obj)
active = obj.get("active")
return Field(
text=obj.get("text") or "",
active=True if active is None else active,
glyph=Icon.from_json(obj.get("glyph")),
face=obj.get("face"),
ref=obj.get("ref"),
)
@runtime_checkable
class ToCandidate(Protocol):
def to_candidate(self) -> Candidate: ...
@dataclass(slots=True)
class Candidate:
"""Convenient sweep item implementation"""
target: list[Field] | None = None
extra: dict[str, Any] | None = None
right: list[Field] | None = None
right_offset: int = 0
right_face: str | None = None
preview: list[Any] | None = None
preview_flex: float = 0.0
hotkey: str | None = None
def to_candidate(self) -> Candidate:
return self
def target_push(
self,
text: str = "",
active: bool = True,
glyph: Icon | None = None,
view: View | None = None,
face: str | None = None,
ref: int | None = None,
) -> Candidate:
"""Add field to the target (matchable left side text)"""
if self.target is None:
self.target = []
self.target.append(Field(text, glyph, view, active, face, ref))
return self
def right_push(
self,
text: str = "",
active: bool = False,
glyph: Icon | None = None,
view: View | None = None,
face: str | None = None,
ref: int | None = None,
) -> Candidate:
"""Add field to the right (unmatchable right side text)"""
if self.right is None:
self.right = []
self.right.append(Field(text, glyph, view, active, face, ref))
return self
def right_offset_set(self, offset: int) -> Candidate:
"""Set offset for the right side text"""
self.right_offset = offset
return self
def right_face_set(self, face: str) -> Candidate:
"""Set face used to fill right side text"""
self.right_face = face
return self
def preview_push(
self,
text: str = "",
active: bool = False,
glyph: Icon | None = None,
view: View | None = None,
face: str | None = None,
ref: int | None = None,
) -> Candidate:
"""Add field to the preview (text shown when item is highlighted)"""
if self.preview is None:
self.preview = []
self.preview.append(Field(text or "", glyph, view, active, face, ref))
return self
def preview_flex_set(self, flex: float) -> Candidate:
"""Set preview flex value"""
self.preview_flex = flex
return self
def extra_update(self, **entries: Any) -> Candidate:
"""Add entries to extra field"""
if self.extra is None:
self.extra = {}
self.extra.update(entries)
return self
def hotkey_set(self, hotkey: str) -> Candidate:
"""Assign hotkey for this candidate"""
self.hotkey = hotkey
return self
def tag[V](self, value: V) -> CandidateTagged[V]:
return CandidateTagged(value, self)
@override
def __repr__(self) -> str:
attrs: list[str] = []
if self.target is not None:
attrs.append(f"target={self.target}")
if self.extra is not None:
attrs.append(f"extra={self.extra}")
if self.right is not None:
attrs.append(f"right={self.right}")
if self.right_offset != 0:
attrs.append(f"right_offset={self.right_offset}")
if self.right_face:
attrs.append(f"right_face={self.right_face}")
if self.preview is not None:
attrs.append(f"preview={self.preview}")
if self.preview_flex != 0.0:
attrs.append(f"preview_flex={self.preview_flex}")
if self.hotkey is not None:
attrs.append(f"hotkey={self.hotkey}")
return f'Candidate({", ".join(attrs)})'
def to_json(self) -> dict[str, Any]:
"""Convert candidate to JSON object"""
obj: dict[str, Any] = self.extra.copy() if self.extra else {}
if self.target:
obj["target"] = [field.to_json() for field in self.target]
if self.right:
obj["right"] = [field.to_json() for field in self.right]
if self.right_offset:
obj["right_offset"] = self.right_offset
if self.right_face:
obj["right_face"] = self.right_face
if self.preview:
obj["preview"] = [field.to_json() for field in self.preview]
if self.preview_flex != 0.0:
obj["preview_flex"] = self.preview_flex
if self.hotkey is not None:
obj["hotkey"] = self.hotkey
return obj
@staticmethod
def from_json(obj: Any) -> Candidate | None:
"""Construct candidate from JSON object"""
if isinstance(obj, str):
return Candidate().target_push(obj)
if not isinstance(obj, dict):
return
def fields_from_json(fields_obj: Any) -> list[Field] | None:
if not isinstance(fields_obj, list):
return None
fields: list[Field] = []
for field_obj in cast(list[Any], fields_obj):
field = Field.from_json(field_obj)
if field is None:
continue
fields.append(field)
return fields or None
obj = cast(dict[str, Any], obj)
target = fields_from_json(obj.pop("target", None))
right = fields_from_json(obj.pop("right", None))
right_offset = obj.pop("offset", None) or 0
right_face = obj.pop("right_face", None)
preview = fields_from_json(obj.pop("preview", None))
preview_flex = obj.pop("preview_flex", None) or 0.0
hotkey = obj.pop("hotkey", None)
return Candidate(
target=target,
extra=obj or None,
right=right,
right_offset=right_offset,
right_face=right_face,
preview=preview,
preview_flex=preview_flex,
hotkey=hotkey,
)
@dataclass
class CandidateTagged[V]:
tag: V
candidate: Candidate
def to_candidate(self) -> Candidate:
return self.candidate
type SweepEvent[I] = SweepBind | SweepSize | SweepSelect[I] | SweepWindow
type BindHandler[I] = Callable[[Sweep[I], str], Awaitable[I | None]]
type FiledResolver = Callable[[int], Awaitable[Field | None]]
type ViewResolver = Callable[[int], Awaitable[View | None]]
type WindowId = str | int
@dataclass
class Bind[I]:
"""Bind structure
If handler returns not None then this value is returned as selected
"""
key: str
tag: str
desc: str
handler: BindHandler[I]
@staticmethod
def decorator(key: str, tag: str, desc: str) -> Callable[[BindHandler[I]], Bind[I]]:
"""Decorator to easier define binds
>>> @Bind.decorator("ctrl+c", "my.action", "My awesome action")
>>> async def my_action(_sweep, _tag):
>>> pass
"""
def bind_decorator(handler: BindHandler[I]) -> Bind[I]:
return Bind(key, tag, desc, handler)
return bind_decorator
class SweepArgs(TypedDict, total=False):
sweep: list[str] | None
prompt: str
preview: str | None
query: str | None
nth: str | None
delimiter: str | None
theme: str | None
scorer: str | None
tty: str | None
log: str | None
title: str | None
keep_order: bool
no_match: str | None
layout: str | None
tmp_socket: bool
field_resolver: FiledResolver | None
view_resolver: ViewResolver | None
window_uid: Any | None
async def sweep[I](
items: Iterable[I],
prompt_icon: Icon | str | None = None,
binds: list[Bind[I]] | None = None,
fields: dict[int, Any] | None = None,
views: dict[int, View] | None = None,
init: Callable[[Sweep[I]], Awaitable[None]] | None = None,
**options: Unpack[SweepArgs],
) -> list[I]:
"""Convenience wrapper around `Sweep`
Useful when you only need to select one candidate from a list of items
"""
async with Sweep[I](**options) as sweep:
# setup fields
if fields:
await sweep.field_register_many(fields)
if views:
for ref, view in views.items():
_ = await sweep.view_register(view, ref)
# setup binds
for bind in binds or []:
await sweep.bind_struct(bind)
# setup prompt
if isinstance(prompt_icon, str):
icon = Icon.from_str_or_file(prompt_icon)
else:
icon = prompt_icon
if icon is not None:
await sweep.prompt_set(prompt=options.get("prompt"), icon=icon)
# send items
await sweep.items_extend(items)
# init
if init is not None:
await init(sweep)
# wait events
async for event in sweep:
if isinstance(event, SweepSelect):
return event.items
return []
@final
class Sweep[I]:
"""RPC wrapper around sweep process
DEBUGGING:
- Load this file as python module from `python -masyncio`.
- Open other terminal window and execute `$ tty` command, then run something that
will not steal characters for sweep process like `$ sleep 100000`.
- Instantiate Sweep class with the tty device path of the other terminal.
- Now you can call all the methods of the Sweep class in an interactive mode.
- set RUST_LOG=debug
- specify log file
"""
__slots__ = [
"__args",
"__proc",
"__io_sock",
"__peer",
"__peer_iter",
"__tmp_socket",
"__items",
"__binds",
"__field_resolver",
"__field_resolved",
"__view_resolver",
"__view_resolved",
"__size",
"__window_uid_count",
"__window_uid_current",
]
def __init__(
self,
sweep: list[str] | None = None,
prompt: str = "INPUT",
preview: str | None = None,
query: str | None = None,
nth: str | None = None,
delimiter: str | None = None,
theme: str | None = None,
scorer: str | None = None,
tty: str | None = None,
log: str | None = None,
title: str | None = None,
keep_order: bool = False,
no_match: str | None = None,
layout: str | None = None,
tmp_socket: bool = False,
field_resolver: FiledResolver | None = None,
view_resolver: ViewResolver | None = None,
window_uid: WindowId | None = "default",
) -> None:
args: list[str] = []
args.extend(["--prompt", prompt])
if query is not None:
args.extend(["--query", query])
if isinstance(nth, str):
args.extend(["--nth", nth])
if delimiter is not None:
args.extend(["--delimiter", delimiter])
if theme is not None:
args.extend(["--theme", theme])
if scorer is not None:
args.extend(["--scorer", scorer])
if tty is not None:
args.extend(["--tty", tty])
if log is not None:
args.extend(["--log", log])
if title:
args.extend(["--title", title])
if keep_order:
args.append("--keep-order")
if no_match:
args.extend(["--no-match", no_match])
if layout:
args.extend(["--layout", layout])
if preview:
args.extend(["--preview", preview])
args.extend(["--window-uid", str(window_uid) if window_uid else ""])
sweep = sweep or ["sweep"]
self.__args: list[str] = [*sweep, "--rpc", *args]
self.__proc: Process | None = None
self.__io_sock: socket.socket | None = None
self.__tmp_socket: bool = tmp_socket # use tmp socket instead of socket pair
self.__peer: RpcPeer = RpcPeer()
self.__peer_iter: AsyncIterator[RpcRequest] = aiter(self.__peer)
self.__size: SweepSize | None = None
self.__items: defaultdict[WindowId, list[I]] = defaultdict(list)
self.__binds: dict[str, BindHandler[I]] = {}
self.__field_resolver: FiledResolver | None = field_resolver
self.__field_resolved: set[int] = set()
self.__view_resolver: ViewResolver | None = view_resolver
self.__view_resolved: set[int] = set()
self.__window_uid_count = 0
self.__window_uid_current: WindowId = (
"default" if window_uid is None else window_uid
)
async def __aenter__(self) -> Sweep[I]:
if self.__proc is not None:
raise RuntimeError("sweep process is already running")
if self.__tmp_socket:
self.__io_sock = await self.__proc_tmp_socket()
else:
self.__io_sock = await self.__proc_pair_socket()
reader, writer = await asyncio.open_unix_connection(sock=self.__io_sock)
create_task(self.__peer.serve(reader, writer), "sweep-rpc-peer")
return self
async def __proc_pair_socket(self) -> socket.socket:
"""Create sweep subprocess and connect via inherited socket pair"""
remote, local = socket.socketpair()
prog, *args = self.__args
self.__proc = await asyncio.create_subprocess_exec(
prog,
*[*args, "--io-socket", str(remote.fileno())],
pass_fds=[remote.fileno()],
)
remote.close()
return local
async def __proc_tmp_socket(self) -> socket.socket:
"""Create sweep subprocess and connect via on disk socket"""
io_sock_path = os.path.join(
tempfile.gettempdir(),
f"sweep-io-{os.getpid()}.socket",
)
if os.path.exists(io_sock_path):
os.unlink(io_sock_path)
io_sock_accept = unix_server_once(io_sock_path)
prog, *args = self.__args
self.__proc = await asyncio.create_subprocess_exec(
prog,
*[*args, "--io-socket", io_sock_path],
)
return await io_sock_accept
def __item_get(self, uid: WindowId | None, item: Any) -> I:
"""Return stored item if it was converted to Candidate"""
if isinstance(item, dict):
items = self.__items[uid or self.__window_uid_current]
item_dict = cast(dict[str, Any], item)
item_index: int | None = item_dict.get("_sweep_item_index")
if item_index is not None and item_index < len(items):
return items[item_index]
return cast(I, item)
async def __aexit__(self, _et: Any, ev: Any, _tb: Any) -> bool:
await self.terminate()
if isinstance(ev, CancelledError):
return True
return False
def __aiter__(self) -> AsyncIterator[SweepEvent[I]]:
async def event_iter() -> AsyncGenerator[SweepEvent[I], None]:
async for event in self.__peer_iter:
if not isinstance(event.params, dict):
continue
if event.method == "select":
uid = event.params["uid"]
yield SweepSelect(
uid=uid,
items=[
self.__item_get(uid, item)
for item in event.params.get("items", [])
],
)
elif event.method == "bind":
uid = event.params["uid"]
tag = event.params.get("tag", "")
handler = self.__binds.get(tag)
if handler is None:
yield SweepBind(
uid=uid,
tag=tag,
key=event.params.get("key", None),
)
else:
item = await handler(self, tag)
if item is not None:
yield SweepSelect(uid, items=[item])
elif event.method == "resize":
size = SweepSize.from_json(event.params)
self.__size = size
yield size
elif event.method in (
"window_closed",
"window_opened",
"window_switched",
):
window = SweepWindow.from_json(
event.method.removeprefix("window_"), event.params
)
if window.type == "switched":
self.__window_uid_current = window.uid_to
elif window.type == "closed":
self.__items.pop(window.uid_to, None)
yield window
elif event.method == "field_missing":
ref = event.params.get("ref")
if (
ref is None
or ref in self.__field_resolved
or self.__field_resolver is None
):
continue
field = await self.__field_resolver(ref)
if field is not None:
await self.field_register(field, ref)
elif event.method == "view_missing":
ref = event.params.get("ref")
if (
ref is None
or ref in self.__view_resolved
or self.__view_resolver is None
):
continue
view = await self.__view_resolver(ref)
if view is not None:
await self.view_register(view, ref)
return event_iter()
async def terminate(self) -> None:
"""Terminate underlying sweep process"""
proc, self.__proc = self.__proc, None
io_sock, self.__io_sock = self.__io_sock, None
self.__peer.terminate()
if io_sock is not None:
io_sock.close()
if proc is not None:
await proc.wait()
async def field_register_many(self, fields: dict[int, Field]) -> None:
for field_ref, field in fields.items():
_ = await self.field_register(field, field_ref)
async def field_register(self, field: Field, ref: int | None = None) -> int:
"""Register field that can later be reference by field with `ref` set"""
ref_val = await self.__peer.field_register(field.to_json(), ref)
self.__field_resolved.add(ref_val)
return ref_val
def field_resolver_set(
self,
field_resolver: FiledResolver | None,
) -> FiledResolver | None:
"""Set field resolver"""
field_resolver, self.__field_resolver = self.__field_resolver, field_resolver
return field_resolver
async def view_register(self, view: View, ref: int | ViewRef | None = None) -> int:
"""Register view that can be later referenced by `ViewRef`"""
ref_val = await self.__peer.view_register(
view.to_json(), ref.ref if isinstance(ref, ViewRef) else ref
)
self.__view_resolved.add(ref_val)
return ref_val
async def size(self) -> SweepSize:
"""Get size of the Sweep ui"""
while self.__size is None:
await self.__peer.events
return self.__size
async def items_extend(
self,
items: Iterable[I],
uid: WindowId | None = None,
) -> None:
"""Extend list of searchable items"""
time_start = time.monotonic()
time_limit = 0.05
batch: list[I | dict[str, Any]] = []
items_cache = self.__items[uid or self.__window_uid_current]
for item in items:
if isinstance(item, ToCandidate):
candidate = item.to_candidate()
candidate.extra_update(_sweep_item_index=len(items_cache))
batch.append(candidate.to_json())
items_cache.append(item)
else:
batch.append(item)
items_cache.append(item)
time_now = time.monotonic()
if time_now - time_start >= time_limit:
time_start = time_now
time_limit *= 1.25
await self.__peer.items_extend(uid=uid, items=batch)
batch.clear()
if batch:
await self.__peer.items_extend(uid=uid, items=batch)
async def item_update(
self,
index: int,
item: I,
uid: WindowId | None = None,
) -> None:
"""Update item by its index"""
assert index >= 0, "index must be non-negative"
items = self.__items[uid or self.__window_uid_current]
if index >= len(items):
raise IndexError(f"index {index} >= {len(items)}")
items[index] = item
if isinstance(item, ToCandidate):
candidate = item.to_candidate()
candidate.extra_update(_sweep_item_index=index)
await self.__peer.item_update(
uid=uid, index=index, item=candidate.to_json()
)
else:
await self.__peer.item_update(uid=uid, index=index, item=item)
async def items_clear(self, uid: WindowId | None = None) -> None:
"""Clear list of searchable items"""
await self.__peer.items_clear(uid=uid)
async def items_current(self, uid: WindowId | None = None) -> I | None:
"""Get currently selected item if any"""
return self.__item_get(uid, await self.__peer.items_current(uid=uid))
async def items_marked(self, uid: WindowId | None = None) -> list[I]:
"""Take currently marked items"""
items = await self.__peer.items_marked(uid)
return [self.__item_get(uid, item) for item in items]
async def cursor_set(self, position: int, uid: WindowId | None = None) -> None:
"""Set cursor to specified position"""
await self.__peer.cursor_set(uid=uid, position=position)
async def query_set(self, query: str, uid: WindowId | None = None) -> None:
"""Set query string used to filter items"""
await self.__peer.query_set(uid=uid, query=query)
async def query_get(self, uid: WindowId | None = None) -> str:
"""Get query string used to filter items"""
query: str = await self.__peer.query_get(uid=uid)
return query
async def prompt_set(
self,
prompt: str | None = None,
icon: Icon | None = None,
uid: WindowId | None = None,
) -> None:
"""Set prompt label and icon"""
attrs: dict[str, Any] = {}
if prompt is not None:
attrs["prompt"] = prompt
if icon is not None:
attrs["icon"] = icon.to_json()
if attrs:
await self.__peer.prompt_set(uid=uid, **attrs)
async def preview_set(
self,
value: bool | None,
uid: WindowId | None = None,
) -> None:
"""Whether to show preview associated with the current item"""
await self.__peer.preview_set(uid=uid, value=value)
async def footer_set(
self,
footer: View | None,
uid: WindowId | None = None,
) -> None:
"""Set footer view"""
if footer:
await self.__peer.footer_set(uid=uid, footer=footer.to_json())
else:
await self.__peer.footer_set(uid=uid)
async def bind_struct(self, bind: Bind[I], uid: WindowId | None = None) -> None:
await self.bind(bind.key, bind.tag, bind.desc, bind.handler, uid)
async def bind(
self,
key: str,
tag: str,
desc: str = "",
handler: BindHandler[I] | None = None,
uid: WindowId | None = None,
) -> None:
"""Assign new key binding
Arguments:
- `key` chord combination that triggers the bind
- `tag` unique bind identifier if it is empty bind is removed
- `description` of the bind shown in sweep help
- `handler` callback if it no specified `SweepBind` event is generated
otherwise, it called on key press
"""
if tag and handler:
self.__binds[tag] = handler
else:
self.__binds.pop(tag, None)
await self.__peer.bind(uid=uid, key=key, tag=tag, desc=desc)
async def window_switch(self, uid: WindowId, close: bool = False) -> bool:
"""Push new empty state
Returns `true` if window was created, `false` otherwise
"""
return await self.__peer.window_switch(uid=uid, close=close)
async def window_pop(self) -> None:
"""Pop previous state from the stack"""
await self.__peer.window_pop()
async def quick_select[H](
self,
items: Iterable[H],
prompt: str | None = None,
prompt_icon: Icon | None = None,
keep_order: bool | None = None,
theme: str | None = None,
scorer: str | None = None,
window_uid: WindowId | None = None,
) -> list[H]:
"""Create sub-sweep view to select from the list of items"""
haystack: list[H | dict[str, Any]] = []
haystack_index: dict[int, H] = {}
for item in items:
if isinstance(item, ToCandidate):
index = len(haystack_index)
haystack_index[index] = item
candidate = item.to_candidate()
candidate.extra_update(__sweep_item_index=index)
haystack.append(candidate.to_json())
else:
haystack.append(item)
if window_uid is None:
self.__window_uid_count += 1
window_uid = self.__window_uid_count
selected = await self.__peer.quick_select(
items=haystack,
prompt=prompt,
prompt_icon=None if prompt_icon is None else prompt_icon.to_json(),
keep_order=keep_order,
theme=theme,
scorer=scorer,
uid=window_uid,
)
result: list[H] = []
for item in selected:
if isinstance(item, dict):
item = cast(dict[str, Any], item)
item_index = item.get("__sweep_item_index")
if item_index is not None and (item := haystack_index.get(item_index)):
result.append(item)
else:
result.append(item)
return result
@asynccontextmanager
async def render_suppress(self, uid: WindowId | None = None) -> AsyncIterator[None]:
"""Suppress rending to reduce flicker during batch updates"""
try:
await self.__peer.render_suppress(uid=uid, suppress=True)
yield None
finally:
if not self.__peer.is_terminated:
await self.__peer.render_suppress(uid=uid, suppress=False)
def unix_server_once(path: str) -> Awaitable[socket.socket]:
"""Create unix server socket and accept one connection"""
loop = asyncio.get_running_loop()
if os.path.exists(path):
os.unlink(path)
server = socket.socket(socket.AF_UNIX)
server.bind(path)
server.listen()
async def accept() -> socket.socket:
try:
accept = loop.create_future()
loop.add_reader(server.fileno(), lambda: accept.set_result(None))
await accept
client, _ = server.accept()