PrimaX/InputHistory.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary App/Prima/REPL.pm »
1 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 0 ▶use Prima;
Subroutine BEGIN: called CC=1 SCAR=2.6
4  
5 # Note: the documentation is given below.
6  
7 package ih;
8 use constant Null => 0;
9 use constant StdOut => 1;
10  
11 use constant Unique => 10;
12 use constant All => 11;
13 use constant NoRepeat => 12;
14  
15 ######################################
16 # PrimaX::InputHistory::Output::Null #
17 ######################################
18 # A ridiculously simple output handler that does nothing
19 package PrimaX::InputHistory::Output::Null;
20 sub printout { }
21 sub newline_printout { }
22 sub new {my $self = {}; return bless $self}
23  
24 ########################################
25 # PrimaX::InputHistory::Output::StdOut #
26 ########################################
27 # The default output handler with which InputHistory works; uses Perl's print
28 # statement for output.
29 package PrimaX::InputHistory::Output::StdOut;
30 sub printout {
31 my $self = shift;
32 print @_;
33
34 # Track the last printed line so that newline printout works:
35 if (defined $_[-1]) {
36 $self->{last_line} = $_[-1];
37 }
38 else {
39 $self->{last_line} = '';
40 }
41 }
42 sub newline_printout {
43 my $self = shift;
44 if ($self->{last_line} !~ /\n$/) {
45 $self->printout("\n", @_);
46 }
47 else {
48 $self->printout(@_);
49 }
50 }
51 sub new {
52 my $self = {last_line => ''};
53 return bless $self
54 }
55  
56 =head1 NAME
57  
58 PrimaX::InputHistory - an input line with input history navigation
59  
60 =head1 SYNOPSIS
61  
62 use strict;
63 use warnings;
64 use Prima qw(Application);
65 use PrimaX::InputHistory;
66
67 # A simple repl that prints the output to the screen
68
69 my $window = Prima::MainWindow->new(
70 text => 'Simpe REPL',
71 width => 600,
72 );
73
74 my $file_name = 'my_history.txt';
75 my $history_length = 10;
76 my $inline = PrimaX::InputHistory->create(
77 owner => $window,
78 text => '',
79 pack => {fill => 'both'},
80 storeType => ih::NoRepeat,
81 onCreate => sub {
82 my $self = shift;
83
84 # Open the file and set up the history:
85 my @history;
86 if (-f $file_name) {
87 open my $fh, '<', $file_name;
88 while (<$fh>) {
89 chomp;
90 push @history, $_;
91 }
92 close $fh;
93 }
94
95 # Store the history and revisions:
96 $self->history(\@history);
97 },
98 onDestroy => sub {
99 my $self = shift;
100
101 # Save the last lines in the history file:
102 open my $fh, '>', $file_name;
103 # I want to save the *last* N lines, so I don't necessarily start at
104 # the first entry in the history:
105 my $offset = 0;
106 my @history = @{$self->history};
107 $offset = @history - $history_length if (@history > $history_length);
108 while ($offset < @history) {
109 print $fh $history[$offset++], "\n";
110 }
111 close $fh;
112 },
113 );
114
115 print "Press Up/Down, Page-Up/Page-Down to see your input history\n";
116
117 run Prima;
118  
119  
120 =cut
121  
122 ###########################
123 # PrimaX::InputHistory #
124 ###########################
125 # a history-tracking input line.
126 package PrimaX::InputHistory;
127 use base 'Prima::InputLine';
128  
129 # This has the standard profile of an InputLine widget, except that it knows
130 # about navigation keys and other things useful for the History.
131 sub profile_default
132 {
133 my %def = %{$_[ 0]-> SUPER::profile_default};
134  
135 # These lines are somewhat patterned from the Prima example called 'editor'
136 my @acc = (
137 # Navigation scrolls through the command history
138 ['Previous Line', 'Up', kb::Up, sub {$_[0]->move_line(-1)}]
139 , ['Next Line', 'Down', kb::Down, sub {$_[0]->move_line(1)}]
140 # Note that the values of 10 here are purely symbolic; the function
141 # actually refers to self's pageLines property when it sees +-10
142 , ['Earlier Lines', 'Page Up', kb::PageUp, sub {$_[0]->move_line(-10)}]
143 , ['Later Lines', 'Page Down', kb::PageDown, sub {$_[0]->move_line(10)}]
144 # Enter runs the line
145 , ['Run', 'Return', kb::Return, sub {$_[0]->PressEnter}]
146 , ['Run', 'Enter', kb::Enter, sub {$_[0]->PressEnter}]
147 );
148  
149 return {
150 %def,
151 pageLines => 10, # lines to 'scroll' with pageup/pagedown
152 accelItems => \@acc,
153 outputWidget => ih::StdOut,
154 promptFormat => '> ',
155 currentLine => 0,
156 storeType => ih::All,
157 }
158 }
159  
160 # This stage initializes the inputline. I believe this is the appropriate stage
161 # for (1) setting the properties above (2) loading the history file data, and
162 # (3) connecting to the output widget.
163 sub init {
164 my $self = shift;
165 my %profile = $self->SUPER::init(@_);
166 foreach ( qw(pageLines promptFormat currentLine outputWidget storeType) ) {
167 $self->{$_} = $profile{$_};
168 }
169
170 # Store the history and revisions:
171 $self->currentRevisions([]);
172 $self->history([]);
173 # history calls currentLine, so this doesn't need to be called:
174 # $self->currentLine(0);
175
176 # Set up the output widget. Perl scalars with text are not allowed:
177 if (not ref($profile{outputWidget}) and $profile{outputWidget} !~ /^\d+$/) {
178 croak("Unknown outputWidget $profile{outputWidget}");
179 }
180 elsif ($profile{outputWidget} == ih::Null) {
181 $self->{outputWidget} = new PrimaX::InputHistory::Output::Null;
182 }
183 elsif ($profile{outputWidget} == ih::StdOut) {
184 $self->{outputWidget} = new PrimaX::InputHistory::Output::StdOut;
185 }
186 else {
187 # Make sure it can do what I need:
188 use Carp 'croak';
189 croak("Unknown outputWidget does not appear to be an object")
190 unless ref($profile{outputWidget});
191 croak("outputWidget must have methods printout and newline_printout")
192 unless $profile{outputWidget}->can('printout')
193 and $profile{outputWidget}->can('newline_printout');
194 # Add it to self
195 $self->{outputWidget} = $profile{outputWidget};
196 }
197  
198 return %profile;
199 }
200  
201 # Changes the contents of the evaluation line to the one stored in the history.
202 # This is used for the up/down key callbacks for the evaluation line. The
203 # currentRevisions array holds the revisions to the history, and it is reset
204 # every time the user runs the evaluation line.
205 sub move_line {
206 my ($self, $requested_move) = @_;
207
208 # Set the move to the pageLines number of lines if 10/-10 was requested:
209 $requested_move = $self->pageLines if $requested_move == 10;
210 $requested_move = -$self->pageLines if $requested_move == -10;
211
212 # Determine the requested line number. (currentLine counts backwards)
213 my $line_number = $self->currentLine() - $requested_move;
214
215 # Don't cycle:
216 my $history_length = scalar @{$self->history};
217 $line_number = 0 if $line_number < 0;
218 $line_number = $history_length if $line_number > $history_length;
219
220 # and go there
221 $self->currentLine($line_number);
222 }
223  
224 # The class properties. Template code for these was taken from Prima::Object's
225 # name example property code:
226 sub pageLines {
227 return $_[0]->{pageLines} unless $#_;
228 $_[0]->{pageLines} = $_[1];
229 }
230 sub promptFormat {
231 return $_[0]->{promptFormat} unless $#_;
232 $_[0]->{promptFormat} = $_[1];
233 }
234 sub outputWidget {
235 return $_[0]->{outputWidget} unless $#_;
236 $_[0]->{outputWidget} = $_[1];
237 }
238 sub history {
239 return $_[0]->{history} unless $#_;
240 $_[0]->{history} = $_[1];
241 $_[0]->currentLine(0);
242 return $_[1];
243 }
244 sub currentRevisions {
245 return $_[0]->{currentRevisions} unless $#_;
246 $_[0]->{currentRevisions} = $_[1];
247 }
248 sub storeType {
249 return $_[0]->{storeType} unless $#_;
250 $_[0]->{storeType} = $_[1];
251 }
252  
253 # Gets or sets the current line number, counting backwards. The current line of
254 # text is considered to be at 0; the previous entry is 1, etc. This handles all
255 # the intermediate storage and text swapping.
256 sub currentLine {
257 return $_[0]->{currentLine} unless $#_;
258 my ($self, $line_number) = @_;
259
260 # Save changes to the current line in the revision list:
261 $self->currentRevisions->[$self->{currentLine}] = $self->text;
262
263 # Get the current character offset:
264 my $curr_offset = $self->charOffset;
265 # Note the end-of-line position by zero:
266 $curr_offset = 0 if $curr_offset == length($self->text);
267
268 # make sure the requested line makes sense; cycle if it doesn't, and just
269 # set to zero if there is no history:
270 my $last_line = scalar @{$self->history};
271 if ($last_line) {
272 $line_number += $last_line while $line_number < 0;
273 $line_number -= $last_line while $line_number > $last_line;
274 }
275 else {
276 $line_number = 0;
277 }
278
279 # Set self's current line:
280 $self->{currentLine} = $line_number;
281
282 # Load the text using the Orcish Maneuver:
283 my $new_text = $self->currentRevisions->[$line_number]
284 //= $self->history->[-$line_number]; #/
285 $self->text($new_text);
286
287 # Put the cursor at the previous offset. However, if the previous offset
288 # was zero, put the cursor at the end of the line:
289 $self->charOffset($curr_offset || length($new_text));
290
291 return $line_number;
292 }
293  
294 # Add a new notification_type for each of on_PressEnter and on_Evaluate. The
295 # first should be set with hooks that remove or modify any text that needs to be
296 # cleaned before the eval stage. In other words, if you want to define commands
297 # that do not parse as a function in Perl, add it as a hook under on_PressEnter.
298 # The best examples I can think of, which also serve to differentiate between
299 # the two needs, are NiceSlice processing, and processing the help command. To
300 # make help work as a bona-fide function, you would have to surround your topic
301 # with quotes:
302 # help 'PDL::IO::FastRaw'
303 # That's ugly. It would be much nicer to avoid the quotes, if possible, with
304 # something like this:
305 # help PDL::IO::FastRaw
306 # That's the kinda thing you would handle with an on_PressEnter hook. After the
307 # help hook handles that sort of thing, it then calls the clear_event() method
308 # on the InputHistory object. On the other hand, NiceSlice parsing will modify
309 # the contents of the evaluation, but not call clear_event because it wants the
310 # contents of the text to be passed to the evaluation.
311 #
312 # If the event is properly handled by one of the hooks, the hook should call the
313 # clear_event() method on this object.
314 {
315 # Keep the notifications hash in its own lexically scoped block so that
316 # other's can't mess with it (at least, not without using PadWalker or some
317 # such).
318 my %notifications = (
319 %{Prima::InputLine-> notification_types()},
320 PressEnter => nt::Request,
321 Evaluate => nt::Action,
322 PostEval => nt::Request,
323 );
324
325 sub notification_types { return \%notifications }
326 }
327  
328 # Issues the on_Evaluate notification. The default evaluation is pretty lame -
329 # it just prints the result of evaling the text using the print command.
330 sub Evaluate {
331 my ($self, $text) = @_;
332 $_[0]->notify('Evaluate', $text);
333 }
334  
335 sub on_evaluate {
336 my ($self, $text) = @_;
337 my $results = eval ($text);
338 $self->outputWidget->newline_printout($results) if defined $results;
339 $self->outputWidget->newline_printout('undef') if not defined $results;
340 }
341  
342 # Issues the on_PostEval notification.
343 sub PostEval {
344 $_[0]->notify('PostEval');
345 }
346  
347 # The default notification is to do nothing:
348 sub on_posteval {}
349  
350 # Issues the on_Enter notification, which starts with the class's method. The
351 # return value here is important and determines whether or not to evaluate the
352 # result. Evaluation can be prevented by a handler by calling the clear_event
353 # method on the InputHistory object from within the handler.
354 sub PressEnter {
355 my $self = shift;
356 # Get a copy of the text from the widget.
357 my $text = $self->text;
358 # Call the hooks, allowing them to modify the text as they go:
359 my $needs_to_eval = $self->notify('PressEnter', $text);
360 $self->Evaluate($text) if $needs_to_eval;
361 $self->PostEval($text);
362 }
363  
364 # This is the object's method for handling PressEnter events. Its job is to
365 # handle all of the history-related munging. It does not change the contents of
366 # the text, so it is safe to unpack the text. (Hooks that intend to modify the
367 # text must work directly with $_[1].)
368 #
369 # Additional PressEnter handlers are called after this one and can be added with
370 # $input_widget->add_notification(PressEnter => sub {});
371 sub on_pressenter {
372 my ($self, $text) = @_;
373  
374 # Remove the endlines, if present, replacing them with safe whitespace:
375 $text =~ s/\n/ /g;
376
377 # Reset the current collection of revisions:
378 $self->{currentRevisions} = [];
379
380 # print this line:
381 $self->outputWidget->newline_printout($self->promptFormat, $text, "\n");
382  
383 # We are about to add this text to the history. Before doing so, check if
384 # the history needs to be modified before performing the add:
385 if ($self->storeType == ih::NoRepeat
386 and defined $self->history->[-1]
387 and $self->history->[-1] eq $text
388 ) {
389 # remove the previous entry if it's identical to this one:
390 pop @{$self->history};
391 }
392 elsif ($self->storeType == ih::Unique) {
393 # Remove all the other identical entries if they are the same is this:
394 $self->history([ grep {$text ne $_} @{$self->history} ]);
395 }
396  
397 # Add the text as the last element in the entry:
398 push @{$self->history}, $text;
399
400 # Remove the text from the entry
401 $self->text('');
402
403 # Set the current line to the last one:
404 $self->{currentLine} = 0;
405 }
406  
407 1;
408  
↑ Summary App/Prima/REPL.pm »