gui.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. import ast
  2. import contextlib
  3. import logging
  4. import os
  5. import re
  6. from typing import ClassVar, Sequence
  7. import panel as pn
  8. from .core import OpenFile, get_filesystem_class, split_protocol
  9. from .registry import known_implementations
  10. pn.extension()
  11. logger = logging.getLogger("fsspec.gui")
  12. class SigSlot:
  13. """Signal-slot mixin, for Panel event passing
  14. Include this class in a widget manager's superclasses to be able to
  15. register events and callbacks on Panel widgets managed by that class.
  16. The method ``_register`` should be called as widgets are added, and external
  17. code should call ``connect`` to associate callbacks.
  18. By default, all signals emit a DEBUG logging statement.
  19. """
  20. # names of signals that this class may emit each of which must be
  21. # set by _register for any new instance
  22. signals: ClassVar[Sequence[str]] = []
  23. # names of actions that this class may respond to
  24. slots: ClassVar[Sequence[str]] = []
  25. # each of which must be a method name
  26. def __init__(self):
  27. self._ignoring_events = False
  28. self._sigs = {}
  29. self._map = {}
  30. self._setup()
  31. def _setup(self):
  32. """Create GUI elements and register signals"""
  33. self.panel = pn.pane.PaneBase()
  34. # no signals to set up in the base class
  35. def _register(
  36. self, widget, name, thing="value", log_level=logging.DEBUG, auto=False
  37. ):
  38. """Watch the given attribute of a widget and assign it a named event
  39. This is normally called at the time a widget is instantiated, in the
  40. class which owns it.
  41. Parameters
  42. ----------
  43. widget : pn.layout.Panel or None
  44. Widget to watch. If None, an anonymous signal not associated with
  45. any widget.
  46. name : str
  47. Name of this event
  48. thing : str
  49. Attribute of the given widget to watch
  50. log_level : int
  51. When the signal is triggered, a logging event of the given level
  52. will be fired in the dfviz logger.
  53. auto : bool
  54. If True, automatically connects with a method in this class of the
  55. same name.
  56. """
  57. if name not in self.signals:
  58. raise ValueError(f"Attempt to assign an undeclared signal: {name}")
  59. self._sigs[name] = {
  60. "widget": widget,
  61. "callbacks": [],
  62. "thing": thing,
  63. "log": log_level,
  64. }
  65. wn = "-".join(
  66. [
  67. getattr(widget, "name", str(widget)) if widget is not None else "none",
  68. thing,
  69. ]
  70. )
  71. self._map[wn] = name
  72. if widget is not None:
  73. widget.param.watch(self._signal, thing, onlychanged=True)
  74. if auto and hasattr(self, name):
  75. self.connect(name, getattr(self, name))
  76. def _repr_mimebundle_(self, *args, **kwargs):
  77. """Display in a notebook or a server"""
  78. try:
  79. return self.panel._repr_mimebundle_(*args, **kwargs)
  80. except (ValueError, AttributeError) as exc:
  81. raise NotImplementedError(
  82. "Panel does not seem to be set up properly"
  83. ) from exc
  84. def connect(self, signal, slot):
  85. """Associate call back with given event
  86. The callback must be a function which takes the "new" value of the
  87. watched attribute as the only parameter. If the callback return False,
  88. this cancels any further processing of the given event.
  89. Alternatively, the callback can be a string, in which case it means
  90. emitting the correspondingly-named event (i.e., connect to self)
  91. """
  92. self._sigs[signal]["callbacks"].append(slot)
  93. def _signal(self, event):
  94. """This is called by a an action on a widget
  95. Within an self.ignore_events context, nothing happens.
  96. Tests can execute this method by directly changing the values of
  97. widget components.
  98. """
  99. if not self._ignoring_events:
  100. wn = "-".join([event.obj.name, event.name])
  101. if wn in self._map and self._map[wn] in self._sigs:
  102. self._emit(self._map[wn], event.new)
  103. @contextlib.contextmanager
  104. def ignore_events(self):
  105. """Temporarily turn off events processing in this instance
  106. (does not propagate to children)
  107. """
  108. self._ignoring_events = True
  109. try:
  110. yield
  111. finally:
  112. self._ignoring_events = False
  113. def _emit(self, sig, value=None):
  114. """An event happened, call its callbacks
  115. This method can be used in tests to simulate message passing without
  116. directly changing visual elements.
  117. Calling of callbacks will halt whenever one returns False.
  118. """
  119. logger.log(self._sigs[sig]["log"], f"{sig}: {value}")
  120. for callback in self._sigs[sig]["callbacks"]:
  121. if isinstance(callback, str):
  122. self._emit(callback)
  123. else:
  124. try:
  125. # running callbacks should not break the interface
  126. ret = callback(value)
  127. if ret is False:
  128. break
  129. except Exception as e:
  130. logger.exception(
  131. "Exception (%s) while executing callback for signal: %s",
  132. e,
  133. sig,
  134. )
  135. def show(self, threads=False):
  136. """Open a new browser tab and display this instance's interface"""
  137. self.panel.show(threads=threads, verbose=False)
  138. return self
  139. class SingleSelect(SigSlot):
  140. """A multiselect which only allows you to select one item for an event"""
  141. signals = ["_selected", "selected"] # the first is internal
  142. slots = ["set_options", "set_selection", "add", "clear", "select"]
  143. def __init__(self, **kwargs):
  144. self.kwargs = kwargs
  145. super().__init__()
  146. def _setup(self):
  147. self.panel = pn.widgets.MultiSelect(**self.kwargs)
  148. self._register(self.panel, "_selected", "value")
  149. self._register(None, "selected")
  150. self.connect("_selected", self.select_one)
  151. def _signal(self, *args, **kwargs):
  152. super()._signal(*args, **kwargs)
  153. def select_one(self, *_):
  154. with self.ignore_events():
  155. val = [self.panel.value[-1]] if self.panel.value else []
  156. self.panel.value = val
  157. self._emit("selected", self.panel.value)
  158. def set_options(self, options):
  159. self.panel.options = options
  160. def clear(self):
  161. self.panel.options = []
  162. @property
  163. def value(self):
  164. return self.panel.value
  165. def set_selection(self, selection):
  166. self.panel.value = [selection]
  167. class FileSelector(SigSlot):
  168. """Panel-based graphical file selector widget
  169. Instances of this widget are interactive and can be displayed in jupyter by having
  170. them as the output of a cell, or in a separate browser tab using ``.show()``.
  171. """
  172. signals = [
  173. "protocol_changed",
  174. "selection_changed",
  175. "directory_entered",
  176. "home_clicked",
  177. "up_clicked",
  178. "go_clicked",
  179. "filters_changed",
  180. ]
  181. slots = ["set_filters", "go_home"]
  182. def __init__(self, url=None, filters=None, ignore=None, kwargs=None):
  183. """
  184. Parameters
  185. ----------
  186. url : str (optional)
  187. Initial value of the URL to populate the dialog; should include protocol
  188. filters : list(str) (optional)
  189. File endings to include in the listings. If not included, all files are
  190. allowed. Does not affect directories.
  191. If given, the endings will appear as checkboxes in the interface
  192. ignore : list(str) (optional)
  193. Regex(s) of file basename patterns to ignore, e.g., "\\." for typical
  194. hidden files on posix
  195. kwargs : dict (optional)
  196. To pass to file system instance
  197. """
  198. if url:
  199. self.init_protocol, url = split_protocol(url)
  200. else:
  201. self.init_protocol, url = "file", os.getcwd()
  202. self.init_url = url
  203. self.init_kwargs = (kwargs if isinstance(kwargs, str) else str(kwargs)) or "{}"
  204. self.filters = filters
  205. self.ignore = [re.compile(i) for i in ignore or []]
  206. self._fs = None
  207. super().__init__()
  208. def _setup(self):
  209. self.url = pn.widgets.TextInput(
  210. name="url",
  211. value=self.init_url,
  212. align="end",
  213. sizing_mode="stretch_width",
  214. width_policy="max",
  215. )
  216. self.protocol = pn.widgets.Select(
  217. options=sorted(known_implementations),
  218. value=self.init_protocol,
  219. name="protocol",
  220. align="center",
  221. )
  222. self.kwargs = pn.widgets.TextInput(
  223. name="kwargs", value=self.init_kwargs, align="center"
  224. )
  225. self.go = pn.widgets.Button(name="⇨", align="end", width=45)
  226. self.main = SingleSelect(size=10)
  227. self.home = pn.widgets.Button(name="🏠", width=40, height=30, align="end")
  228. self.up = pn.widgets.Button(name="‹", width=30, height=30, align="end")
  229. self._register(self.protocol, "protocol_changed", auto=True)
  230. self._register(self.go, "go_clicked", "clicks", auto=True)
  231. self._register(self.up, "up_clicked", "clicks", auto=True)
  232. self._register(self.home, "home_clicked", "clicks", auto=True)
  233. self._register(None, "selection_changed")
  234. self.main.connect("selected", self.selection_changed)
  235. self._register(None, "directory_entered")
  236. self.prev_protocol = self.protocol.value
  237. self.prev_kwargs = self.storage_options
  238. self.filter_sel = pn.widgets.CheckBoxGroup(
  239. value=[], options=[], inline=False, align="end", width_policy="min"
  240. )
  241. self._register(self.filter_sel, "filters_changed", auto=True)
  242. self.panel = pn.Column(
  243. pn.Row(self.protocol, self.kwargs),
  244. pn.Row(self.home, self.up, self.url, self.go, self.filter_sel),
  245. self.main.panel,
  246. )
  247. self.set_filters(self.filters)
  248. self.go_clicked()
  249. def set_filters(self, filters=None):
  250. self.filters = filters
  251. if filters:
  252. self.filter_sel.options = filters
  253. self.filter_sel.value = filters
  254. else:
  255. self.filter_sel.options = []
  256. self.filter_sel.value = []
  257. @property
  258. def storage_options(self):
  259. """Value of the kwargs box as a dictionary"""
  260. return ast.literal_eval(self.kwargs.value) or {}
  261. @property
  262. def fs(self):
  263. """Current filesystem instance"""
  264. if self._fs is None:
  265. cls = get_filesystem_class(self.protocol.value)
  266. self._fs = cls(**self.storage_options)
  267. return self._fs
  268. @property
  269. def urlpath(self):
  270. """URL of currently selected item"""
  271. return (
  272. (f"{self.protocol.value}://{self.main.value[0]}")
  273. if self.main.value
  274. else None
  275. )
  276. def open_file(self, mode="rb", compression=None, encoding=None):
  277. """Create OpenFile instance for the currently selected item
  278. For example, in a notebook you might do something like
  279. .. code-block::
  280. [ ]: sel = FileSelector(); sel
  281. # user selects their file
  282. [ ]: with sel.open_file('rb') as f:
  283. ... out = f.read()
  284. Parameters
  285. ----------
  286. mode: str (optional)
  287. Open mode for the file.
  288. compression: str (optional)
  289. The interact with the file as compressed. Set to 'infer' to guess
  290. compression from the file ending
  291. encoding: str (optional)
  292. If using text mode, use this encoding; defaults to UTF8.
  293. """
  294. if self.urlpath is None:
  295. raise ValueError("No file selected")
  296. return OpenFile(self.fs, self.urlpath, mode, compression, encoding)
  297. def filters_changed(self, values):
  298. self.filters = values
  299. self.go_clicked()
  300. def selection_changed(self, *_):
  301. if self.urlpath is None:
  302. return
  303. if self.fs.isdir(self.urlpath):
  304. self.url.value = self.fs._strip_protocol(self.urlpath)
  305. self.go_clicked()
  306. def go_clicked(self, *_):
  307. if (
  308. self.prev_protocol != self.protocol.value
  309. or self.prev_kwargs != self.storage_options
  310. ):
  311. self._fs = None # causes fs to be recreated
  312. self.prev_protocol = self.protocol.value
  313. self.prev_kwargs = self.storage_options
  314. listing = sorted(
  315. self.fs.ls(self.url.value, detail=True), key=lambda x: x["name"]
  316. )
  317. listing = [
  318. l
  319. for l in listing
  320. if not any(i.match(l["name"].rsplit("/", 1)[-1]) for i in self.ignore)
  321. ]
  322. folders = {
  323. "📁 " + o["name"].rsplit("/", 1)[-1]: o["name"]
  324. for o in listing
  325. if o["type"] == "directory"
  326. }
  327. files = {
  328. "📄 " + o["name"].rsplit("/", 1)[-1]: o["name"]
  329. for o in listing
  330. if o["type"] == "file"
  331. }
  332. if self.filters:
  333. files = {
  334. k: v
  335. for k, v in files.items()
  336. if any(v.endswith(ext) for ext in self.filters)
  337. }
  338. self.main.set_options(dict(**folders, **files))
  339. def protocol_changed(self, *_):
  340. self._fs = None
  341. self.main.options = []
  342. self.url.value = ""
  343. def home_clicked(self, *_):
  344. self.protocol.value = self.init_protocol
  345. self.kwargs.value = self.init_kwargs
  346. self.url.value = self.init_url
  347. self.go_clicked()
  348. def up_clicked(self, *_):
  349. self.url.value = self.fs._parent(self.url.value)
  350. self.go_clicked()