blib/lib/Term/Fabulous/Widget/FileDialog.pm untested

filter: Statementstmt 0.0% 0 / 342 Branchbran 0.0% 0 / 142 Conditioncond 0.0% 0 / 82 MC/DCmcdc 0.0% 0 / 49 Subroutinesub 0.0% 0 / 30 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 646 CC 3 SCAR 10.8
CC
3
Cov
0%
BUILDARGS
12.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.9
1 package Term::Fabulous::Widget::FileDialog;
2  
3 use v5.32;
4 use warnings;
5 use feature 'signatures';
6 no warnings 'experimental::signatures';
7  
8 use Object::Pad 0.825;
9  
10 use Term::Fabulous::Widget::Dialog;
11  
12 our $VERSION = '0.05';
13  
14 class Term::Fabulous::Widget::FileDialog
15 :isa(Term::Fabulous::Widget::Dialog)
16 :strict(params)
17 {
18 use Clay::UI::Enum::Result;
19 use Clay::XS qw(sizing_grow);
20 use Cwd qw(abs_path getcwd);
21 use Encode qw(decode encode);
22 use File::Basename qw(basename dirname);
23 use File::Spec;
24 use List::Util qw(any first min);
25 use POSIX qw(strftime);
26 use Scalar::Util qw(weaken);
27 use Term::Fabulous::Check qw(boolean describe one_of positive_integer string);
28 use Term::Fabulous::Text::Markup qw(escape_markup);
29 use Term::Fabulous::Widget::Box;
30 use Term::Fabulous::Widget::Checkbox;
31 use Term::Fabulous::Widget::Dropdown;
32 use Term::Fabulous::Widget::FileDialog::FolderLine;
33 use Term::Fabulous::Widget::Prompt;
34 use Term::Fabulous::Widget::Table;
35 use Term::Fabulous::Widget::Table::Frame qw(framed);
36 use Term::Fabulous::Widget::Text;
37 use Term::Fabulous::Widget::TextField;
38  
39 use constant DEFAULT_WIDTH => 70;
40 use constant CANCEL => 'cancel';
41 use constant FEWEST_ROWS => 2; # the entries the list keeps on a small screen
42  
43 # What each mode calls itself: its default title, the label and the
44 # placeholder of the field, and the button (and answer) that takes
45 # the choice.
46 my %MODE = (
47 open => { title => 'Open a file', field => 'File', placeholder => 'A file name or a path', button => 'Open', answer => 'open' },
48 save => { title => 'Save the file as', field => 'File', placeholder => 'A file name or a path', button => 'Save', answer => 'save' },
49 folder => { title => 'Choose a folder', field => 'Name', placeholder => 'A folder name or a path', button => 'Choose', answer => 'choose' },
50 );
51  
52 my $generated_ids = 0;
53  
54 field $mode :param = 'open';
55 field $directory :param = undef; # bytes, as the file system has them
56 field $current_file :param = undef; # bytes
57 field $list_rows :param = 10;
58 field $show_hidden :param = 0;
59 field $default_extension :param = undef;
60 field $confirm_overwrite :param = undef;
61  
62 field @_filters; # [ { label, patterns => [ regex, ... ] } ], in order
63 field $_filter; # the index of the active filter, undef without filters
64 field $_folder_line;
65 field $_list;
66 field $_field;
67 field $_filter_choice; # the Dropdown, undef with fewer than two filters
68 field $_hidden_box;
69 field $_replace_question; # the open Replace question, a weak reference
70  
71 # A file dialog is a dialog with room at its sides and no gaps between
72 # its parts (it has many), as wide as the program asks or as the
73 # screen when that is narrower, with an id the id of its list derives
74 # from. Its title and its two buttons come from its mode, and its
75 # notice line always takes its row, so that a message does not move
76 # the buttons.
77 sub BUILDARGS ( $class, %params ) {
78 my $width = positive_integer( $class, width => delete $params{width} // DEFAULT_WIDTH );
79 my $layout = $params{layout} // {};
80 $params{id} //= 'file-dialog-' . ++$generated_ids;
81 $params{layout} = {
82 padding => { left => 2, right => 2, top => 1, bottom => 1 },
83 child_gap => 0,
84 %$layout,
85 sizing => { width => sizing_grow( 0, $width ), %{ $layout->{sizing} // {} } },
86 };
87 my @own = grep { exists $params{$_} } qw(buttons notice_line);
88 die "$class: a file dialog has its own @own" if @own;
89 $params{notice_line} = 'row';
90 if ( my $words = $MODE{ $params{mode} // 'open' } ) { # an unknown mode dies in ADJUST
91 $params{title} //= $words->{title};
92 $params{buttons} = [ { id => $words->{answer}, label => $words->{button}, primary => 1 }, { id => CANCEL, label => 'Cancel' } ];
93 }
94 return $class->SUPER::BUILDARGS(%params);
95 }
96  
97 ADJUST :params ( :$filters = undef, :$name = undef ) {
98 $mode = one_of( $self, mode => $mode, sort keys %MODE );
99 if ( $mode eq 'folder' ) {
100 my %meaningless = ( filters => $filters, default_extension => $default_extension, name => $name, confirm_overwrite => $confirm_overwrite );
101 my @given = grep { defined $meaningless{$_} } sort keys %meaningless;
102 die ref($self) . ": a folder dialog takes no " . join( ', ', @given ) if @given;
103 }
104 $directory = $self->_checked_directory( $directory // getcwd() );
105 $current_file = $self->_checked_current_file($current_file);
106 $list_rows = positive_integer( $self, list_rows => $list_rows );
107 $show_hidden = boolean( $self, show_hidden => $show_hidden );
108 $default_extension = $self->_checked_extension($default_extension);
109 $confirm_overwrite = boolean( $self, confirm_overwrite => $confirm_overwrite // 1 );
110 @_filters = $self->_parsed_filters( $filters // [] );
111 $_filter = @_filters ? 0 : undef;
112  
113 $self->_build( _decoded( $self->_checked_bytes( name => $name // '' ) ) );
114 }
115  
116 # ---------------------------------------------------------------------
117 # Parameters
118 # ---------------------------------------------------------------------
119  
120 # Paths and names come as the file system has them: bytes, not
121 # characters.
122 method _checked_bytes ( $name, $value ) {
123 $value = string( $self, $name => $value );
124 die ref($self) . ": $name must be bytes as the file system has them (encode it to UTF-8 first), got a character string" if $value =~ /[^\x00-\xff]/;
125 return $value;
126 }
127  
128 method _checked_directory ($path) {
129 $path = $self->_checked_bytes( directory => $path );
130 die ref($self) . ": directory '$path' is not a folder" unless -d $path;
131 return _absolute($path);
132 }
133  
134 method _checked_current_file ($path) {
135 return undef unless defined $path;
136 $path = $self->_checked_bytes( current_file => $path );
137 die ref($self) . ": current_file must be an absolute path, got '$path'" unless File::Spec->file_name_is_absolute($path);
138 return _canonical($path);
139 }
140  
141 method _checked_extension ($extension) {
142 return undef unless defined $extension;
143 $extension = string( $self, default_extension => $extension );
144 die ref($self) . ": default_extension must be an extension without its dot, like 'txt', got '$extension'" unless $extension =~ m{\A[^./\s][^/\s]*\z};
145 return $extension;
146 }
147  
148 # A filter is [ label, patterns ]: the patterns are globs separated by
149 # white space, matched without case.
150 method _parsed_filters ($filters) {
151 die ref($self) . ": filters must be an array reference, got " . describe($filters) unless ref $filters eq 'ARRAY';
152 my ( @parsed, %seen );
153 foreach my $filter (@$filters) {
154 die ref($self) . ": a filter must be [ label, patterns ], got " . describe($filter) unless ref $filter eq 'ARRAY' && @$filter == 2;
155 my $label = string( $self, 'the label of a filter' => $filter->[0] );
156 my @patterns = split ' ', string( $self, "the patterns of the filter '$label'" => $filter->[1] );
157 die ref($self) . ": the filter '$label' has no patterns" unless @patterns;
158 die ref($self) . ": two filters are labelled '$label'" if $seen{$label}++;
159 push @parsed, { label => $label, patterns => [ map { _glob_regex($_) } @patterns ] };
160 }
161 return @parsed;
162 }
163  
164 sub _glob_regex ($glob) {
165 my $regex = join '', map { $_ eq '*' ? '.*' : $_ eq '?' ? '.' : quotemeta } split /([*?])/, $glob;
166 return qr/\A$regex\z/is;
167 }
168  
169 # ---------------------------------------------------------------------
170 # The parts
171 # ---------------------------------------------------------------------
172  
173 method _build ($name) {
174 my @size_column = $mode eq 'folder' ? () : ( { key => 'size', title => 'Size', width => 'fit', sortable => 0, align => 'right' } );
175 $_folder_line = Term::Fabulous::Widget::FileDialog::FolderLine->new;
176 $_list = Term::Fabulous::Widget::Table->new(
177 id => $self->id . '/list',
178 row_id => 'entry',
179 selection => 'single',
180 border => 'none',
181 column_lines => 'none',
182 header_line => 'Solid',
183 columns => [
184 { key => 'name', title => 'Name', width => 'grow', sortable => 0, cell => \&_name_cell },
185 @size_column,
186 { key => 'modified', title => 'Modified', width => 'fit', sortable => 0 },
187 ],
188 layout => { sizing => { width => sizing_grow(), height => sizing_grow() } },
189 );
190 $_list->on( RowActivate => sub ( $self, $event ) { $self->_enter( $event->row_id ); return }, owner => $self );
191 $_list->on( CursorMove => sub ( $self, $event ) { $self->_pointed( $event->row_id ); return Clay::UI::Enum::Result->CONTINUE }, owner => $self );
192 $_list->on(
193 KeyPress => sub ( $self, $event ) { return ( $event->main_key_name // '' ) eq 'Backspace' && $self->_up ? Clay::UI::Enum::Result->HANDLED : Clay::UI::Enum::Result->CONTINUE },
194 owner => $self
195 );
196  
197 $_field = Term::Fabulous::Widget::TextField->new( value => $name, placeholder => $MODE{$mode}{placeholder}, layout => { sizing => { width => sizing_grow() } } );
198 $_field->on( Submit => sub ( $self, $event ) { $self->_submitted( $event->value ); return }, owner => $self );
199 my $field_row = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow() }, child_gap => 1 } );
200 $field_row->add_child( Term::Fabulous::Widget::Text->new( text => $MODE{$mode}{field} ), $_field );
201  
202 my $options_row = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow() }, child_gap => 2 } );
203 if ( @_filters > 1 ) {
204 $_filter_choice = Term::Fabulous::Widget::Dropdown->new( options => [ map { $_->{label} } @_filters ], value => $_filters[0]{label} );
205 $_filter_choice->on( Change => sub ( $self, $event ) { $self->filter( $event->value ); return Clay::UI::Enum::Result->CONTINUE }, owner => $self );
206 $options_row->add_child($_filter_choice);
207 }
208 $_hidden_box = Term::Fabulous::Widget::Checkbox->new( label => 'Show hidden files', checked => $show_hidden );
209 $_hidden_box->on( Change => sub ( $self, $event ) { $self->show_hidden( $event->value ); return Clay::UI::Enum::Result->CONTINUE }, owner => $self );
210 $options_row->add_child($_hidden_box);
211  
212 # The list counts its header and the line below it as rows.
213 $self->add_child( $_folder_line, framed( $_list, $list_rows + 2, min( $list_rows, FEWEST_ROWS ) + 2 ), $field_row, $options_row );
214 return;
215 }
216  
217 # A name too long for its column is cut from the left, so that it
218 # does not push the size and the time out of the list.
219 sub _name_cell ($cell) {
220 return Term::Fabulous::Widget::FileDialog::FolderLine->new( label => '', path => $cell->{display} );
221 }
222  
223 # The notice line above the buttons, empty while all is well: a text
224 # and the path it is about, as given.
225 method _say ( $text, $path = '', $after = '' ) {
226 return $self->notice( join '', map { escape_markup($_) } $text, $path, $after );
227 }
228  
229 # A file or folder that is not there, named as the user typed it.
230 method _say_missing ( $kind, $target ) {
231 return $self->_say( "There is no $kind ", $target->{shown}, $target->{here} ? ' in this folder.' : '.' );
232 }
233  
234 # ---------------------------------------------------------------------
235 # Accessors
236 # ---------------------------------------------------------------------
237  
238 method directory () {
239 return $directory;
240 }
241  
242 method typed () {
243 return $_field->value;
244 }
245  
246 method list () {
247 return $_list;
248 }
249  
250 method filter (@new) {
251 return defined $_filter ? $_filters[$_filter]{label} : undef unless @new;
252 my $label = $new[0];
253 my $index = first { $_filters[$_]{label} eq ( $label // '' ) } 0 .. $#_filters;
254 die ref($self) . ": the dialog has no filter labelled " . describe($label) unless defined $index;
255 $_filter = $index;
256 $_filter_choice->value($label) if defined $_filter_choice && ( $_filter_choice->value // '' ) ne $label;
257 $self->_list_directory if $self->is_open;
258 return $label;
259 }
260  
261 method show_hidden (@new) {
262 return $show_hidden unless @new;
263 $show_hidden = boolean( $self, show_hidden => $new[0] );
264 $_hidden_box->checked($show_hidden) if $_hidden_box->checked != $show_hidden;
265 $self->_list_directory if $self->is_open;
266 return $show_hidden;
267 }
268  
269 # ---------------------------------------------------------------------
270 # The folder
271 # ---------------------------------------------------------------------
272  
273 method _list_directory () {
274 $_folder_line->path( _decoded($directory) );
275 my @rows = $directory eq File::Spec->rootdir ? () : ( { name => '../', entry => '..', kind => 'up', size => '', modified => '' } );
276 if ( opendir my $handle, $directory ) {
277 push @rows, $self->_rows_of( grep { $_ ne '.' && $_ ne '..' } readdir $handle );
278 closedir $handle;
279 $self->_say('');
280 }
281 else {
282 $self->_say("Cannot read the folder: $!.");
283 }
284 $_list->rows( \@rows );
285 return;
286 }
287  
288 # The rows of the folder's entries: the folders, then the files the
289 # filter lets through, each sorted by the name shown.
290 method _rows_of (@entries) {
291 my ( @folders, @files );
292 foreach my $entry ( grep { $show_hidden || !/\A\./ } @entries ) {
293 my $path = File::Spec->catfile( $directory, $entry );
294 my $name = _decoded($entry);
295 if ( -d $path ) {
296 push @folders, { name => "$name/", entry => $entry, kind => 'folder', size => '', modified => _when($path) };
297 next;
298 }
299 next if $mode eq 'folder' || !$self->_passes_filter($name);
300 push @files, { name => $name, entry => $entry, kind => 'file', size => _size($path), modified => _when($path) };
301 }
302 return map {
303 sort { fc $a->{name} cmp fc $b->{name} or $a->{entry} cmp $b->{entry} }
304 @$_
305 } \@folders, \@files;
306 }
307  
308 method _passes_filter ($name) {
309 return 1 unless defined $_filter;
310 return any { $name =~ $_ } @{ $_filters[$_filter]{patterns} };
311 }
312  
313 sub _size ($path) {
314 my $bytes = -s $path // 0;
315 return $bytes < 1024 ? "$bytes B" : $bytes < 1024 * 1024 ? sprintf( '%.1f KiB', $bytes / 1024 ) : sprintf( '%.1f MiB', $bytes / 1024 / 1024 );
316 }
317  
318 sub _when ($path) {
319 my $time = ( stat $path )[9] // return '';
320 return strftime( '%Y-%m-%d %H:%M', localtime $time );
321 }
322  
323 # The file system's names are bytes; the dialog shows and matches them
324 # as UTF-8 text, with a byte that is no UTF-8 shown as \xHH.
325 sub _decoded ($bytes) {
326 return decode( 'UTF-8', $bytes, Encode::FB_PERLQQ | Encode::LEAVE_SRC );
327 }
328  
329 sub _encoded ($text) {
330 return encode( 'UTF-8', $text );
331 }
332  
333 # An absolute path without symbolic links, or just made absolute when
334 # they cannot be resolved.
335 sub _absolute ($path) {
336 return abs_path($path) // File::Spec->rel2abs($path);
337 }
338  
339 # The same for a file that may not exist yet: its folder resolved.
340 sub _canonical ($path) {
341 return _absolute($path) if -d $path;
342 return File::Spec->catfile( _absolute( dirname($path) ), basename($path) );
343 }
344  
345 # Another folder: the field empties, except in save mode, where it
346 # keeps the name to save under.
347 method _go ($path) {
348 $directory = _absolute($path);
349 $_field->value('') unless $mode eq 'save';
350 $self->_list_directory;
351 return 1;
352 }
353  
354 method _up () {
355 return 0 if $directory eq File::Spec->rootdir;
356 return $self->_go( dirname($directory) );
357 }
358  
359 # Enter or a double click on an entry: a folder opens, a file is
360 # chosen (and shown in the field).
361 method _enter ($entry) {
362 return unless defined $entry;
363 my $row = $_list->row($entry);
364 return $self->_up if $row->{kind} eq 'up';
365 return $self->_go( File::Spec->catdir( $directory, $entry ) ) if $row->{kind} eq 'folder';
366 $_field->value( $row->{name} );
367 $self->choose( $row->{name} );
368 return;
369 }
370  
371 # In open mode the cursor on a file puts its name into the field; in
372 # folder mode the cursor on a folder does, and on ../ empties it. In
373 # save mode the field keeps the name typed.
374 method _pointed ($entry) {
375 return unless defined $entry;
376 my $row = $_list->row($entry);
377 if ( $mode eq 'folder' ) {
378 $_field->value( $row->{kind} eq 'folder' ? $row->{name} =~ s{/\z}{}r : '' );
379 return;
380 }
381 $_field->value( $row->{name} ) if $mode eq 'open' && $row->{kind} eq 'file';
382 return;
383 }
384  
385 # ---------------------------------------------------------------------
386 # Choosing
387 # ---------------------------------------------------------------------
388  
389 # What a text in the field names: the entry the list shows under this
390 # name, or else the text as a path (in UTF-8 for the file system):
391 # relative to the folder shown, absolute, or starting with ~ for the
392 # home folder. The target keeps the text, to name it in messages, and
393 # whether it is relative to the folder shown. Undef for no text.
394 method _target ($typed) {
395 my $shown = $typed =~ s/\A\s+|\s+\z//gr;
396 return undef unless length $shown;
397 my $row = first { $_->{kind} ne 'up' && ( $_->{name} =~ s{/\z}{}r ) eq $shown } @{ $_list->rows };
398 return { path => File::Spec->catfile( $directory, $row->{entry} ), shown => $shown, here => 1 } if defined $row;
399 my $path = _encoded($shown) =~ s{\A~(?=/|\z)}{$ENV{HOME} // '~'}er;
400 return { path => $path, shown => $shown, here => 0 } if File::Spec->file_name_is_absolute($path);
401 return { path => File::Spec->catfile( $directory, $path ), shown => $shown, here => 1 };
402 }
403  
404 # Enter in the field: in folder mode a folder typed opens, an empty
405 # field chooses the folder shown; otherwise as the button.
406 method _submitted ($typed) {
407 return $self->choose($typed) unless $mode eq 'folder';
408 my $target = $self->_target($typed) // return $self->choose('');
409 return $self->_say_missing( folder => $target ) unless -d $target->{path};
410 $self->_go( $target->{path} );
411 return;
412 }
413  
414 method choose ($typed) {
415 die ref($self) . ": choose needs an open dialog" unless $self->is_open;
416 my $target = $self->_target($typed);
417 return $self->_choose_folder($target) if $mode eq 'folder';
418 return $self->_say( $mode eq 'open' ? 'Choose a file, or type its name.' : 'Type a file name.' ) unless defined $target;
419 if ( -d $target->{path} ) { # a folder typed is used up: it opens
420 $_field->value('');
421 $self->_go( $target->{path} );
422 return $self;
423 }
424 return $mode eq 'open' ? $self->_choose_file_to_open($target) : $self->_choose_file_to_save($target);
425 }
426  
427 method _choose_folder ($target) {
428 return $self->_answer( _absolute($directory) ) unless defined $target;
429 return $self->_say_missing( folder => $target ) unless -d $target->{path};
430 return $self->_answer( _absolute( $target->{path} ) );
431 }
432  
433 method _choose_file_to_open ($target) {
434 return $self->_say_missing( file => $target ) unless -f $target->{path};
435 return $self->_answer( _canonical( $target->{path} ) );
436 }
437  
438 method _choose_file_to_save ($target) {
439 my ( $path, $shown ) = @$target{qw(path shown)};
440 ( $path, $shown ) = ( "$path.$default_extension", "$shown.$default_extension" ) if defined $default_extension && basename($path) !~ /\./;
441 return $self->_say_missing( folder => _folder_target( $target, $path, $shown ) ) unless -d dirname($path);
442 return $self->_say( '', $shown, ' is a folder.' ) if -d $path; # a folder only once the default extension is added
443 $path = _canonical($path);
444 return $self->_ask_to_replace($path) if $confirm_overwrite && -e $path && $path ne ( $current_file // '' );
445 return $self->_answer($path);
446 }
447  
448 # The folder of a file to save that is not there, named by the folder
449 # part of the text typed.
450 sub _folder_target ( $target, $path, $shown ) {
451 my ($folder) = $shown =~ m{\A(.*)/};
452 return { shown => _decoded( dirname($path) ), here => 0 } unless defined $folder;
453 return { here => $target->{here}, shown => length $folder ? $folder : '/' };
454 }
455  
456 # A question above the dialog, starting on Cancel: Replace answers
457 # with the path, Cancel or Escape leave the dialog open.
458 method _ask_to_replace ($path) {
459 my $question = Term::Fabulous::Widget::Prompt->confirm(
460 $self->ui,
461 title => 'Replace the file?',
462 message => '[bold]' . ( _decoded( basename($path) ) =~ s/\[/\\[/gr ) . '[/] already exists. Replace it?',
463 ok => 'Replace',
464 focus => CANCEL,
465 z_index => $self->z_index + 1,
466 );
467 $question->on(
468 Answer => sub ( $self, $event ) {
469 $self->_answer($path) if $event->button eq 'ok' && $self->is_open;
470 return;
471 },
472 owner => $self
473 );
474 weaken( $_replace_question = $question );
475 return $self;
476 }
477  
478 method _close_question () {
479 $_replace_question->close if defined $_replace_question && $_replace_question->is_open;
480 return;
481 }
482  
483 # ---------------------------------------------------------------------
484 # Opening and answering
485 # ---------------------------------------------------------------------
486  
487 # The folder is read each time the dialog opens. Save mode starts in
488 # the field.
489 method open :override ($ui) {
490 return $self if $self->is_open;
491 $self->_list_directory;
492 $self->SUPER::open($ui);
493 $self->_select_name($ui) if $mode eq 'save';
494 return $self;
495 }
496  
497 # The field focused with the name selected up to its extension, so
498 # typing replaces the name and keeps the extension.
499 method _select_name ($ui) {
500 my $stem = $_field->value =~ s/(?<=.)\.[^.]*\z//r;
501 $ui->interaction->set_focused_widget($_field);
502 $_field->editor->set_selection( 0, 0, 0, length $stem );
503 return;
504 }
505  
506 # A choice answers with the button of the mode and the path.
507 method _answer ($path) {
508 return $self->answer( $MODE{$mode}{answer}, path => $path );
509 }
510  
511 # The button of the mode chooses what the field names; Cancel answers.
512 method press_button :override ($id) {
513 return $self->choose( $self->typed ) if $id eq $MODE{$mode}{answer};
514 return $self->SUPER::press_button($id);
515 }
516  
517 # Whatever closes the dialog (an answer, Escape, close from the
518 # program) closes the question above it first.
519 method answer :override ( $id, %values ) {
520 $self->_close_question;
521 return $self->SUPER::answer( $id, %values );
522 }
523  
524 method close :override () {
525 $self->_close_question;
526 return $self->SUPER::close;
527 }
528 }
529  
530 1;
531  
532 __END__