Source

Kephra / lib / Kephra / App / Focus.pm

Full commit
use v5.12;
use warnings;
use Wx;

package Kephra::App::Focus;
my @focus_stack = ();
my $max_stack_size = 50;

use Kephra::App::Util qw(is_widget);

#Kephra::API::Command::register({
 #'app-focus-set-back'  =>{ sub=>'set_back', label=>'',  keys=>'' },
 #'app-focus-stay'      =>{ sub=>'stay',     label=>'',  keys=>'' },
#});


sub get  {                              # give widget in focus or one that was before
	my ($nr) = shift // 0;
	return '' if @focus_stack == 0;
	return $focus_stack[$nr] if $nr < @focus_stack or $nr < 0 and $nr > @focus_stack;
	return '';
}

sub last {                              # give me last widget of a class in focus
	my $class = shift;
	return Kephra::Log::warning( "need a class name", 1 ) unless $class;
	for (@focus_stack) { return $_ if ref $_ eq $class }
}

sub set  {                              # set focus to another widget
	my ($widget) = @_;
	return unless defined $widget;
	#Kephra::Log::note("focus is on :". get()." and will be: $widget");
	return Kephra::Log::warning( "got no proper widget but $widget", 1 ) unless is_widget($widget);
	return if $widget eq get();
	unshift @focus_stack, $widget;
	pop @focus_stack while stack_size() > $max_stack_size;
	stay();
}

sub set_back {                          # undo n times (default 1) a set command
	my ($times) = shift // 1;
	for (1 .. $times) { shift @focus_stack if stack_size() > 1 }
	stay();
}

sub stay {                              # reset focus to current (last set) entry
	my ($widget) = get();
	is_widget($widget)
		? Wx::Window::SetFocus( $widget )
		: Kephra::Log::warning( "no widget to stay focussed on", 1 );
}

sub stack_size { scalar @focus_stack }  # get current size (number  of memorized widgets)

sub max_stack_size {                    # get and set maximum number of memorized widgets in focus
	my $new_stack_size = shift;
	$max_stack_size = defined $new_stack_size ? $new_stack_size : $max_stack_size;
}


1;