Source

Kephra / lib / Kephra / App / Menu.pm

Full commit
use strict;
use warnings;

use Kephra::API;
use Kephra::CommandList;

package Kephra::App::Menu;


my $menu_ID = 1000;
my %storage;

# build ready to compile data structure from menu definitions (list of commandID)
sub assemble {
	my $menu_def = shift;
	die "__PACKAGE__::assemble got no array ref" unless ref $menu_def eq ref [];
	my $menu_ID = '';
	my @menu_data;

	for my $item_def (@$menu_def) {
		if    (ref $item_def eq ref []) { push  @menu_data, assemble($item_def) }
		elsif (ref $item_def eq ref {}) {
			$menu_ID = $item_def->{'menu_ID'}
				if defined $item_def->{'menu_ID'} and not $menu_ID;
			push  @menu_data, $item_def;
		}
		elsif (not defined $item_def or not $item_def) {
			push  @menu_data, 'separator';
		} else  {
			$item_def = $menu_ID.$item_def if substr($item_def, 0, 1) eq '-';
			my $cmd_data = Kephra::CommandList::cmd_all_properties( $item_def );
			next unless $cmd_data;
			push @menu_data, {
				'type' => 'item',
				'label'=> ucfirst $cmd_data->{'label'},
				'coderef' => $cmd_data->{'coderef'},
			};
		}
	}
	return \@menu_data;
}

# make real menus from datastructure
sub compile {
	my $menu_data = shift;
	die "__PACKAGE__::compile got no array ref" unless ref $menu_data eq ref [];

	my $menu = Wx::Menu->new();
	my $item_ID = $menu_ID;
	$menu_ID += 100;
	my $win = Kephra::API::main_window();

	for my $item_data (@$menu_data) {
		if (ref $item_data eq ref []) {
			my ($submenu, $name) = compile( $item_data );
			my $item = Wx::MenuItem->new(
				$menu, $item_ID++, $name, ' ', &Wx::wxITEM_NORMAL, $submenu
			);
			#if (defined $item_data->{icon}) {
				#my $bmp = ;
				#$menu_item->SetBitmap( $bmp ) if ref $bmp eq 'Wx::Bitmap' and not Wx::wxMAC();
			#}
			$menu->Append( $item );
		}
		elsif (ref $item_data eq ref {} and exists $item_data->{'type'}) {
			my $item = Wx::MenuItem->new(
				$menu, $item_ID,
				$item_data->{'label'}, ' ', &Wx::wxITEM_NORMAL
			);

			Wx::Event::EVT_MENU( $win, $item_ID, $item_data->{'coderef'} );

			$menu->Append( $item );
			$item_ID++;
		} elsif (not ref $item_data and $item_data eq 'separator'){
			$menu->AppendSeparator;
		}
	}
	return wantarray
		? ($menu, ucfirst $menu_data->[0]{'menu_ID'})
		:  $menu;
}

1;