add basic UI plugin infrastructure

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
This commit is contained in:
Thomas Lamprecht 2023-06-19 16:59:22 +02:00
parent 170ab052a1
commit bc05a8fc6b
5 changed files with 167 additions and 0 deletions

View File

@ -13,6 +13,10 @@ PERL_MODULES=\
Sys/Command.pm \
Sys/File.pm \
Sys/Net.pm \
UI.pm \
UI/Base.pm \
UI/Gtk3.pm \
UI/StdIO.pm \
.PHONY: install
install: $(PERL_MODULES)

56
Proxmox/UI.pm Normal file
View File

@ -0,0 +1,56 @@
package Proxmox::UI;
# a few simple abstractions to be a bit more general over what UI is in use, this is basically an
# UI², a User-Interface Interface
use strict;
use warnings;
use Carp;
use Proxmox::UI::Gtk3;
use Proxmox::UI::StdIO;
my $ui = undef;
sub init_gtk {
my ($state) = @_;
croak "overriding existing UI!" if defined($ui);
$ui = Proxmox::UI::Gtk3->new($state);
return $ui;
}
sub init_stdio {
my ($state) = @_;
croak "overriding existing UI!" if defined($ui);
$ui = Proxmox::UI::StdIO->new($state);
return $ui;
}
sub get_ui {
return $ui // croak "no UI initialized!";
}
sub message {
my ($msg) = @_;
get_ui()->message($msg);
}
sub error {
my ($msg) = @_;
get_ui()->error($msg);
}
sub prompt {
my ($query) = @_;
return get_ui()->prompt($query);
}
}
1;

36
Proxmox/UI/Base.pm Normal file
View File

@ -0,0 +1,36 @@
package Proxmox::UI::Base;
use strict;
use warnings;
use Carp;
sub new {
my ($this, $state) = @_;
my $class = ref($this) || $this;
my $self = bless { state => $state }, $class;
return $self;
}
sub message {
my ($self, $msg) = @_;
croak "implement me in sub-class";
}
sub error {
my ($self, $msg) = @_;
croak "implement me in sub-class";
}
sub prompt {
my ($self, $query) = @_;
croak "implement me in sub-class";
}
1;

39
Proxmox/UI/Gtk3.pm Normal file
View File

@ -0,0 +1,39 @@
package Proxmox::UI::Gtk3;
use strict;
use warnings;
use Gtk3;
use base qw(Proxmox::UI::Base);
sub message {
my ($self, $msg) = @_;
my $window = $self->{state}->{window};
my $dialog = Gtk3::MessageDialog->new($window, 'modal', 'info', 'ok', $msg);
$dialog->run();
$dialog->destroy();
}
sub error {
my ($self, $msg) = @_;
my $window = $self->{state}->{window};
my $dialog = Gtk3::MessageDialog->new($window, 'modal', 'error', 'ok', $msg);
$dialog->run();
$dialog->destroy();
}
sub prompt {
my ($self, $query) = @_;
my $window = $self->{state}->{window};
my $dialog = Gtk3::MessageDialog->new($window, 'modal', 'question', 'ok-cancel', $query);
my $response = $dialog->run();
$dialog->destroy();
return ($response // '') eq 'ok';
}
1;

32
Proxmox/UI/StdIO.pm Normal file
View File

@ -0,0 +1,32 @@
package Proxmox::UI::StdIO;
use strict;
use warnings;
use base qw(Proxmox::UI::Base);
sub message {
my ($self, $msg) = @_;
print STDOUT "message: $msg\n";
}
sub error {
my ($self, $msg) = @_;
print STDOUT "error: $msg\n";
}
sub prompt {
my ($self, $query) = @_;
print STDOUT "prompt: $query\n";
my $response = <STDIN> // ''; # FIXME: error handling?
chomp($response);
return lc($response) eq 'ok';
}
1;