blib/lib/Term/Fabulous/ThemeEditor.pm untested

filter: Statementstmt 0.0% 0 / 1190 Branchbran 0.0% 0 / 410 Conditioncond 0.0% 0 / 318 MC/DCmcdc 0.0% 0 / 183 Subroutinesub 0.0% 0 / 45 Podpod n/a totaltotal 0.0% 0 / 2146 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package Term::Fabulous::ThemeEditor;
2  
3 use v5.32;
4 use warnings;
5 use feature 'signatures';
6 no warnings 'experimental::signatures';
7  
8 our $VERSION = '0.05';
9  
10 use Object::Pad 0.825;
11  
12 class Term::Fabulous::ThemeEditor :strict(params) {
13 use Clay::UI::Enum::Result;
14 use Clay::XS qw(sizing_fixed sizing_grow sizing_percent CLAY_TOP_TO_BOTTOM);
15 use Cwd qw(abs_path getcwd);
16 use Encode qw(decode encode);
17 use Feature::Compat::Try;
18 use File::Basename qw(basename dirname);
19 use File::Spec;
20 use IO::Async::Loop;
21 use IO::Async::Signal;
22 use IO::Async::OS;
23 use IO::Async::Timer::Countdown;
24 use List::Util qw(any first max min);
25 use Scalar::Util qw(blessed refaddr weaken);
26 use Term::Fabulous::Check qw(describe);
27 use Term::Fabulous::Commands;
28 use Term::Fabulous::Editor;
29 use Term::Fabulous::Scrolling qw(scroll_by_key);
30 use Term::Fabulous::Theme;
31 use Term::Fabulous::Theme::Document;
32 use Term::Fabulous::ThemeEditor::Form;
33 use Term::Fabulous::ThemeEditor::Preview;
34 use Term::Fabulous::ThemeEditor::Tab;
35 use Term::Fabulous::ThemeEditor::UI;
36 use Term::Fabulous::ThemeEditor::ValueDialog;
37 use Term::Fabulous::Widget::Box;
38 use Term::Fabulous::Widget::DocumentTabs;
39 use Term::Fabulous::Widget::Dropdown;
40 use Term::Fabulous::Widget::FileDialog;
41 use Term::Fabulous::Widget::KeyReference;
42 use Term::Fabulous::Widget::MenuBar;
43 use Term::Fabulous::Widget::Prompt;
44 use Term::Fabulous::Widget::Text;
45 use Term::Fabulous::Widget::ScrollBox;
46 use Term::Fabulous::Widget::SegmentedControl;
47 use Term::Fabulous::Widget::StatusBar;
48 use Term::Fabulous::Widget::TextField;
49  
50 # How long the text must rest before it is parsed again, in seconds.
51 use constant PARSE_DELAY => 0.15;
52  
53 # What the open and save dialogs list.
54 use constant THEME_FILTERS => [ [ 'Theme files' => '*.kdl' ], [ 'All files' => '*' ] ];
55  
56 use constant WATCHED_SIGNALS => qw(TERM INT HUP);
57  
58 # ---------------------------------------------------------------------
59 # Parameters
60 # ---------------------------------------------------------------------
61  
62 field $files :param = [];
63 field $ui_theme :param = 'dark';
64 field $preview :param = undef; # a widget, or code that returns one
65 field $directory :param = undef;
66 field $terminal :param = undef;
67 field $width :param = 80;
68 field $height :param = 24;
69  
70 # ---------------------------------------------------------------------
71 # State
72 # ---------------------------------------------------------------------
73  
74 field $ui :reader;
75 field @tabs;
76 field $active; # index of the shown tab, undef when none is open
77 field $untitled_count = 0;
78 field $quitting = 0;
79 field $parse_timer;
80 field @recovered; # the recovery files the last run wrote
81 field @signal_watchers;
82 field %signals_before;
83 field $signalled = 0;
84  
85 field $menu;
86 field $strip;
87 field $gallery; # the Term::Fabulous::ThemeEditor::Preview, or undef for a custom preview
88 field $preview_root;
89 field $preview_pane;
90 field $preview_title;
91 field $settings_pane;
92 field $settings_title;
93 field $mode_switch;
94 field $content; # holds the form, the text or the welcome text
95 field $form :reader;
96 field $text_box;
97 field $errors_text;
98 field $welcome;
99 field $status :reader;
100 field $commands = Term::Fabulous::Commands->new;
101 field $find_text = '';
102  
103 ADJUST {
104 die "Term::Fabulous::ThemeEditor: files must be an array reference of file names, got " . describe($files) unless ref $files eq 'ARRAY' && !grep { !defined || ref || !length } @$files;
105 $directory //= getcwd();
106 die "Term::Fabulous::ThemeEditor: directory '$directory' is not a directory" unless -d $directory;
107 $self->_define_commands;
108 $self->_build_screen;
109 $self->open_file($_) foreach @$files;
110 $status->message( sprintf 'Opened %d themes. F1 lists every key; F10 or Alt with an underlined letter opens a menu.', scalar @tabs ) if @$files > 1;
111 $self->new_theme unless @tabs;
112 $self->_show_active;
113 $self->_focus_settings;
114 }
115  
116 # ---------------------------------------------------------------------
117 # Commands: every action, with its menu entry and keys
118 # ---------------------------------------------------------------------
119  
120 method _command ( $id, %definition ) {
121 $commands->add( { id => $id, %definition } );
122 return;
123 }
124  
125 method _define_commands () {
126 weaken( my $editor = $self );
127 my $has_tab = sub { defined $editor->active_tab };
128 my $in_form = sub { defined $editor->active_tab && $editor->active_tab->mode eq 'form' };
129 my $writable = sub { $in_form->() && !$editor->active_tab->document->has_syntax_error };
130  
131 $self->_command( new => label => 'New theme...', keys => ['Ctrl+N'], run => sub { $editor->_ask_new_theme } );
132 $self->_command( open => label => 'Open...', keys => ['Ctrl+O'], run => sub { $editor->_ask_open } );
133 $self->_command( save => label => 'Save', keys => ['Ctrl+S'], run => sub { $editor->_save }, enabled => $has_tab );
134 $self->_command( save_as => label => 'Save as...', keys => ['Alt+S'], run => sub { $editor->_save_as }, enabled => $has_tab );
135 $self->_command(
136 save_all => label => 'Save all',
137 keys => [],
138 run => sub { $editor->_save_all },
139 enabled => sub {
140 any { $_->is_modified } @tabs;
141 }
142 );
143 $self->_command(
144 revert => label => 'Revert to saved', keys => ['Ctrl+R'], run => sub { $editor->_revert },
145 enabled => sub { defined $editor->active_tab && defined $editor->active_tab->path && -f $editor->active_tab->path }
146 );
147 $self->_command( duplicate => label => 'Duplicate as new theme', keys => [], run => sub { $editor->_duplicate }, enabled => $has_tab );
148 $self->_command( close => label => 'Close tab', keys => ['Ctrl+W'], run => sub { $editor->close_tab }, enabled => $has_tab );
149 $self->_command( quit => label => 'Quit', keys => ['Ctrl+Q'], run => sub { $editor->_quit } );
150  
151 $self->_command( undo => label => 'Undo', keys => ['Ctrl+Z'], run => sub { $editor->_undo }, enabled => sub { defined $editor->active_tab && $editor->active_tab->can_undo } );
152 $self->_command( redo => label => 'Redo', keys => ['Ctrl+Y'], run => sub { $editor->_redo }, enabled => sub { defined $editor->active_tab && $editor->active_tab->can_redo } );
153 $self->_command( cut => label => 'Cut', keys => ['Ctrl+X'], run => sub { $editor->_cut }, enabled => $has_tab );
154 $self->_command( copy => label => 'Copy', keys => ['Ctrl+C'], run => sub { $editor->_copy }, enabled => $has_tab );
155 $self->_command( paste => label => 'Paste', keys => ['Ctrl+V'], run => sub { $editor->_paste }, enabled => $has_tab );
156 $self->_command( paste_keys => label => 'Paste at the copied keys', keys => ['Alt+P'], run => sub { $editor->_paste( at_keys => 1 ) }, enabled => $writable );
157 $self->_command( edit => label => 'Edit value...', keys => ['Enter'], run => sub { $editor->_edit_current }, enabled => sub { $writable->() && defined $editor->form->current_key } );
158 $self->_command( reset => label => 'Reset to default', keys => ['Delete'], run => sub { $editor->_reset_current }, enabled => $writable );
159 $self->_command( find => label => 'Find...', keys => ['Ctrl+F'], run => sub { $editor->_find }, enabled => $has_tab );
160 $self->_command( find_next => label => 'Find next', keys => ['F3'], run => sub { $editor->_find_next }, enabled => sub { defined $editor->active_tab && length $find_text } );
161 $self->_command(
162 next_error => label => 'Go to the next error', keys => ['F8'], run => sub { $editor->_next_error },
163 enabled => sub { defined $editor->active_tab && !$editor->active_tab->document->is_valid }
164 );
165  
166 $self->_command( toggle_mode => label => 'Form or text', keys => ['F2'], run => sub { $editor->_toggle_mode }, enabled => $has_tab );
167 $self->_command(
168 switch_pane => label => 'Preview or settings', keys => ['F6'], run => sub { $editor->_switch_pane },
169 enabled => sub { defined $editor->active_tab && $editor->_preview_shown }
170 );
171 $self->_command( toggle_preview => label => 'Show or hide the preview', keys => ['F7'], run => sub { $editor->_toggle_preview } );
172 $self->_command( only_set => label => 'Only set settings', keys => ['Alt+L'], run => sub { $editor->_toggle_only_set }, enabled => $in_form );
173 $self->_command( open_all => label => 'Open all sections', keys => [], run => sub { $editor->form->list->expand_all }, enabled => $in_form );
174 $self->_command( close_all => label => 'Close all sections', keys => [], run => sub { $editor->form->list->collapse_all }, enabled => $in_form );
175 $self->_command( previous_tab => label => 'Previous tab', keys => ['Alt+PageUp'], run => sub { $editor->select_tab( $active - 1 ) }, enabled => sub { @tabs > 1 } );
176 $self->_command( next_tab => label => 'Next tab', keys => ['Alt+PageDown'], run => sub { $editor->select_tab( $active + 1 ) }, enabled => sub { @tabs > 1 } );
177  
178 $self->_command( rename => label => 'Rename theme...', keys => [], run => sub { $editor->_edit_key('theme.name') }, enabled => $has_tab );
179 $self->_command( rebase => label => 'Change base theme...', keys => [], run => sub { $editor->_edit_key('theme.extends') }, enabled => $has_tab );
180 $self->_command( add_variant => label => 'Add variant...', keys => [], run => sub { $editor->_ask_add_variant }, enabled => $writable );
181 $self->_command( remove_variant => label => 'Remove variant', keys => [], run => sub { $editor->_remove_variant }, enabled => sub { $writable->() && defined $editor->_current_variant } );
182 $self->_command( reset_section => label => 'Reset section...', keys => [], run => sub { $editor->_reset_section }, enabled => sub { $writable->() && defined $editor->form->current } );
183 $self->_command( reset_theme => label => 'Reset whole theme...', keys => [], run => sub { $editor->_reset_theme }, enabled => $writable );
184  
185 $self->_command( keys => label => 'Key reference', keys => ['F1'], run => sub { $editor->_show_keys } );
186 $self->_command( about => label => 'About', keys => [], run => sub { $editor->_show_about } );
187 return;
188 }
189  
190 method _menus () {
191 return [
192 { title => 'File', items => [qw(new open - save save_as save_all revert - duplicate - close quit)] },
193 { title => 'Edit', items => [qw(undo redo - cut copy paste paste_keys - edit reset - find find_next next_error)] },
194 { title => 'View', items => [qw(toggle_mode switch_pane toggle_preview - only_set open_all close_all - previous_tab next_tab)] },
195 { title => 'Theme', items => [qw(rename rebase - add_variant remove_variant - reset_section reset_theme)] },
196 { title => 'Help', items => [qw(keys about)] },
197 ];
198 }
199  
200 method run_command ($id) {
201 return $commands->command($id)->run;
202 }
203  
204 # Every command: its id, its plain label and its keys.
205 method commands () {
206 return map { { id => $_->id, label => $_->plain_label, keys => [ $_->keys ] } } $commands->commands;
207 }
208  
209 method command_enabled ($id) {
210 return $commands->command($id)->is_enabled;
211 }
212  
213 # ---------------------------------------------------------------------
214 # The screen
215 # ---------------------------------------------------------------------
216  
217 method _build_screen () {
218 weaken( my $editor = $self ); # for the callbacks the parts keep
219 my $root = Term::Fabulous::Widget::Box->new( layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_grow(), height => sizing_grow() } } );
220  
221 $menu = Term::Fabulous::Widget::MenuBar->new(
222 commands => $commands,
223 menus => $self->_menus,
224 caption => 'Term::Fabulous theme editor',
225 layout => { sizing => { width => sizing_grow(), height => sizing_fixed(1) } },
226 );
227 $strip = Term::Fabulous::Widget::DocumentTabs->new(
228 tabs => sub { $editor->_tab_summaries },
229 layout => { sizing => { width => sizing_grow(), height => sizing_fixed(1) } },
230 );
231 $strip->on( Select => sub ( $self, $event ) { $self->select_tab( $event->index ); return }, owner => $self );
232 $strip->on( TabClose => sub ( $self, $event ) { $self->close_tab( $event->index ); return }, owner => $self );
233 $strip->on( TabAdd => sub ( $self, $event ) { $self->_ask_new_theme; return }, owner => $self );
234  
235 # The preview pane: the editor draws its frame and title, the preview
236 # inside it draws in the theme being edited.
237 $preview_title = Term::Fabulous::Widget::Text->new( text => 'Preview' );
238 $preview_root = $self->_preview_widget;
239 $preview_pane = $self->_pane( $preview_title, $preview_root );
240  
241 $settings_title = Term::Fabulous::Widget::Text->new( text => 'Settings' );
242 $mode_switch = Term::Fabulous::Widget::SegmentedControl->new( options => [ [ Form => 'form' ], [ Text => 'text' ] ], value => 'form', can_focus => 0 );
243 $mode_switch->on( Change => sub ( $self, $event ) { $self->set_mode( $event->value ); return Clay::UI::Enum::Result->CONTINUE }, owner => $self );
244 my $title_box = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow() } } );
245 $title_box->add_child($settings_title);
246 my $settings_head = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow() }, child_gap => 1 } );
247 $settings_head->add_child( $title_box, $mode_switch );
248 $content = Term::Fabulous::Widget::Box->new( layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_grow(), height => sizing_grow() } } );
249 $settings_pane = $self->_pane( $settings_head, $content );
250  
251 $form = Term::Fabulous::ThemeEditor::Form->new(
252 on_activate => sub ($key) { $editor->_edit_key($key) },
253 on_cursor => sub ($id) { $editor->_cursor_moved($id) },
254 );
255 $form->explain_with( sub ($row) { $editor->_explain($row) } );
256 $text_box = Term::Fabulous::Widget::Box->new( layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_grow(), height => sizing_grow() } } );
257 $errors_text = Term::Fabulous::Widget::Text->new( text => '' );
258 $welcome = Term::Fabulous::Widget::Text->new(
259 markup => "No theme is open.\n\n[bold]Ctrl+N[/] makes a new theme, [bold]Ctrl+O[/] opens a theme file, [bold]F1[/] lists every key, [bold]Ctrl+Q[/] quits.",
260 );
261  
262 my $workspace = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow(), height => sizing_grow() } } );
263 $workspace->add_child( $preview_pane, $settings_pane );
264  
265 $status = Term::Fabulous::Widget::StatusBar->new( parts => sub { $editor->_status_info }, layout => { sizing => { width => sizing_grow(), height => sizing_fixed(1) } } );
266 $root->add_child( $menu, $strip, $workspace, $status );
267  
268 $ui = Term::Fabulous::ThemeEditor::UI->new(
269 root => $root,
270 theme => $ui_theme,
271 stop_on_ctrl_c => 0,
272 width => $width,
273 height => $height,
274 ( defined $terminal ? ( terminal => $terminal ) : () ),
275 );
276 $ui->add_preview_root($preview_root);
277 $root->on( KeyPress => sub ( $self, $event ) { return $self->_key($event) ? Clay::UI::Enum::Result->HANDLED : Clay::UI::Enum::Result->CONTINUE }, owner => $self );
278 $root->on( OnFocus => sub ( $self, $event ) { $self->_focus_moved; return Clay::UI::Enum::Result->CONTINUE }, owner => $self );
279 $root->on(
280 Start => sub ( $self, $event ) {
281 $self->status->message('The terminal is narrow: F7 hides the preview, so the settings get the whole width.') if $event->width < 100;
282 return Clay::UI::Enum::Result->CONTINUE;
283 },
284 owner => $self
285 );
286 $root->on(
287 MouseMove => sub ( $self, $event ) {
288 my $list = $self->form->list;
289 $list->hover(undef) unless blessed $event->target && $list->contains( $event->target );
290 return Clay::UI::Enum::Result->CONTINUE;
291 },
292 owner => $self
293 );
294 $status->message('Welcome. F1 lists every key; F10 or Alt with an underlined letter opens a menu.');
295 return;
296 }
297  
298 # Hides the preview, so the settings take the whole width (on a narrow
299 # terminal), or shows it again.
300 method _preview_shown () {
301 return $settings_pane->parent->has_child($preview_pane) ? 1 : 0;
302 }
303  
304 method _toggle_preview () {
305 my $workspace = $settings_pane->parent;
306 my $shown = $workspace->has_child($preview_pane);
307 if ($shown) {
308 my $focused = $ui->interaction->get_focused_widget;
309 $self->_focus_settings if defined $focused && $preview_pane->contains($focused);
310 $workspace->remove_child($preview_pane);
311 }
312 else {
313 $workspace->insert_children( 0, $preview_pane );
314 }
315 $settings_pane->layout( { %{ $settings_pane->layout }, sizing => { width => $shown ? sizing_grow() : sizing_percent(0.5), height => sizing_grow() } } );
316 $status->message( $shown ? 'The preview is hidden; F7 shows it again.' : 'The preview is back.' );
317 return;
318 }
319  
320 # A framed part of the workspace.
321 method _pane ( $head, $body ) {
322 my $pane = Term::Fabulous::Widget::Box->new(
323 bordered => 1,
324 layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_percent(0.5), height => sizing_grow() }, padding => { left => 1, right => 1 } },
325 );
326 $pane->add_child( $head, $body );
327 return $pane;
328 }
329  
330 # The preview: the gallery, or the program's own widgets.
331 method _preview_widget () {
332 my $widget = ref $preview eq 'CODE' ? $preview->($self) : $preview;
333 if ( !defined $widget ) {
334 $gallery = Term::Fabulous::ThemeEditor::Preview->new;
335 return $gallery;
336 }
337 die "Term::Fabulous::ThemeEditor: preview must be a Term::Fabulous::Widget or code that returns one, got " . describe($widget)
338 unless blessed $widget && $widget->isa('Term::Fabulous::Widget');
339  
340 # A scroll box in both directions keeps any content inside the pane.
341 my $holder = Term::Fabulous::Widget::ScrollBox->new(
342 id => 'theme-editor-custom-preview',
343 horizontal => 1,
344 layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_grow(), height => sizing_grow() } },
345 );
346 $holder->add_child($widget);
347  
348 # PageUp, PageDown, Ctrl+Home and Ctrl+End scroll it when the
349 # focused widget in it does not use them.
350 $holder->on(
351 KeyPress => sub ( $holder, $event ) {
352 my $ui = $holder->ui // return Clay::UI::Enum::Result->CONTINUE;
353 return defined scroll_by_key( $ui, $holder, $event->main_key_name, keys => 'pager' ) ? Clay::UI::Enum::Result->HANDLED : Clay::UI::Enum::Result->CONTINUE;
354 },
355 owner => $holder
356 );
357 return $holder;
358 }
359  
360 # ---------------------------------------------------------------------
361 # Running
362 # ---------------------------------------------------------------------
363  
364 # Runs the editor until the user quits. A signal (TERM, INT, HUP) ends
365 # it too; the text of themes with unsaved changes is then written to
366 # recovery files, which are listed on STDERR.
367 method run () {
368 ( $quitting, $signalled ) = ( 0, 0 );
369 $self->_watch_signals;
370 try {
371 $ui->run;
372 }
373 catch ($error) {
374 $self->_stop_watching;
375 die $error;
376 }
377 $self->_stop_watching;
378 @recovered = $signalled && !$quitting ? $self->_recover : ();
379 return $self;
380 }
381  
382 # Term::Fabulous ends its loop (the process's IO::Async loop) on these
383 # signals; the editor notes that one came, to keep the unsaved work.
384 # The handlers the program had come back afterwards.
385 method _watch_signals () {
386 my $loop = IO::Async::Loop->new;
387 weaken( my $editor = $self );
388 my @signals = IO::Async::OS->HAVE_SIGNALS ? WATCHED_SIGNALS : (); # IO::Async watches no signals on Windows
389 %signals_before = map { $_ => $SIG{$_} } @signals;
390 @signal_watchers = map {
391 IO::Async::Signal->new( name => $_, on_receipt => sub { $editor->_signalled } )
392 } @signals;
393 $loop->add($_) foreach @signal_watchers;
394 return;
395 }
396  
397 method _signalled () {
398 $signalled = 1;
399 return;
400 }
401  
402 method recovered_files () {
403 return @recovered;
404 }
405  
406 method _stop_watching () {
407 foreach my $notifier ( grep { defined } $parse_timer, @signal_watchers ) {
408 $notifier->loop->remove($notifier) if defined $notifier->loop;
409 }
410 ( $parse_timer, @signal_watchers ) = ();
411 foreach my $name ( keys %signals_before ) {
412 $SIG{$name} = $signals_before{$name} unless defined $SIG{$name};
413 }
414 %signals_before = ();
415 return;
416 }
417  
418 method _recover () {
419 my @written;
420 foreach my $tab ( grep { $_->is_modified } @tabs ) {
421 try {
422 push @written, $tab->write_recovery($directory);
423 }
424 catch ($error) {
425 warn "Term::Fabulous::ThemeEditor: could not keep the unsaved text of " . $tab->title . ": $error";
426 }
427 }
428 warn "Term::Fabulous::ThemeEditor: the editor was stopped with unsaved changes; they were written to:\n" . join( '', map { " $_\n" } @written ) if @written;
429 return @written;
430 }
431  
432 # ---------------------------------------------------------------------
433 # Tabs
434 # ---------------------------------------------------------------------
435  
436 method tabs () {
437 return @tabs;
438 }
439  
440 method active_tab () {
441 return defined $active ? $tabs[$active] : undef;
442 }
443  
444 method _tab_summaries () {
445 return map { { title => _title_of($_), modified => $_->is_modified, error => !$_->document->is_valid } } @tabs;
446 }
447  
448 method _add_tab ($tab) {
449 weaken( my $weak_tab = $tab ); # the tab holds its area, which keeps the listener
450 $tab->area->on( Change => sub ( $self, $event ) { $self->_text_changed($weak_tab); return Clay::UI::Enum::Result->CONTINUE }, owner => $self );
451 push @tabs, $tab;
452 $self->select_tab($#tabs);
453 return $tab;
454 }
455  
456 # Opens a theme file in a new tab, or shows the tab it is open in. A
457 # file that does not exist yet becomes a new theme that is saved there.
458 method open_file ($path) {
459 die "Term::Fabulous::ThemeEditor: open_file needs a file name, got " . describe($path) unless defined $path && !ref $path && length $path;
460 die "Term::Fabulous::ThemeEditor: open_file needs the path as the file system has it (bytes), got a character string" if $path =~ /[^\x00-\xff]/;
461 my $full = abs_path($path) // $path;
462 my $existing = first { defined $tabs[$_]->path && ( abs_path( $tabs[$_]->path ) // $tabs[$_]->path ) eq $full } 0 .. $#tabs;
463 return $self->select_tab($existing) && $tabs[$existing] if defined $existing;
464 if ( !-e $path ) {
465 my ($name) = _decoded( basename($path) ) =~ /\A(.*?)(?:\.kdl)?\z/i;
466 my $tab = $self->_add_tab( Term::Fabulous::ThemeEditor::Tab->new( path => $path, text => _template( $name, 'dark' ), modified => 1 ) );
467 $status->message( $self->_shown_path($path) . ' does not exist yet; it is made when you save.' );
468 return $tab;
469 }
470 my $document = Term::Fabulous::Theme::Document->read_file($path);
471 my $tab = $self->_add_tab( Term::Fabulous::ThemeEditor::Tab->new( path => $path, text => $document->text, mode => $document->is_valid ? 'form' : 'text' ) );
472 $self->_show_active;
473 my @errors = $tab->document->errors;
474 my $shown = $self->_shown_path($path);
475 $status->message( @errors ? sprintf( 'Opened %s; it has %d error%s, shown in text mode.', $shown, scalar @errors, @errors == 1 ? '' : 's' ) : "Opened $shown.", @errors ? 'warning' : 'info' );
476 return $tab;
477 }
478  
479 # A path as the editor shows it: relative to the start directory when it
480 # is inside it, and decoded.
481 method _shown_path ($path) {
482 my $full = abs_path($path) // File::Spec->rel2abs($path);
483 my $base = abs_path($directory) // $directory;
484 return _decoded( index( $full, "$base/" ) == 0 ? substr( $full, length($base) + 1 ) : $full );
485 }
486  
487 # Paths are bytes, as the file system has them; the editor shows them
488 # as UTF-8 text, with a byte that is no UTF-8 as \xHH.
489 sub _decoded ($bytes) {
490 return decode( 'UTF-8', $bytes, Encode::FB_PERLQQ | Encode::LEAVE_SRC );
491 }
492  
493 # The title of a tab as the editor shows it: its file's name decoded.
494 sub _title_of ($tab) {
495 return _decoded( $tab->title );
496 }
497  
498 sub _template ( $name, $base ) {
499 my $quoted = $name =~ s/(["\\])/\\$1/gr;
500 return <<~"KDL";
501 // A theme for Term::Fabulous; see Term::Fabulous::Theme. A program
502 // loads it with Term::Fabulous::Theme->from_file.
503  
504 theme "$quoted" extends="$base"
505 KDL
506 }
507  
508 # A new theme in a new tab.
509 method new_theme (%parameters) {
510 my $number = ++$untitled_count;
511 my $name = $parameters{name} // "untitled-$number";
512 my $base = $parameters{extends} // 'dark';
513 die "Term::Fabulous::ThemeEditor: extends must be the name of a built-in theme, got " . describe($base) unless grep { $_ eq $base } Term::Fabulous::Theme::builtin_names();
514 return $self->_add_tab( Term::Fabulous::ThemeEditor::Tab->new( untitled => $number, text => _template( $name, $base ) ) );
515 }
516  
517 method select_tab ($index) {
518 return 0 unless @tabs;
519 $index %= @tabs;
520 my $previous = $self->active_tab;
521 $form->keep_state($previous) if defined $previous && ( !defined $active || $index != $active ) && $previous->mode eq 'form';
522 $self->_sync($previous) if defined $previous;
523 $active = $index;
524 $self->_show_active;
525 return 1;
526 }
527  
528 method _remove_tab ($index) {
529 my ($tab) = splice @tabs, $index, 1;
530 if ( !@tabs ) {
531 $active = undef;
532 }
533 elsif ( $active >= $index ) {
534 $active = max( 0, $active - 1 );
535 }
536 $self->_show_active;
537 $self->_focus_settings;
538 return $tab;
539 }
540  
541 # ---------------------------------------------------------------------
542 # Showing the active tab
543 # ---------------------------------------------------------------------
544  
545 # Shows the active tab in the settings pane; the focus stays in the
546 # pane when it was there.
547 method _show_active () {
548 my $tab = $self->active_tab;
549 my $focused = $ui->interaction->get_focused_widget;
550 my $had = defined $focused && $content->contains($focused);
551 $strip->active($active);
552 if ( !defined $tab ) {
553 $self->_show_content($welcome);
554 $preview_title->markup('Preview');
555 $mode_switch->disabled(1);
556 $ui->preview_theme( Term::Fabulous::Theme->builtin('dark') );
557 $self->_paint_preview_background( Term::Fabulous::Theme->builtin('dark') );
558 $gallery->show_theme( Term::Fabulous::Theme->builtin('dark') ) if defined $gallery;
559 return;
560 }
561 $mode_switch->disabled(0);
562 $mode_switch->value( $tab->mode );
563 if ( $tab->mode eq 'form' ) {
564 $self->_show_content($form);
565 }
566 else {
567 $text_box->clear_children if !$text_box->has_child( $tab->area );
568 $text_box->add_child( $tab->area, $errors_text ) unless $text_box->has_child( $tab->area );
569 $self->_show_content($text_box);
570 }
571 $self->_refresh;
572 $self->_focus_settings if $had;
573 return;
574 }
575  
576 method _show_content ($widget) {
577 return if $content->has_child($widget);
578 $content->clear_children;
579 $content->add_child($widget);
580 return;
581 }
582  
583 # Everything that follows the active tab's document: the preview, the
584 # form or the error list, the titles.
585 method _refresh () {
586 my $tab = $self->active_tab // return;
587 my $document = $tab->document;
588 my $theme = $tab->preview_theme;
589 $ui->preview_theme($theme);
590 $self->_paint_preview_background($theme);
591 $gallery->show_theme( $theme, $document->has_syntax_error ? () : $document->variants ) if defined $gallery;
592  
593 my @errors = $document->errors;
594 my $danger = _hex_of( $ui->theme->token('danger') );
595 $preview_title->markup( 'Preview: ' . _escaped( $theme->name // _title_of($tab) ) . ( $tab->is_stale ? " [bold $danger](stale: the text has errors)[/]" : '' ) );
596 $settings_title->markup( 'Settings of ' . _escaped( _title_of($tab) ) );
597  
598 if ( $tab->mode eq 'form' ) {
599 my $shown = $tab->is_stale ? $self->_last_valid_document($tab) : $document;
600 $form->show( $tab, $shown, @{ $tab->form_state->{new_variants} // [] } );
601 $form->read_only( $tab->is_stale );
602 @errors
603 ? $form->show_banner(
604 sprintf(
605 "[bold]The text has %d error%s[/]; the form shows its last valid state and takes no changes. F8 shows the first error in text mode.\n", scalar @errors, @errors == 1 ? '' : 's'
606 )
607 )
608 : $form->hide_banner;
609 $form->explain_current;
610 }
611 else {
612 $errors_text->markup( join "\n", map { "[bold $danger]Line $_->{line}:[/] " . _escaped( $_->{message} ) } @errors[ 0 .. min( 2, $#errors ) ] );
613 $errors_text->markup( $errors_text->text . "\n... and " . ( @errors - 3 ) . ' more' ) if @errors > 3;
614 }
615 return;
616 }
617  
618 # The preview lies on the edited theme's screen background (none when
619 # the token has alpha 0: the terminal's own background shows).
620 method _paint_preview_background ($theme) {
621 my $background = $theme->token('background');
622 $background->[3] > 0 ? $preview_root->background_color($background) : $preview_root->reset_look('background_color');
623 return;
624 }
625  
626 sub _hex_of ($rgba) {
627 return sprintf( '#%02x%02x%02x', @{$rgba}[ 0 .. 2 ] );
628 }
629  
630 sub _escaped ($text) {
631 return $text =~ s/\[/\\[/gr;
632 }
633  
634 field %last_valid; # tab => the last document without errors
635  
636 method _last_valid_document ($tab) {
637 return $last_valid{ refaddr $tab } // Term::Fabulous::Theme::Document->parse('');
638 }
639  
640 # ---------------------------------------------------------------------
641 # The text changes
642 # ---------------------------------------------------------------------
643  
644 # Text typed in text mode is parsed once it rests for a moment; without
645 # a running loop (in tests) at once.
646 method _text_changed ($tab) {
647 return unless defined $tab;
648 my $loop = $ui->loop;
649 return $self->_sync($tab) unless defined $loop;
650 if ( !defined $parse_timer ) {
651 weaken( my $editor = $self );
652 $parse_timer = IO::Async::Timer::Countdown->new( delay => PARSE_DELAY, on_expire => sub { $editor->_sync( $editor->active_tab ) } );
653 $loop->add($parse_timer);
654 }
655 $parse_timer->is_running ? $parse_timer->reset : $parse_timer->start;
656 return;
657 }
658  
659 # Parses a tab's text when it changed and shows the result.
660 method _sync ($tab) {
661 return unless defined $tab;
662 my $changed = $tab->sync;
663 $last_valid{ refaddr $tab } = $tab->document if $tab->document->is_valid;
664 $self->_refresh if $changed && defined $self->active_tab && refaddr $tab == refaddr $self->active_tab;
665 return $changed;
666 }
667  
668 # A change the editor makes (from the form, a paste, a reset): one undo
669 # step, shown at once.
670 method _change ( $what, $change ) {
671 my $tab = $self->active_tab // return 0;
672 my $changed;
673 try {
674 $changed = $tab->change_document($change);
675 }
676 catch ($error) {
677 $error =~ s/\ATerm::Fabulous::Theme::Document: //;
678 $error =~ s/ at \S+ line \d+\.?\n?\z//;
679 $error =~ s/ \(known: [^)]*\)//g; # the status line has one row
680 $error =~ s/\s+\z//;
681 $status->message( "Not changed: $error", 'danger' );
682 return 0;
683 }
684 $last_valid{ refaddr $tab } = $tab->document if $tab->document->is_valid;
685 $self->_refresh;
686 $status->message( $changed ? $what : 'Nothing changed.', $changed ? 'success' : 'info' );
687 return $changed;
688 }
689  
690 # ---------------------------------------------------------------------
691 # Modes, panes and focus
692 # ---------------------------------------------------------------------
693  
694 method set_mode ($mode) {
695 my $tab = $self->active_tab // return;
696 return if $tab->mode eq $mode;
697 $self->_sync($tab);
698 my $place = $tab->mode eq 'form' ? $self->_line_of_cursor_row : $self->_key_on_text_line;
699 $form->keep_state($tab) if $tab->mode eq 'form';
700 $tab->mode($mode);
701 $self->_show_active;
702 $self->_focus_settings;
703 $mode eq 'text' ? $self->_put_text_cursor($place) : $self->_put_form_cursor($place);
704 $status->message( $mode eq 'form' ? 'Form mode: Enter edits a setting, Delete resets it.' : 'Text mode: the file as it is; the preview follows your typing.' );
705 return;
706 }
707  
708 # The line of the text that holds the setting under the form's cursor
709 # (for a section, its first setting the theme sets), or undef.
710 method _line_of_cursor_row () {
711 my $tab = $self->active_tab // return undef;
712 my $row = $form->current // return undef;
713 my @keys = defined $row->{key} ? ( $row->{key} ) : $form->keys_in( $row->{id} );
714 my ($line) = sort { $a <=> $b } grep { defined } map { $tab->document->line_of($_) } @keys;
715 return $line;
716 }
717  
718 # The setting on the line of the text cursor (or the nearest one above
719 # it), or undef.
720 method _key_on_text_line () {
721 my $tab = $self->active_tab // return undef;
722 my ($row) = $tab->area->editor->cursor;
723 my $document = $tab->document;
724 my ($key) = sort { $document->line_of($b) <=> $document->line_of($a) } grep { $document->line_of($_) <= $row + 1 } $document->setting_keys;
725 return $key;
726 }
727  
728 method _put_text_cursor ($line) {
729 my $tab = $self->active_tab // return;
730 return unless defined $line;
731 my $editor = $tab->area->editor;
732 $editor->move_to( min( $line - 1, $editor->line_count - 1 ), 0 );
733 $tab->area->mark_changed;
734 return;
735 }
736  
737 method _put_form_cursor ($key) {
738 return unless defined $key && $form->has_row($key);
739 $form->go_to($key);
740 return;
741 }
742  
743 method _toggle_mode () {
744 my $tab = $self->active_tab // return;
745 $self->set_mode( $tab->mode eq 'form' ? 'text' : 'form' );
746 return;
747 }
748  
749 method _focus_settings () {
750 my $tab = $self->active_tab;
751 my $target = !defined $tab ? undef : $tab->mode eq 'form' ? $form->list : $tab->area;
752 $ui->interaction->set_focused_widget($target) if !defined $target || $ui->interaction->can_take_focus($target);
753 return;
754 }
755  
756 method _switch_pane () {
757 my $focused = $ui->interaction->get_focused_widget;
758 if ( defined $focused && $preview_root->contains($focused) ) {
759 $self->_focus_settings;
760 return;
761 }
762 my ($first) = $ui->interaction->focusables( within => $preview_root );
763 $ui->interaction->set_focused_widget($first) if defined $first;
764 $status->message('In the preview: Tab moves between the widgets, PageUp and PageDown scroll, F6 goes back.');
765 return;
766 }
767  
768 # The pane with the focus gets its border in the accent color.
769 method _focus_moved () {
770 my $focused = $ui->interaction->get_focused_widget;
771 foreach my $pane ( $preview_pane, $settings_pane ) {
772 my $has = defined $focused && $pane->contains($focused);
773 $has ? $pane->border_color( $pane->family_look( input => 'accent' ) ) : $pane->reset_look('border_color');
774 }
775 return;
776 }
777  
778 # The form's cursor moved: the preview shows the family of the row.
779 method _cursor_moved ($id) {
780 return unless defined $gallery && defined $id;
781 my $info = $form->section_info( $form->section_of($id) ) // return;
782 my $kind = $info->{kind};
783 my $target
784 = $kind eq 'variant' ? 'variants'
785 : $kind eq 'palette' || $kind eq 'theme' ? 'palette'
786 : $gallery->section_of_family( $info->{family} );
787 $gallery->show_section($target) if defined $target;
788 return;
789 }
790  
791 method _toggle_only_set () {
792 my $box = $form->only_set;
793 $box->checked( $box->checked ? 0 : 1 );
794 $box->fire_change( $box->checked );
795 return;
796 }
797  
798 # ---------------------------------------------------------------------
799 # Keys
800 # ---------------------------------------------------------------------
801  
802 method _key ($event) {
803 my $name = $event->key_name // return 0;
804 return 1 if $menu->handle_shortcut($event);
805 if ( my ($number) = $name =~ /\AAlt\+([1-9])\z/ ) {
806 $self->select_tab( $number - 1 ) if $number <= @tabs;
807 return 1;
808 }
809 if ( $name eq 'Escape' ) {
810 return $self->_escape;
811 }
812 my $command = $commands->command_for_key($name) // return 0;
813 my $id = $command->id;
814 return 0 if ( $id eq 'edit' || $id eq 'reset' ) && !$self->_form_has_focus;
815 $command->run or $self->_not_now($id);
816 return 1;
817 }
818  
819 method _not_now ($id) {
820 my %why = (
821 save => 'No theme is open.',
822 paste_keys => 'Pasting at the copied keys works in form mode, on a theme without errors.',
823 edit => 'Editing works in form mode, on a theme without errors.',
824 reset => 'Resetting works in form mode, on a theme without errors.',
825 undo => 'Nothing to undo.',
826 redo => 'Nothing to redo.',
827 revert => 'The theme has no file to revert to.',
828 find_next => 'Find something first (Ctrl+F).',
829 next_error => 'The theme has no errors.',
830 );
831 $status->message( $why{$id} // $commands->command($id)->plain_label . ' is not available now.', 'warning' );
832 return;
833 }
834  
835 method _form_has_focus () {
836 my $focused = $ui->interaction->get_focused_widget // return 0;
837 return $form->list->contains($focused) ? 1 : 0;
838 }
839  
840 # Escape in the search field empties it and goes back to the list.
841 method _escape () {
842 my $focused = $ui->interaction->get_focused_widget // return 0;
843 my $search = $form->search;
844 return 0 unless refaddr $focused == refaddr $search;
845 if ( length $search->value ) {
846 $search->value('');
847 $form->list->search('');
848 }
849 $ui->interaction->set_focused_widget( $form->list );
850 return 1;
851 }
852  
853 # ---------------------------------------------------------------------
854 # Editing settings
855 # ---------------------------------------------------------------------
856  
857 method _writable_tab () {
858 my $tab = $self->active_tab // return undef;
859 $self->_sync($tab);
860 if ( !$tab->document->is_valid ) {
861 $status->message( 'The text has errors; fix them first (F8 shows the first one).', 'warning' );
862 return undef;
863 }
864 return $tab;
865 }
866  
867 method _edit_current () {
868 my $key = $form->current_key // return;
869 $self->_edit_key($key);
870 return;
871 }
872  
873 # Opens the dialog that edits a setting.
874 method _edit_key ($key) {
875 my $tab = $self->_writable_tab // return;
876 my $document = $tab->document;
877 my $effective = $document->effective_setting($key);
878 my $fallback = $document->without_setting($key)->effective_setting($key);
879 my $palette = $tab->preview_theme->palette;
880 my $dialog = Term::Fabulous::ThemeEditor::ValueDialog->new(
881 key => $key,
882 current => $effective->{spec},
883 is_set => $effective->{origin} eq 'set' ? 1 : 0,
884 default => $fallback->{spec},
885 palette => $palette,
886 list_rows => $self->_list_rows(19),
887 );
888 $dialog->on( Change => sub ( $self, $event ) { $self->_preview_value( $key, $event->value ); return }, owner => $self );
889 $dialog->on( Answer => sub ( $self, $event ) { $self->_value_answered( $key, $event ); return }, owner => $self );
890 $dialog->open($ui);
891 $status->message('Choose a value: the preview shows it. Enter applies, Escape leaves the theme as it was.');
892 return $dialog;
893 }
894  
895 # Apply writes the value, Reset removes the setting; anything else
896 # leaves the theme as it was, and the preview shows it again.
897 method _value_answered ( $key, $answer ) {
898 my $button = $answer->button;
899 return $self->set_setting( $key, $answer->value('value') ) if $button eq 'apply';
900 return $self->reset_setting($key) if $button eq 'reset';
901 return $self->_preview_value( $key, undef );
902 }
903  
904 # Shows a value in the preview before it is applied (undef: the theme
905 # as it is).
906 method _preview_value ( $key, $value ) {
907 my $tab = $self->active_tab // return;
908 my $theme = $tab->preview_theme;
909 if ( defined $value ) {
910 try {
911 $theme = $tab->document->with_setting( $key, $value )->theme // $theme;
912 }
913 catch ($error) {
914  
915 # a value the key cannot take: the preview stays
916 }
917 }
918 $ui->preview_theme($theme);
919 return;
920 }
921  
922 method set_setting ( $key, $value ) {
923 return 0 unless $self->_writable_tab;
924 my $changed = $self->_change( "Set $key to $value.", sub ($document) { $document->with_setting( $key, $value ) } );
925 $self->_forget_new_variant($key) if $changed;
926 return $changed ? 1 : 0;
927 }
928  
929 method reset_setting ($key) {
930 my $tab = $self->_writable_tab // return 0;
931 if ( !defined $tab->document->setting($key) ) {
932 $status->message( "$key is not set; it follows " . _origin_words( $tab->document->effective_setting($key) ) . ' already.' );
933 return 0;
934 }
935 my $changed = $self->_change(
936 "Reset $key; it follows " . _origin_words( $tab->document->without_setting($key)->effective_setting($key) ) . ' now.',
937 sub ($document) { $document->without_setting($key) }
938 );
939 return $changed ? 1 : 0;
940 }
941  
942 # Where a value comes from, and the value; a token is named as a token
943 # (a token may be called like a state: disabled).
944 sub _origin_words ($effective) {
945 my %words = ( default => 'the default', normal => 'the normal state', family => 'its family', dark => 'the dark theme', light => 'the light theme', set => 'the theme' );
946 my $spec = $effective->{spec};
947 my $value = !defined $spec ? '' : ( grep { $_ eq $spec } Term::Fabulous::Theme::tokens() ) ? qq{ (the token "$spec")} : " ($spec)";
948 return ( $words{ $effective->{origin} } // $effective->{origin} ) . $value;
949 }
950  
951 method _reset_current () {
952 my $row = $form->current // return;
953 return $self->reset_setting( $row->{key} ) if defined $row->{key};
954 return $self->_reset_section;
955 }
956  
957 # Resets every setting of the section under the cursor, after asking.
958 method _reset_section () {
959 my $tab = $self->_writable_tab // return;
960 my $row = $form->current // return;
961 my $section = $form->section_of( $row->{id} ) // return;
962 my @keys = grep { defined $tab->document->setting($_) } $form->keys_in($section);
963 my $info = $form->section_info($section);
964 my %name_of = ( theme => 'the theme node', palette => 'the palette', variant => "the variant $info->{family}\[" . ( $info->{variant} // '' ) . ']', family => "the family $info->{family}" );
965 my $name = $name_of{ $info->{kind} };
966 if ( !@keys ) {
967 $status->message("Nothing to reset: $name sets nothing.");
968 return;
969 }
970 $self->_ask(
971 title => 'Reset section',
972 message => sprintf( 'Reset the %d setting%s of %s to their defaults? Undo (Ctrl+Z) takes it back.', scalar @keys, @keys == 1 ? '' : 's', $name ),
973 buttons => [ { id => 'reset', label => 'Reset', primary => 1 }, { id => 'cancel', label => 'Cancel' } ],
974 on_done => sub ( $button, $values ) {
975 return unless $button eq 'reset';
976 $self->_change(
977 sprintf( 'Reset %d setting%s of %s.', scalar @keys, @keys == 1 ? '' : 's', $name ),
978 sub ($document) {
979 $document->with_settings( [ map { [ $_, undef ] } @keys ] );
980 }
981 );
982 },
983 );
984 return;
985 }
986  
987 method _reset_theme () {
988 my $tab = $self->_writable_tab // return;
989 my @keys = grep { !/\Atheme\./ } $tab->document->setting_keys;
990 if ( !@keys ) {
991 $status->message('The theme sets nothing besides its name and base.');
992 return;
993 }
994 $self->_ask(
995 title => 'Reset whole theme',
996 message => sprintf( 'Remove all %d settings, so the theme is its base theme (%s) again? Its name and base stay. Undo (Ctrl+Z) takes it back.', scalar @keys, $tab->document->extends ),
997 buttons => [ { id => 'reset', label => 'Reset', primary => 1 }, { id => 'cancel', label => 'Cancel' } ],
998 on_done => sub ( $button, $values ) {
999 return unless $button eq 'reset';
1000 $self->_change(
1001 sprintf( 'Removed %d settings.', scalar @keys ),
1002 sub ($document) {
1003 $document->with_settings( [ map { [ $_, undef ] } @keys ] );
1004 }
1005 );
1006 },
1007 );
1008 return;
1009 }
1010  
1011 # ---------------------------------------------------------------------
1012 # Variants
1013 # ---------------------------------------------------------------------
1014  
1015 method _current_variant () {
1016 my $row = $form->current // return undef;
1017 my $info = $form->section_info( $form->section_of( $row->{id} ) ) // return undef;
1018 return undef unless $info->{kind} eq 'variant';
1019 return [ @{$info}{qw(family variant)} ];
1020 }
1021  
1022 method _ask_add_variant () {
1023 my $tab = $self->_writable_tab // return;
1024 my $row = $form->current;
1025 my $info = defined $row ? $form->section_info( $form->section_of( $row->{id} ) ) : undef;
1026 my $family = defined $info ? $info->{family} : undef;
1027 $self->_ask(
1028 title => 'Add variant',
1029 message => 'A variant changes some settings of a family for the widgets whose [bold]classes[/] name it, such as a button made with classes => [\'primary\'].',
1030 fields => [
1031 {
1032 name => 'family', label => 'Family',
1033 input => Term::Fabulous::Widget::Dropdown->new( options => [ Term::Fabulous::Theme::families() ], value => $family // 'button', max_visible_options => 10 )
1034 },
1035 {
1036 name => 'name',
1037 label => 'Name',
1038 input => _text_input(
1039 placeholder => 'primary',
1040 required => 1,
1041 required_message => 'A variant needs a name.',
1042 validator => sub ($value) { $value =~ /\A[A-Za-z0-9_-]+\z/ ? undef : 'A name is a word: letters, digits, _ and -.' },
1043 ),
1044 },
1045 ],
1046 check => sub ($values) {
1047 return 'The theme has this variant already.' if grep { $_->[0] eq $values->{family} && $_->[1] eq $values->{name} } $tab->document->variants;
1048 return undef;
1049 },
1050 buttons => [ { id => 'add', label => 'Add', primary => 1 }, { id => 'cancel', label => 'Cancel' } ],
1051 on_done => sub ( $button, $values ) {
1052 return unless $button eq 'add';
1053 push @{ $tab->form_state->{new_variants} }, [ $values->{family}, $values->{name} ];
1054 $self->_refresh;
1055 my $id = Term::Fabulous::ThemeEditor::Form::section_id( 'variant', $values->{family}, $values->{name} );
1056 $form->go_to($id);
1057 $status->message("Added the variant $values->{family}\[$values->{name}]. Set some of its settings; until then the file does not hold it.");
1058 },
1059 );
1060 return;
1061 }
1062  
1063 method _forget_new_variant ($key) {
1064 my $tab = $self->active_tab // return;
1065 my $parsed = Term::Fabulous::Theme::Document::parse_key($key);
1066 return unless defined $parsed->{variant};
1067 my $pending = $tab->form_state->{new_variants} // return;
1068 @$pending = grep { !( $_->[0] eq $parsed->{family} && $_->[1] eq $parsed->{variant} ) } @$pending;
1069 return;
1070 }
1071  
1072 method _remove_variant () {
1073 my $variant = $self->_current_variant // return;
1074 my ( $family, $name ) = @$variant;
1075 my $tab = $self->_writable_tab // return;
1076 my $pending = $tab->form_state->{new_variants} // [];
1077 if ( grep { $_->[0] eq $family && $_->[1] eq $name } @$pending ) {
1078 @$pending = grep { !( $_->[0] eq $family && $_->[1] eq $name ) } @$pending;
1079 $self->_refresh;
1080 $status->message("Removed the variant $family\[$name].");
1081 return;
1082 }
1083 $self->_change( "Removed the variant $family\[$name].", sub ($document) { $document->without_variant( $family, $name ) } );
1084 return;
1085 }
1086  
1087 # ---------------------------------------------------------------------
1088 # Undo, clipboard
1089 # ---------------------------------------------------------------------
1090  
1091 method _undo () {
1092 return $self->_history('undo');
1093 }
1094  
1095 method _redo () {
1096 return $self->_history('redo');
1097 }
1098  
1099 # Undo and redo; in form mode the cursor goes to the first setting that
1100 # changed.
1101 method _history ($which) {
1102 my $tab = $self->active_tab // return 0;
1103 $self->_sync($tab);
1104 my $before = $tab->document;
1105 return 0 unless $tab->$which;
1106 $last_valid{ refaddr $tab } = $tab->document if $tab->document->is_valid;
1107 $self->_refresh;
1108 my @changed = _changed_keys( $before, $tab->document );
1109 $form->go_to( $changed[0] ) if @changed && $tab->mode eq 'form' && $form->has_row( $changed[0] );
1110 $status->message( ( $which eq 'undo' ? 'Undone' : 'Redone' ) . ( @changed ? ': ' . join( ', ', @changed[ 0 .. min( 2, $#changed ) ] ) . ( @changed > 3 ? ', ...' : '' ) : '' ) . '.' );
1111 return 1;
1112 }
1113  
1114 sub _changed_keys ( $before, $after ) {
1115 my %keys = map { $_ => 1 } $before->setting_keys, $after->setting_keys;
1116 return grep { ( $before->setting($_) // "\x{0}" ) ne ( $after->setting($_) // "\x{0}" ) }
1117 sort { ( $after->line_of($a) // $before->line_of($a) // 0 ) <=> ( $after->line_of($b) // $before->line_of($b) // 0 ) } keys %keys;
1118 }
1119  
1120 method _in_text_mode () {
1121 my $tab = $self->active_tab // return 0;
1122 return $tab->mode eq 'text' ? 1 : 0;
1123 }
1124  
1125 # In text mode, the clipboard commands work on the text; in form mode
1126 # on settings, as KDL that the text mode can paste too.
1127 method _copy () {
1128 my $tab = $self->active_tab // return;
1129 if ( $self->_in_text_mode ) {
1130 my $editor = $tab->area->editor;
1131 if ( !$editor->has_selection ) {
1132 $status->message( 'Select some text to copy.', 'warning' );
1133 return;
1134 }
1135 $editor->_copy;
1136 $status->message('Copied the selection.');
1137 return;
1138 }
1139 my @keys = $self->_keys_to_copy;
1140 return unless @keys;
1141 my $document = $self->_shown_document($tab);
1142 my $fragment
1143 = Term::Fabulous::Theme::Document->parse('')->with_settings( [ map { [ $_, $document->effective_setting($_)->{spec} ] } grep { defined $document->effective_setting($_)->{spec} } @keys ] );
1144 Term::Fabulous::Editor->clipboard( $fragment->text );
1145 $status->message( @keys == 1 ? "Copied $keys[0] (" . $document->effective_setting( $keys[0] )->{spec} . ').' : sprintf( 'Copied %d settings.', scalar @keys ), 'success' );
1146 return @keys;
1147 }
1148  
1149 method _shown_document ($tab) {
1150 return $tab->is_stale ? $self->_last_valid_document($tab) : $tab->document;
1151 }
1152  
1153 # The keys a copy takes: the setting under the cursor, or the settings
1154 # a section sets.
1155 method _keys_to_copy () {
1156 my $row = $form->current;
1157 if ( !defined $row ) {
1158 $status->message( 'Put the cursor on a setting or a section to copy.', 'warning' );
1159 return;
1160 }
1161 return ( $row->{key} ) if defined $row->{key};
1162 my $document = $self->_shown_document( $self->active_tab );
1163 my @keys = grep { defined $document->setting($_) } $form->keys_in( $row->{id} );
1164 $status->message( 'This section sets nothing to copy.', 'warning' ) unless @keys;
1165 return @keys;
1166 }
1167  
1168 method _cut () {
1169 my $tab = $self->active_tab // return;
1170 if ( $self->_in_text_mode ) {
1171 if ( !$tab->area->editor->has_selection ) {
1172 $status->message( 'Select some text to cut.', 'warning' );
1173 return;
1174 }
1175 $tab->area->apply_edit( $tab->area->editor->cut );
1176 $self->_sync($tab);
1177 return;
1178 }
1179 return unless $self->_writable_tab;
1180 my @keys = $self->_copy or return;
1181 my @set = grep { defined $tab->document->setting($_) } @keys;
1182 $self->_change(
1183 @keys == 1 ? "Cut $keys[0]." : sprintf( 'Cut %d settings.', scalar @set ),
1184 sub ($document) {
1185 $document->with_settings( [ map { [ $_, undef ] } @set ] );
1186 }
1187 ) if @set;
1188 return;
1189 }
1190  
1191 # Pastes the clipboard: in text mode as text; in form mode one copied
1192 # value onto the setting under the cursor, or copied settings at their
1193 # own keys (always with at_keys).
1194 method _paste (%options) {
1195 my $tab = $self->active_tab // return;
1196 my $clipboard = Term::Fabulous::Editor->clipboard;
1197 if ( $self->_in_text_mode ) {
1198 $tab->area->apply_edit( $tab->area->editor->paste );
1199 $self->_sync($tab);
1200 return;
1201 }
1202 return unless $self->_writable_tab;
1203 my @entries = _settings_in($clipboard);
1204 my $target = $form->current_key;
1205 my ($word) = $clipboard =~ /\A\s*(\S+)\s*\z/;
1206 my $value = @entries == 1 ? $entries[0][1] : @entries ? undef : $word;
1207 return $self->set_setting( $target, $value ) if !$options{at_keys} && defined $target && defined $value;
1208 if ( !@entries ) {
1209 $status->message( 'The clipboard holds no theme settings. Copy a setting or a section first (Ctrl+C).', 'warning' );
1210 return;
1211 }
1212 $self->_change(
1213 sprintf( 'Pasted %d setting%s at %s.', scalar @entries, @entries == 1 ? '' : 's', @entries == 1 ? $entries[0][0] : 'their keys' ),
1214 sub ($document) { $document->with_settings( \@entries ) }
1215 );
1216 $self->_forget_new_variant( $_->[0] ) foreach @entries;
1217 return;
1218 }
1219  
1220 # The [ key, value ] settings a text holds when it is a theme fragment.
1221 sub _settings_in ($text) {
1222 return () unless length $text;
1223 my $document = Term::Fabulous::Theme::Document->parse($text);
1224 return () unless $document->is_valid;
1225 return map { [ $_, $document->setting($_) ] } $document->setting_keys;
1226 }
1227  
1228 # ---------------------------------------------------------------------
1229 # Finding
1230 # ---------------------------------------------------------------------
1231  
1232 # In form mode, the search field; in text mode, a word to find.
1233 method _find () {
1234 my $tab = $self->active_tab // return;
1235 if ( $tab->mode eq 'form' ) {
1236 $ui->interaction->set_focused_widget( $form->search );
1237 $status->message('Type to filter the settings; Enter or Down goes to them, Escape empties the field.');
1238 return;
1239 }
1240 $self->_ask(
1241 title => 'Find',
1242 fields => [ { name => 'text', label => 'Find', input => _text_input( value => $find_text ) } ],
1243 buttons => [ { id => 'find', label => 'Find', primary => 1 }, { id => 'cancel', label => 'Cancel' } ],
1244 on_done => sub ( $button, $values ) {
1245 return unless $button eq 'find' && length $values->{text};
1246 $find_text = $values->{text};
1247 $self->_find_next;
1248 },
1249 );
1250 return;
1251 }
1252  
1253 method _find_next () {
1254 my $tab = $self->active_tab // return;
1255 return $self->_find unless $tab->mode eq 'text';
1256 my $editor = $tab->area->editor;
1257 my @lines = $editor->lines;
1258 my ( $row, $offset ) = $editor->has_selection ? ( $editor->selection )[ 2, 3 ] : $editor->cursor;
1259 my $needle = fc $find_text;
1260 foreach my $step ( 0 .. scalar @lines ) {
1261 my $index = ( $row + $step ) % @lines;
1262 my $from = $step == 0 ? $offset : 0;
1263 my $at = index( fc $lines[$index], $needle, $from );
1264 next if $at < 0;
1265 $editor->set_selection( $index, $at, $index, $at + length $find_text );
1266 $tab->area->mark_changed;
1267 $status->message( "Found \"$find_text\" on line " . ( $index + 1 ) . '. F3 finds the next one.' );
1268 $ui->interaction->set_focused_widget( $tab->area );
1269 return;
1270 }
1271 $status->message( "\"$find_text\" is not in the text.", 'warning' );
1272 return;
1273 }
1274  
1275 # Shows the first error after the cursor in text mode.
1276 method _next_error () {
1277 my $tab = $self->active_tab // return;
1278 $self->_sync($tab);
1279 my @errors = $tab->document->errors or return;
1280 $self->set_mode('text') unless $tab->mode eq 'text';
1281 my $editor = $tab->area->editor;
1282 my ($row) = $editor->cursor;
1283 my $error = ( first { $_->{line} - 1 > $row } @errors ) // $errors[0];
1284 my $line = min( $error->{line} - 1, $editor->line_count - 1 );
1285 $editor->move_to( $line, 0 );
1286 $editor->move_line_end(1);
1287 $tab->area->mark_changed;
1288 $ui->interaction->set_focused_widget( $tab->area );
1289 $status->message( "Line $error->{line}: $error->{message}", 'danger' );
1290 return;
1291 }
1292  
1293 # ---------------------------------------------------------------------
1294 # Files
1295 # ---------------------------------------------------------------------
1296  
1297 # How many rows a list in a dialog gets: what the screen has left
1298 # besides the dialog's other rows, between 4 and 10.
1299 method _list_rows ($other_rows) {
1300 return max( 4, min( 10, $ui->height - $other_rows ) );
1301 }
1302  
1303 # Opens a prompt; on_done gets the id of the button that answered it
1304 # and the values of its fields.
1305 method _ask (%parameters) {
1306 my $on_done = delete $parameters{on_done};
1307 my $prompt = Term::Fabulous::Widget::Prompt->new(%parameters);
1308 $prompt->on( Answer => sub ($event) { $on_done->( $event->button, $event->values ) if defined $on_done; return } );
1309 $prompt->open($ui);
1310 return $prompt;
1311 }
1312  
1313 # A text field that grows to the width of the prompt, its text selected
1314 # so typing replaces it.
1315 sub _text_input (%parameters) {
1316 my $input = Term::Fabulous::Widget::TextField->new( %parameters, layout => { sizing => { width => sizing_grow() } } );
1317 $input->editor->select_all;
1318 return $input;
1319 }
1320  
1321 method _tell ( $title, $message ) {
1322 return $self->_ask( title => $title, message => _escaped($message) );
1323 }
1324  
1325 method _ask_new_theme () {
1326 weaken( my $editor = $self );
1327 my $number = $untitled_count + 1;
1328 $self->_ask(
1329 title => 'New theme',
1330 message => 'A theme starts from one of the built-in themes and changes what you set.',
1331 fields => [
1332 { name => 'name', label => 'Name', input => _text_input( value => "untitled-$number", required => 1, required_message => 'A theme needs a name.' ) },
1333 { name => 'base', label => 'Based on', input => Term::Fabulous::Widget::SegmentedControl->new( options => [ Term::Fabulous::Theme::builtin_names() ], value => 'dark' ) },
1334 ],
1335 buttons => [ { id => 'create', label => 'Create', primary => 1 }, { id => 'cancel', label => 'Cancel' } ],
1336 on_done => sub ( $button, $values ) {
1337 return unless $button eq 'create';
1338 $editor->new_theme( name => $values->{name}, extends => $values->{base} );
1339 $editor->_focus_settings;
1340 $editor->status->message("Made the theme $values->{name}, based on $values->{base}.");
1341 },
1342 );
1343 return;
1344 }
1345  
1346 method _ask_open () {
1347 my $tab = $self->active_tab;
1348 my $start = defined $tab && defined $tab->path ? dirname( abs_path( $tab->path ) // $tab->path ) : $directory;
1349 my $dialog = Term::Fabulous::Widget::FileDialog->new(
1350 mode => 'open',
1351 title => 'Open a theme',
1352 filters => THEME_FILTERS,
1353 list_rows => $self->_list_rows(20),
1354 directory => -d $start ? $start : $directory,
1355 );
1356 $dialog->on(
1357 Answer => sub ( $self, $event ) {
1358 return if $event->button eq 'cancel';
1359 try {
1360 $self->open_file( $event->values->{path} );
1361 $self->_focus_settings;
1362 }
1363 catch ($error) {
1364 $error =~ s/\ATerm::Fabulous::Theme::Document: //;
1365 $self->_tell( 'Cannot open the file', $error );
1366 }
1367 return;
1368 },
1369 owner => $self
1370 );
1371 $dialog->open($ui);
1372 return;
1373 }
1374  
1375 # Saves the active tab: to its file, or (untitled) where the user says.
1376 # A theme with errors and a file changed on the disk are saved after a
1377 # question. $then runs after a successful save.
1378 method _save ( $tab = $self->active_tab, $then = undef ) {
1379 return unless defined $tab;
1380 $self->_sync($tab);
1381 return $self->_save_as( $tab, $then ) unless defined $tab->path;
1382 my @steps = (
1383 sub ($next) {
1384 my @errors = $tab->document->errors;
1385 return $next->() unless @errors;
1386 $self->_ask(
1387 title => 'The theme has errors',
1388 message => sprintf(
1389 "%s has %d error%s; the first is on line %d: %s\n\nA program cannot load the file until they are fixed. Save it anyway?", _title_of($tab), scalar @errors,
1390 @errors == 1 ? '' : 's',
1391 $errors[0]{line}, _escaped( $errors[0]{message} )
1392 ),
1393 buttons => [ { id => 'save', label => 'Save anyway', primary => 1 }, { id => 'cancel', label => 'Cancel' } ],
1394 on_done => sub ( $button, $values ) { $next->() if $button eq 'save' },
1395 );
1396 },
1397 sub ($next) {
1398 return $next->() unless $tab->changed_on_disk;
1399 $self->_ask(
1400 title => 'The file changed',
1401 message => _escaped( _decoded( $tab->path ) ) . ' was changed by another program since it was opened or saved. Overwrite it with the theme from the editor?',
1402 buttons => [ { id => 'save', label => 'Overwrite', primary => 1 }, { id => 'cancel', label => 'Cancel' } ],
1403 on_done => sub ( $button, $values ) { $next->() if $button eq 'save' },
1404 );
1405 },
1406 sub ($next) {
1407 $self->_write( $tab, $tab->path ) or return;
1408 $then->() if defined $then;
1409 },
1410 );
1411 _chain(@steps);
1412 return;
1413 }
1414  
1415 # Runs steps that each get the next one to continue with.
1416 sub _chain (@steps) {
1417 my $step = shift @steps // return;
1418 $step->( sub { _chain(@steps) } );
1419 return;
1420 }
1421  
1422 method _write ( $tab, $path ) {
1423 try {
1424 $tab->save($path);
1425 }
1426 catch ($error) {
1427 $error =~ s/\ATerm::Fabulous::Theme::Document: //;
1428 $self->_tell( 'Cannot save', $error );
1429 return 0;
1430 }
1431 $status->message( 'Saved ' . $self->_shown_path( $tab->path ) . '.', 'success' );
1432 return 1;
1433 }
1434  
1435 method _save_as ( $tab = $self->active_tab, $then = undef ) {
1436 return unless defined $tab;
1437 my $start = defined $tab->path ? dirname( abs_path( $tab->path ) // $tab->path ) : $directory;
1438 my $name = defined $tab->path ? basename( $tab->path ) : encode( 'UTF-8', ( $tab->document->name // _title_of($tab) ) . '.kdl' );
1439 my $dialog = Term::Fabulous::Widget::FileDialog->new(
1440 mode => 'save',
1441 title => 'Save the theme as',
1442 filters => THEME_FILTERS,
1443 default_extension => 'kdl',
1444 current_file => defined $tab->path ? File::Spec->rel2abs( $tab->path ) : undef,
1445 list_rows => $self->_list_rows(20),
1446 directory => -d $start ? $start : $directory,
1447 name => $name,
1448 );
1449 $dialog->on(
1450 Answer => sub ( $self, $event ) {
1451 return if $event->button eq 'cancel';
1452 $self->_write( $tab, $event->values->{path} ) && $then && $then->();
1453 return;
1454 },
1455 owner => $self
1456 );
1457 $dialog->open($ui);
1458 return;
1459 }
1460  
1461 method _save_all ( $then = undef ) {
1462 my @unsaved = grep { $_->is_modified } @tabs;
1463 _chain(
1464 (
1465 map {
1466 my $tab = $_;
1467 sub ($next) { $self->_save( $tab, $next ) }
1468 } @unsaved
1469 ),
1470 sub ($next) { $then->() if defined $then }
1471 );
1472 return;
1473 }
1474  
1475 method _revert () {
1476 my $tab = $self->active_tab // return;
1477 my $go = sub {
1478 try {
1479 $tab->revert;
1480 }
1481 catch ($error) {
1482 $error =~ s/\ATerm::Fabulous::Theme::Document: //;
1483 return $self->_tell( 'Cannot revert', $error );
1484 }
1485 $self->_sync($tab);
1486 $self->_refresh;
1487 $status->message( 'Reverted to ' . $self->_shown_path( $tab->path ) . '. Undo (Ctrl+Z) takes it back.', 'success' );
1488 };
1489 return $go->() unless $tab->is_modified;
1490 $self->_ask(
1491 title => 'Revert to saved',
1492 message => 'Replace the theme in the editor with ' . _escaped( _decoded( $tab->path ) ) . ' as it is on the disk? Undo (Ctrl+Z) takes it back.',
1493 buttons => [ { id => 'revert', label => 'Revert', primary => 1 }, { id => 'cancel', label => 'Cancel' } ],
1494 on_done => sub ( $button, $values ) { $go->() if $button eq 'revert' },
1495 );
1496 return;
1497 }
1498  
1499 method _duplicate () {
1500 my $tab = $self->active_tab // return;
1501 $self->_sync($tab);
1502 my $number = ++$untitled_count;
1503 my $text = $tab->text;
1504 my $name = $tab->document->name;
1505 if ( !$tab->document->has_syntax_error ) {
1506 $text = $tab->document->with_setting( 'theme.name', ( $name // _title_of($tab) ) . '-copy' )->text;
1507 }
1508 $self->_add_tab( Term::Fabulous::ThemeEditor::Tab->new( untitled => $number, text => $text, modified => 1 ) );
1509 $self->_focus_settings;
1510 $status->message( 'Made a copy of ' . _title_of($tab) . ' as a new theme.' );
1511 return;
1512 }
1513  
1514 # Closes a tab, asking first when it has unsaved changes.
1515 method close_tab ( $index = $active ) {
1516 return unless defined $index && $tabs[$index];
1517 my $tab = $tabs[$index];
1518 $self->_sync($tab);
1519 weaken( my $editor = $self );
1520 my $close = sub {
1521 my $found = first { refaddr $tabs[$_] == refaddr $tab } 0 .. $#tabs;
1522 $editor->_remove_tab($found) if defined $found;
1523 delete $last_valid{ refaddr $tab };
1524 $status->message( 'Closed ' . _title_of($tab) . '.' );
1525 };
1526 return $close->() unless $tab->is_modified;
1527 $self->select_tab($index);
1528 $self->_ask(
1529 title => 'Unsaved changes',
1530 message => 'Save the changes to ' . _escaped( _title_of($tab) ) . ' before closing it?',
1531 buttons => [ { id => 'save', label => 'Save', primary => 1 }, { id => 'discard', label => 'Close without saving' }, { id => 'cancel', label => 'Cancel' } ],
1532 on_done => sub ( $button, $values ) {
1533 return $editor->_save( $tab, $close ) if $button eq 'save';
1534 $close->() if $button eq 'discard';
1535 },
1536 );
1537 return;
1538 }
1539  
1540 # Quits, asking first when a theme has unsaved changes.
1541 method _quit () {
1542 $self->_sync($_) foreach @tabs;
1543 my @unsaved = grep { $_->is_modified } @tabs;
1544 weaken( my $editor = $self );
1545 my $stop = sub { $quitting = 1; $ui->loop->stop if defined $ui->loop };
1546 return $stop->() unless @unsaved;
1547 $self->_ask(
1548 title => 'Unsaved changes',
1549 message => sprintf(
1550 "%d theme%s %s unsaved changes: %s.\n\nSave %s before quitting?", scalar @unsaved, @unsaved == 1 ? '' : 's', @unsaved == 1 ? 'has' : 'have',
1551 join( ', ', map { _escaped( _title_of($_) ) } @unsaved ), @unsaved == 1 ? 'it' : 'them'
1552 ),
1553 buttons => [ { id => 'save', label => @unsaved == 1 ? 'Save' : 'Save all', primary => 1 }, { id => 'discard', label => 'Quit without saving' }, { id => 'cancel', label => 'Cancel' } ],
1554 on_done => sub ( $button, $values ) {
1555 return $editor->_save_all($stop) if $button eq 'save';
1556 $stop->() if $button eq 'discard';
1557 },
1558 );
1559 return;
1560 }
1561  
1562 method is_quitting () {
1563 return $quitting;
1564 }
1565  
1566 # ---------------------------------------------------------------------
1567 # Help
1568 # ---------------------------------------------------------------------
1569  
1570 # Commands that work in the form only: the key reference lists their keys
1571 # with the form's.
1572 my %FORM_COMMAND = map { $_ => 1 } qw(edit reset paste_keys only_set);
1573  
1574 # The commands with keys that work everywhere, and their group.
1575 use constant COMMAND_GROUP => 'Everywhere';
1576  
1577 method _commands_everywhere () {
1578 return grep { !$FORM_COMMAND{ $_->id } } $commands->commands;
1579 }
1580  
1581 method key_list () {
1582 return ( Term::Fabulous::Widget::KeyReference->command_rows( COMMAND_GROUP, $self->_commands_everywhere ), _other_keys() );
1583 }
1584  
1585 # The keys that are no commands' (and the form's commands, under The
1586 # form), in groups in the order they are listed.
1587 sub _other_keys () {
1588 return
1589 [ 'Everywhere', 'Alt+1 to Alt+9', 'Show the first to the ninth tab' ],
1590 [ 'Everywhere', 'F10, Alt+F/E/V/T/H', 'Open the menu bar, or one of its menus' ],
1591 [ 'Everywhere', 'Tab, Shift+Tab', 'Move the focus (in text mode: indent, outdent)' ],
1592 [ 'Menus', 'Left, Right, Tab', 'Another menu' ],
1593 [ 'Menus', 'Up, Down, Home, End', 'Another command' ],
1594 [ 'Menus', 'Enter, Space', 'Run the command' ],
1595 [ 'Menus', 'Escape, F10', 'Close the menu' ],
1596 [ 'The form', 'Up, Down, PageUp, PageDown, Home, End', 'Move between settings' ],
1597 [ 'The form', 'Right, +', 'Open a section; Right on an open one goes into it' ],
1598 [ 'The form', 'Left, -', 'Close a section; on a setting, go to its section' ],
1599 [ 'The form', 'Enter, double click', 'Edit the setting; on a section: open or close it' ],
1600 [ 'The form', 'Delete', 'Reset the setting to its default; on a section: all of its settings' ],
1601 [ 'The form', 'Ctrl+C, Ctrl+X', 'Copy (cut) the setting, or every setting of a section' ],
1602 [ 'The form', 'Ctrl+V', 'Paste one value onto the setting, or settings at their keys' ],
1603 [ 'The form', 'Alt+P', 'Paste settings at the keys they were copied from' ],
1604 [ 'The form', 'Ctrl+F, Escape', 'Search the settings; empty the search' ],
1605 [ 'The form', 'Alt+L', 'Show only the settings the theme sets' ],
1606 [ 'Text mode', 'Enter', 'New line, indented like the last (more after {)' ],
1607 [ 'Text mode', 'Tab', 'Indent the selected lines; without a selection, insert one level' ],
1608 [ 'Text mode', 'Shift+Tab', 'Outdent the line or the selected lines' ],
1609 [ 'Text mode', '}', 'Typed into the indentation of a line: one level back' ],
1610 [ 'Text mode', 'Ctrl+C, Ctrl+X, Ctrl+V', 'Copy, cut, paste' ],
1611 [ 'Text mode', 'Ctrl+Z, Ctrl+Y', 'Undo, redo (form changes too, up to 100 steps)' ],
1612 [ 'Text mode', 'Ctrl+A', 'Select everything' ],
1613 [ 'Text mode', 'Shift+arrows, Shift+Home, Shift+End', 'Select' ],
1614 [ 'Text mode', 'Ctrl+Left, Ctrl+Right', 'A word to the left, to the right' ],
1615 [ 'Text mode', 'Alt+Backspace, Ctrl+Delete', 'Delete the word before, after the cursor' ],
1616 [ 'Text mode', 'Ctrl+U, Ctrl+K', 'Delete to the start, to the end of the line' ],
1617 [ 'Text mode', 'Ctrl+F, F3', 'Find, find the next' ],
1618 [ 'Text mode', 'F8', 'Go to the next error' ],
1619 [ 'The preview', 'F6', 'Go to the preview, back to the settings' ],
1620 [ 'The preview', 'Tab, Shift+Tab', 'Move between the widgets' ],
1621 [ 'The preview', 'PageUp, PageDown', 'Scroll the preview' ],
1622 [ 'The preview', 'Ctrl+Home, Ctrl+End', 'The top, the end of the preview' ],
1623 [ 'Dialogs', 'Tab, Shift+Tab', 'Move between the fields and buttons' ],
1624 [ 'Dialogs', 'Enter', 'Choose (in a list), press the button' ],
1625 [ 'Dialogs', 'Escape', 'Cancel' ],
1626 [ 'Files', 'Enter', 'Open a folder, choose a file' ],
1627 [ 'Files', 'Backspace', 'The parent folder' ];
1628 }
1629  
1630 method _show_keys () {
1631 Term::Fabulous::Widget::KeyReference->new(
1632 title => 'Keys of the theme editor',
1633 commands => [ $self->_commands_everywhere ],
1634 group => COMMAND_GROUP,
1635 keys => [ _other_keys() ],
1636 height => max( 1, min( 40, $ui->height - 2 ) ),
1637 width => max( 1, min( 100, $ui->width - 2 ) ),
1638 )->open($ui);
1639 return;
1640 }
1641  
1642 method _show_about () {
1643 $self->_ask(
1644 title => 'About',
1645 message =>
1646 "The theme editor of [bold]Term::Fabulous[/] $Term::Fabulous::ThemeEditor::VERSION.\n\nIt edits theme files: KDL documents that set the palette and the looks of the widget families of Term::Fabulous. Programs load them with Term::Fabulous::Theme->from_file. See perldoc Term::Fabulous::ThemeEditor and Term::Fabulous::Theme.",
1647 );
1648 return;
1649 }
1650  
1651 # ---------------------------------------------------------------------
1652 # Status
1653 # ---------------------------------------------------------------------
1654  
1655 method _status_info () {
1656 my $tab = $self->active_tab // return ( [ 'F1 keys', 'dim' ] );
1657 my @parts;
1658 my $errors = scalar $tab->document->errors;
1659 push @parts, [ sprintf( '%d error%s', $errors, $errors == 1 ? '' : 's' ), 'danger' ] if $errors;
1660 push @parts, [ 'modified', 'accent' ] if $tab->is_modified;
1661 if ( $tab->mode eq 'text' ) {
1662 my ( $row, $offset ) = $tab->area->editor->cursor;
1663 push @parts, [ sprintf( 'Ln %d, Col %d', $row + 1, $offset + 1 ), 'info' ];
1664 }
1665 push @parts, [ ucfirst( $tab->mode ), 'info' ], [ 'F1 keys', 'dim' ];
1666 return @parts;
1667 }
1668  
1669 # The line under the form: what the setting under the cursor is.
1670 method _explain ($row) {
1671 my $tab = $self->active_tab // return '';
1672 my $document = $self->_shown_document($tab);
1673 if ( $row->{section} ) {
1674 my @keys = $form->keys_in( $row->{id} );
1675 my $set = grep { defined $document->setting($_) } @keys;
1676 return sprintf( '[bold]%s[/]: %d of %d settings set. Enter opens or closes it, Delete resets it, Ctrl+C copies what it sets.', _escaped( $row->{setting} ), $set, scalar @keys );
1677 }
1678 my $key = $row->{key};
1679 my $parsed = Term::Fabulous::Theme::Document::parse_key($key);
1680 my $effective = $document->effective_setting($key);
1681 my $kind
1682 = $parsed->{section} eq 'palette' ? 'a color'
1683 : $parsed->{section} eq 'theme' ? ( $parsed->{field} eq 'name' ? 'the theme\'s name' : 'the built-in theme it starts from' )
1684 : do {
1685 my $info = Term::Fabulous::Theme::slot_info( @{$parsed}{qw(family slot)} );
1686 $info->{kind} eq 'boolean'
1687 ? 'true or false'
1688 : ( $info->{kind} eq 'style' ? 'a border style' : 'a token or a color' ) . ( $info->{required} ? ', required' : '' );
1689 };
1690 my $line = $document->line_of($key);
1691 my $where = $effective->{origin} eq 'set' ? 'set' . ( defined $line ? " on line $line" : '' ) : 'follows ' . _origin_words($effective);
1692 return sprintf( '[bold]%s[/] (%s): %s. Enter edits, Delete resets, Ctrl+C copies, Ctrl+V pastes.', _escaped($key), $kind, _escaped($where) );
1693 }
1694 }
1695  
1696 1;
1697  
1698 __END__