summaryrefslogtreecommitdiff
path: root/lib/App/Raps2/UI.pm
blob: faca33f6d49fea5219ddc61c4c403ec56b36d228 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package App::Raps2::UI;

use strict;
use warnings;
use 5.010;

use Carp qw(confess);
use POSIX;
use Term::ReadLine;

our $VERSION = '0.2';

sub new {
	my ($obj) = @_;
	my $ref = {};
	$ref->{term_readline} = Term::ReadLine->new('App::Raps2');
	return bless($ref, $obj);
}

sub list {
	my ($self, @list) = @_;
	my $format = "%-20s %-20s %s\n";

	if (not $self->{list}->{header}) {
		printf($format, map { $_->[0] } @list);
		$self->{list}->{header} = 1;
	}
	printf($format, map { $_->[1] // q{} } @list);
}

sub read_line {
	my ($self, $str, $pre) = @_;

	my $input = $self->{term_readline}->readline("${str}: ", $pre);

	return $input;
}

sub read_multiline {
	my ($self, $str) = @_;
	my $in;

	say "${str} (^D to quit)";

	while (my $line = $self->read_line('multiline')) {
		$in .= "${line}\n";
	}
	return $in;
}

sub read_pw {
	my ($self, $str, $verify) = @_;
	my ($in1, $in2);

	my $term = POSIX::Termios->new();
	$term->getattr(0);
	$term->setlflag($term->getlflag() & ~POSIX::ECHO);
	$term->setattr(0, POSIX::TCSANOW);

	print "${str}: ";
	$in1 = readline(STDIN);
	print "\n";

	if ($verify) {
		print 'Verify: ';
		$in2 = readline(STDIN);
		print "\n";
	}

	$term->setlflag($term->getlflag() | POSIX::ECHO);
	$term->setattr(0, POSIX::TCSANOW);

	if ($verify and $in1 ne $in2) {
		confess('Input lines did not match');
	}

	chomp $in1;
	return $in1;
}

sub to_clipboard {
	my ($self, $str) = @_;

	open(my $clipboard, '|-', 'xclip -l 1');
	print $clipboard $str;
	close($clipboard);
	return;
}

sub output {
	my ($self, @out) = @_;

	for my $pair (@out) {
		printf(
			"%-8s : %s\n",
			$pair->[0],
			$pair->[1] // q{},
		);
	}
	return;
}

1;