gui.py 14 KB

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