Debian Codegraph @

cylc/flow/tui/overlay.py

raw
1 #!/usr/bin/env python3
2 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
3 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 """Overlay panels for Tui.
18
19 Panels are functions::
20
21 function(app) -> (widget, overlay_options)
22
23 Parameters:
24
25 app:
26 Tui application object.
27 widget (urwid.Widget):
28 A widget to place in the overlay.
29 overlay_options (dict):
30 A dictionary of keyword arguments to provide to the
31 urwid.Overlay constructor.
32
33 You will likely want to override the `width` and `height`
34 arguments.
35
36 See the `urwid` documentation for details.
37
38 """
39
40 from functools import partial
41 import os
42 import re
43 import shlex
44 import stat
45 from subprocess import Popen
46 import sys
47 import tempfile
48 from time import sleep
49
50 import urwid
51
52 from cylc.flow.id import Tokens
53 from cylc.flow.task_state import (
54 TASK_STATUSES_ORDERED,
55 TASK_STATUS_WAITING
56 )
57 from cylc.flow.tui import (
58 JOB_COLOURS,
59 JOB_ICON,
60 TUI
61 )
62 from cylc.flow.tui.data import (
63 list_mutations,
64 mutate,
65 )
66 from cylc.flow.tui.util import (
67 ListBoxPlus,
68 MODIFIER_ATTR_MAPPING,
69 get_status_str,
70 get_task_icon,
71 get_text_dimensions,
72 )
73
74
75 def _get_display_id(id_):
76 """Return an ID for display in context menus.
77
78 * Display the full ID for users/workflows
79 * Display the relative ID for everything else
80
81 """
82 tokens = Tokens(id_)
83 if tokens.is_task_like:
84 # if it's a cycle/task/job, then use the relative id
85 return tokens.relative_id
86 else:
87 # otherwise use the full id
88 return tokens.id
89
90
91 def _toggle_filter(app, filter_group, status, *_):
92 """Toggle a filter state."""
93 app.filters[filter_group][status] = not app.filters[filter_group][status]
94 app.updater.update_filters(app.filters)
95
96
97 def _invert_filter(checkboxes, *_):
98 """Invert the state of all filters."""
99 for checkbox in checkboxes:
100 checkbox.set_state(not checkbox.state)
101
102
103 def filter_workflow_state(app):
104 """Return a widget for adjusting the workflow filter options."""
105 checkboxes = [
106 urwid.CheckBox(
107 [status],
108 state=is_on,
109 on_state_change=partial(_toggle_filter, app, 'workflows', status)
110 )
111 for status, is_on in app.filters['workflows'].items()
112 if status != 'id'
113 ]
114
115 workflow_id_prompt = 'id (regex)'
116
117 def update_id_filter(widget, value):
118 try:
119 # ensure the filter is value before updating the filter
120 re.compile(value)
121 except re.error:
122 # error in the regex -> inform the user
123 widget.set_caption(f'{workflow_id_prompt} - error: \n')
124 else:
125 # valid regex -> update the filter
126 widget.set_caption(f'{workflow_id_prompt}: \n')
127 app.filters['workflows']['id'] = value
128 app.updater.update_filters(app.filters)
129
130 id_filter_widget = urwid.Edit(
131 caption=f'{workflow_id_prompt}: \n',
132 edit_text=app.filters['workflows']['id'],
133 )
134 urwid.connect_signal(id_filter_widget, 'change', update_id_filter)
135
136 widget = urwid.ListBox(
137 urwid.SimpleFocusListWalker([
138 urwid.Text('Filter Workflow States'),
139 urwid.Divider(),
140 urwid.Padding(
141 urwid.Button(
142 'Invert',
143 on_press=partial(_invert_filter, checkboxes)
144 ),
145 right=19
146 )
147 ] + checkboxes + [
148 urwid.Divider(),
149 id_filter_widget,
150 ])
151 )
152
153 return (
154 widget,
155 {'width': 35, 'height': 23}
156 )
157
158
159 def filter_task_state(app):
160 """Return a widget for adjusting the task state filter."""
161
162 checkboxes = [
163 urwid.CheckBox(
164 get_task_icon(state, colour='overlay')
165 + [' ' + state],
166 state=is_on,
167 on_state_change=partial(_toggle_filter, app, 'tasks', state)
168 )
169 for state, is_on in app.filters['tasks'].items()
170 ]
171
172 widget = urwid.ListBox(
173 urwid.SimpleFocusListWalker([
174 urwid.Text('Filter Task States'),
175 urwid.Divider(),
176 urwid.Padding(
177 urwid.Button(
178 'Invert',
179 on_press=partial(_invert_filter, checkboxes)
180 ),
181 right=19
182 )
183 ] + checkboxes)
184 )
185
186 return (
187 widget,
188 {'width': 35, 'height': 23}
189 )
190
191
192 def help_info(app):
193 """Return a widget displaying help information."""
194 # system title
195 items = [
196 urwid.Text(r'''
197 _ _ _
198 | | | | (_)
199 ___ _ _| | ___ | |_ _ _ _
200 / __| | | | |/ __| | __| | | | |
201 | (__| |_| | | (__ | |_| |_| | |
202 \___|\__, |_|\___| \__|\__,_|_|
203 __/ |
204 |___/
205
206 ( scroll using arrow keys )
207
208 '''),
209 urwid.Text(TUI)
210 ]
211
212 # list key bindings
213 for group, bindings in app.bindings.list_groups():
214 items.append(
215 urwid.Text([
216 f'{group["desc"]}:'
217 ])
218 )
219 for binding in bindings:
220 keystr = ' '.join(binding['keys'])
221 items.append(
222 urwid.Text([
223 (' '),
224 ('key', keystr),
225 (' ' * (10 - len(keystr))),
226 binding['desc']
227 ])
228 )
229 items.append(
230 urwid.Divider()
231 )
232
233 # mouse interaction
234 items.extend([
235 urwid.Text(
236 'fn + ⌥ & click to select text' if sys.platform == 'darwin' else
237 'Shift & click to select text'
238 ),
239 urwid.Divider()
240 ])
241
242 # list task states
243 items.append(urwid.Divider())
244 items.append(urwid.Text('Task Icons:'))
245 for state in TASK_STATUSES_ORDERED:
246 items.append(
247 urwid.Text(
248 [' ']
249 + get_task_icon(state, colour='overlay')
250 + [' ', state]
251 )
252 )
253
254 items.append(urwid.Divider())
255 items.append(urwid.Text('Special States:'))
256 for modifier_text, (modifier_attr, _) in MODIFIER_ATTR_MAPPING.items():
257 items.append(
258 urwid.Text(
259 [' ']
260 + get_task_icon(
261 TASK_STATUS_WAITING,
262 **{modifier_attr: True},
263 colour='overlay'
264 )
265 + [' ', modifier_text]
266 )
267 )
268
269 # list job states
270 items.append(urwid.Divider())
271 items.append(urwid.Text('Job Icons:'))
272 for state in JOB_COLOURS:
273 items.append(
274 urwid.Text(
275 [
276 ' ',
277 (f'overlay_job_{state}', JOB_ICON),
278 ' ',
279 state
280 ]
281 )
282 )
283
284 widget = urwid.ListBox(
285 urwid.SimpleFocusListWalker(items)
286 )
287
288 return (
289 widget,
290 {'width': 60, 'height': 40}
291 )
292
293
294 def context(app):
295 """An overlay for context menus."""
296 value = app.tree_walker.get_focus()[0].get_node().get_value()
297 selection = [value['id_']] # single selection ATM
298
299 is_running = True
300 if (
301 value['type_'] == 'workflow'
302 and value['data']['status'] not in {'running', 'paused'}
303 ):
304 # this is a stopped workflow
305 # => don't display mutations only valid for a running workflow
306 is_running = False
307
308 def _mutate(mutation, _):
309 app.open_overlay(partial(progress, text='Running Command'))
310 overlay_fcn = None
311 try:
312 overlay_fcn = mutate(mutation, selection)
313 except Exception as exc:
314 app.open_overlay(partial(error, text=str(exc)))
315 else:
316 app.close_topmost()
317 app.close_topmost()
318 if overlay_fcn:
319 app.open_overlay(overlay_fcn)
320
321 # determine the ID to display for the context menu
322 display_id = _get_display_id(value['id_'])
323 header = [
324 f'id: {display_id}',
325 get_status_str(value['data']),
326 ]
327
328 widget = urwid.ListBox(
329 urwid.SimpleFocusListWalker(
330 [
331 urwid.Text('\n'.join(header)),
332 urwid.Divider(),
333 urwid.Text('Action'),
334 urwid.Button(
335 '(cancel)',
336 on_press=lambda *_: app.close_topmost()
337 ),
338 urwid.Divider()
339 ] + [
340 urwid.Button(
341 mutation,
342 on_press=partial(_mutate, mutation)
343 )
344 for mutation in list_mutations(
345 selection,
346 is_running,
347 )
348 ]
349 )
350 )
351
352 return (
353 widget,
354 {'width': 50, 'height': 20}
355 )
356
357
358 def error(app, text=''):
359 """An overlay for unexpected errors."""
360 return (
361 urwid.ListBox([
362 urwid.Text('Error'),
363 urwid.Divider(),
364 urwid.Text(text),
365 ]),
366 {'width': 50, 'height': 40}
367 )
368
369
370 def progress(app, text='Working'):
371 """An overlay for presenting a running action."""
372 return (
373 urwid.ListBox([
374 urwid.Text(text),
375 ]),
376 {'width': 30, 'height': 10}
377 )
378
379
380 def log(app, id_=None, list_files=None, get_log=None):
381 """An overlay for displaying log files."""
382 # display the host name where the file is coming from
383 host_widget = urwid.Text('loading...')
384 # display the log filepath
385 file_widget = urwid.Text('')
386 # display the actual log file itself
387 text_widget = urwid.Text('')
388
389 def open_menu(*_args, **_kwargs):
390 """Open an overlay for selecting a log file."""
391 app.open_overlay(select_log)
392
393 def select_log(*_args, **_kwargs):
394 """Create an overlay for selecting a log file."""
395 try:
396 files = list_files()
397 except Exception as exc:
398 return error(app, text=str(exc))
399 return (
400 urwid.ListBox([
401 *[
402 urwid.Text('Select File'),
403 urwid.Divider(),
404 ],
405 *[
406 urwid.Button(
407 filename,
408 on_press=partial(
409 open_log,
410 filename=filename,
411 close=True,
412 ),
413 )
414 for filename in files
415 ],
416 ]),
417 # NOTE: the "+6" avoids the need for scrolling
418 {'width': 40, 'height': len(files) + 6}
419 )
420
421 def open_log(*_, filename=None, close=False):
422 """View the provided log file.
423
424 Args:
425 filename:
426 The name of the file to open (note name not path).
427 close:
428 If True, then the topmost overlay will be closed when a file is
429 selected. Use this to close the "select_log" overlay.
430
431 """
432 try:
433 host, path, text = get_log(filename)
434 except Exception as exc:
435 host_widget.set_text(f'Error: {exc}')
436 file_widget.set_text('')
437 text_widget.set_text('')
438 else:
439 host_widget.set_text(f'Host: {host}')
440 file_widget.set_text(f'Path: {path}')
441 text_widget.set_text(text)
442 if close:
443 app.close_topmost()
444
445 def open_in_editor(*_, command):
446 """Suspend Tui, open the file in an external utility, then restore Tui.
447
448 Args:
449 command:
450 The command to run as a list, e.g. 'gvim -f'.
451 This command must be blocking, the tui session will be
452 restored when the command exits.
453
454 """
455
456 with tempfile.NamedTemporaryFile('w+') as temp_file:
457 # write the text into a temp file
458 temp_file.write(text_widget.text)
459 temp_file.seek(0, 0)
460
461 # make the file readonly to avoid confusion
462 os.chmod(temp_file.name, stat.S_IRUSR)
463
464 # suspend Tui
465 app.loop.screen.stop()
466
467 # open the file using the external tool (must be blocking)
468 print(
469 'Launching external tool, Tui will resume once it exits.',
470 file=sys.stderr,
471 )
472 try:
473 Popen(
474 [*shlex.split(command), temp_file.name]
475 ).wait() # nosec B603
476 # (this is running a command the user has configured)
477 except OSError as exc:
478 # ensure any critical errors are visible to the user so
479 # that they have a chance to fix them
480 _sleep_time = 5
481 print(
482 (
483 f'Error running {command} {temp_file.name}'
484 f'\n{exc}'
485 f'\nTui will resume in {_sleep_time} seconds'
486 ),
487 file=sys.stderr
488 )
489 sleep(_sleep_time)
490
491 # restore Tui
492 app.loop.screen.start()
493
494 # load the default log file
495 if id_:
496 # NOTE: the kwargs are not provided in the overlay unit tests
497 open_log()
498
499 return (
500 ListBoxPlus([
501 # NOTE: We use a ListBox here because it allows the file-select
502 # button to have focus whilst keeping the overlay scrollable at the
503 # same time.
504 host_widget,
505 file_widget,
506 urwid.Button(
507 'Select File',
508 on_press=open_menu,
509 ),
510 urwid.Columns([
511 ('pack', urwid.Text('Open in: ')),
512 *(
513 (
514 'pack',
515 urwid.Button(
516 command,
517 align='left',
518 on_press=partial(open_in_editor, command=command),
519 ),
520 )
521 for command in [
522 os.environ.get('EDITOR', 'vim'),
523 os.environ.get('GEDITOR', 'gvim -f'),
524 os.environ.get('PAGER', 'less'),
525 ]
526 ),
527 ]),
528 urwid.Text(
529 "(Configure apps to open logs via $EDITOR, $GEDITOR, $PAGER)"
530 ),
531 urwid.Divider(),
532 text_widget,
533 ]),
534 # open full screen
535 {'width': 9999, 'height': 9999}
536 )
537
538
539 def text_box(app, text=''):
540 """A simple text box overlay."""
541 width, height = get_text_dimensions(text)
542 return (
543 urwid.ListBox([
544 urwid.Text(text),
545 ]),
546 # NOTE: those fudge factors account for the overlay border & padding
547 {'width': width + 4, 'height': height + 6}
548 )