Source

Kephra / lib / Kephra / App / Part / FileBrowser.pm

use v5.10;
use strict;
use warnings;

package Kephra::App::Part::FileBrowser;
our @ISA = 'Wx::TreeCtrl';
my $panel;
use File::Find;
use File::Spec;

Kephra::API::Command::register({
 'filebrowser-focus' =>{ sub=>'focus', label => ' ', keys => 'F2' },
});


sub new {
	my( $class, $parent) = @_;
	my $self = $panel = $class->SUPER::new(
		$parent, -1, [-1,-1], [-1,-1], 
		&Wx::wxTR_SINGLE | &Wx::wxTR_HIDE_ROOT,
	);

	my $lib = get_modules_and_paths($Kephra::location_path);
	my $root_ID = $self->AddRoot( 'Root', -1, -1, Wx::TreeItemData->new( ));
	if (ref $lib eq 'ARRAY'){
		for (0 .. @$lib - 1){
			my $data = Wx::TreeItemData->new; 
			$data->SetData( $lib->[$_][1] );
			my $ItemID = $self->AppendItem( $root_ID, $lib->[$_][0] );
			$self->SetItemData( $ItemID, $data );
		}
	}

	Wx::Event::EVT_TREE_ITEM_ACTIVATED( $self, -1, sub {
		my ($fb, $event) = @_;
		say $fb->GetItemData( $event->GetItem )->GetData;
		Kephra::File::open( $fb->GetItemData( $event->GetItem )->GetData );
		Wx::Window::SetFocus( $fb );
	} );
	Wx::Event::EVT_KEY_DOWN ($self, sub {
		my ($fb, $event) = @_;
		my $key = Kephra::API::KeyMap::keycode_from_event($event);
		Kephra::API::log("pressed key $key inside the filebrowser");
		if    ($key ==  &Wx::WXK_ESCAPE) {Kephra::API::focus_back() }
		elsif ($key ==  &Wx::WXK_F2)     {Kephra::API::focus_back() }
		elsif ($key ==  &Wx::WXK_F11)    {Kephra::API::main_window()->toggle_fullscreen() } 
		else { $event->Skip }
	});

	# selection only visible when browser has focus
	Wx::Event::EVT_SET_FOCUS($self, sub { $_[0]->SelectItem( $_[0]->GetSelection, 1) });
	Wx::Event::EVT_KILL_FOCUS($self, sub { $_[0]->SelectItem( $_[0]->GetSelection, 0) });

	my ($fi_ID, $cookie) = $self->GetFirstChild($root_ID);
	$self->SelectItem( $fi_ID, 1 ); # hack tor eall start when focus at number 1 not 0
	$self->SelectItem( $fi_ID, 0 );
	return $self;
}

sub focus{ Kephra::API::focus( $panel ) }

sub get_modules_and_paths {
	my $dir = shift;
	return 0 unless -d $dir;
	my $cwd = Cwd::cwd();
	chdir $dir;
	my @libs;
	find( sub {
		return if not -f $_ or $_ !~ /\.pm$/;
		my $file = my $module = $File::Find::name;
		$module = substr($module, 2);
		$module =~ s|\.pm||;
		$module =~ s|/|::|g;
		push @libs, [ $module, File::Spec->catfile($dir, $file) ];
	}, '.');
	chdir $cwd;
	@libs = sort {$a->[0] cmp $b->[0]} @libs;
	return \@libs;
}


1;