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

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