#!/usr/bin/perl

# DCT - desktop calculator thingy

# reverse polish notition calculator using curses
# by Shiar <shiar.org>

our $VERSION = 1.009;

use strict;
use warnings;
use utf8;

use Term::ReadKey;
use Curses;

use vars qw(@stack %val %var %set %alias %action %hook);

%set = (
	base     => 10,  # decimal; set using commands bin/oct/dec/hex/base
	numb     =>  0,  # fixed scientific engineering
	card     =>  1,  # degrees radians grades
	coord    =>  0,  # cartesian polar spherical
	complex  =>  0,  # real complex

	height   =>  4,  # stack depth (lines of stack plus one)
	width    => 42,  # limit value precision, stetch menu
); # %set

%alias = (' '=>'enter', "\004"=>'quit', 'q'=>'quit');  # rudimentary default key bindings

%action = (
	"chs"   => [1, sub { -$_[0] }], # negative

	"drop"  => [1, sub { defined $val{i} ? '' : () }], # drop
	"back"  => [1, sub { () }], # drop essentially
	"clear" => [0, sub { @stack = (); undef %val; () }], # clear all  #todo: if (val{i}) delete char after cursor

	"enter" => [0, sub {
		local $_ = defined $val{i} ? $val{i} : $stack[0];
		undef %val;
		return defined $_ ? $_ : ();
	}], # duplication

	"swap"  => [2, sub { reverse @_ }], # swap x<->y
	"undo"  => [-1, sub {
		($var{undo}, @stack) = ([@stack], @{ $var{undo} });
	}], # undo/redo
	"stack" => [-1, sub {
		$var{stackpos} = 0 unless $var{stackpos};  # initialize
		$var{stackpos} %= @stack;  # cycle
		$val{i} = $stack[$var{stackpos}++];
	}], # stack

	"version" => [-1, sub { error("Desktop Calculator Thingy $VERSION by Shiar"); () }], # version

	"sto"   => [1, sub { $var{a} = $_[0] }], # copy
	'?'     => [1, sub { $var{a} = $_[0] }], # assign
); # %action


sub error($) {
	attron(A_REVERSE);
	addstr(0, 0, shift);
	attroff(A_REVERSE);
	clrtoeol;
	refresh;

	ReadKey; # wait for confirm
	1 while defined ReadKey(-1); # clear key buffer
} # error

sub showval($$);
sub showval($$) {
	my ($val, $base) = @_;
	return '' unless defined $val;
	return $val if $base==10;

	my $sign = $val<0;
	$val = abs $val;
	my $int = int $val;
	my $frac = $val-$int;
	my $exp = 0;

	my $txt = '';

	while ($int>$base**10) {
		$int /= $base;
		$exp++;
	} # exponent part

	while ($int>=1) {
		my $char = $int%$base;
		$txt = ($char<10 ? $char : chr($char+55)).$txt;
		$int /= $base;
	} # integer part

	$txt .= '.' if $frac>0;
	for (my $i = 0; length $txt<$set{width}-2 && $frac>0; $i++) {
		$frac *= $base;
		my $char = int $frac;
		$frac -= $char;
		$txt .= $char<10 ? $char : chr($char+55);
	} # fraction part

	$txt = "-".$txt if $sign;
	$txt .= 'e'.showval($exp, $base) if $exp;

	return $txt;
} # showval

sub showstack() {
	for (0..@stack-1) {
		addstr($set{height}-$_, 1, "$_: ".showval($stack[$_], $set{base}));
		clrtoeol;
	} # show stack
	clrtoeol($set{height}-@stack, 1);
} # showstack


my @modules;
eval 'require $_' ? push @modules, $_
: print STDERR "error loading $_\n".(join "", map "\t$_\n", split /\n/, $@)
	for glob "*.pm";

initscr;
ReadMode 3;  # cbreak mode
END {
	ReadMode 0;
	endwin;
} # restore terminal on quit

$set{height} = $LINES-2 if $LINES>=3;
$set{width} = $COLS if $COLS;
$_->() for @{ $hook{init} };


DRAW:
clear;
$_->() for @{ $hook{refresh} };
showstack();
addstr($set{height}+1, 0, "> ");  # prompt

LOOP:
while (1) {
	addstr($set{height}+1, 2, showval($val{i}, $set{base}));
	for my $cmd (@{ $hook{showentry} }) {
		addstr($_) if $_ = $cmd->();
	} # showentry functions
	addstr($val{alpha}) if exists $val{alpha};
	clrtoeol;
	refresh;

	my $key = ReadKey;
	if ($key eq chr 27) {
		$key .= $_ while defined ($_ = ReadKey(-1));  # read additional keys
	} # escape sequence
	$_ = $alias{$key} || $key; #if exists $alias{$key};  # command shortkeys
	$_ = delete $val{alpha} if $_ eq "enter" and exists $val{alpha};  # use manual command

	for my $cmd (@{ $hook{precmd} }) {
		next LOOP if $cmd->();
	} # precmd functions

	last if $_ eq 'quit';
	goto DRAW if $_ eq 'refresh';

	if (exists $val{alpha} or /^\033?[A-Z]$/) {
		if (defined $val{i}) {
			unshift @stack, $val{i};
			undef %val;
			showstack();
		} # enter present value

		if ($_ eq "back") {
			$val{alpha} = substr $val{alpha}, 0, -1 or delete $val{alpha};
		} # backspace
		elsif ($_ eq "drop") {
			delete $val{alpha};
		} # drop
		else {
			$val{alpha} .= $key =~ /^\033(.)/ ? uc $1 : lc $key;
		} # add character
	} # manual command entry

	elsif (/^\d$/) {
		$val{i} = 0 unless defined $val{i};
		$_ = -$_ if $val{i}<0;  # substract from negative value
		$val{i} = ($val{frac} and $val{frac} *= 10) ? $val{i}+$_/$val{frac}
			: $val{i}*10+$_;
	} # digit
	elsif ($_ eq '.') {
		$val{i} = 0 unless defined $val{i};
		$val{frac} = 1;
	} # decimal point
	elsif ($_ eq "eex") {
		$val{i} = 1 unless defined $val{i};
		#todo
	} # exponent
	elsif ($_ eq "chs" and defined $val{i}) {
		$val{i} = -$val{i};
	} # change sign
	elsif ($_ eq "back" and defined $val{i}) {
		$val{i} = ($val{frac} = int $val{frac}/10)
			? int($val{i}*$val{frac})/$val{frac} : int $val{i}/10
	} # backspace

	elsif (exists $action{$_}) {
		my ($type, $cmd) = @{ $action{$_} };
		unshift @stack, $action{enter}[1]->()
			if $type>0 and defined $val{i};  # auto enter
		if ($type>0 and $type>@stack) {
			error("insufficient stack arguments for operation");
			goto DRAW;
		} # insufficient arguments

		if ($type>=0) {
			$var{undo} = [@stack]; # if $_ ne 'undo';
			unshift @stack, $cmd->(splice @stack, 0, $type);
			showstack();
		} # stack-modifying operation
		else {
			$cmd->();
		} # harmless
	} # some operation

	else {
		error("unrecognised command: ".join(' ', map ord, split //, $_));
		goto DRAW; # screen messed up
	} # error
} # input loop

=cut
VERSION HISTORY
1.01 06-18       - start (curses, some basic commands)
1.02 06-20       - function keys select command/submenu from (sub)menu
                 - backspace to undo last digit
1.03 06-25       - values displayable in arbitrary base
                 - can enter fractions (.) and negative values (_)
1.04 08-04 14:45 - error dialog (don't mess up screen)
                 - manual command input using capital letters
                 - ^L redraws screen
 pre 09-09 22:00 - overhaul in stack handling
1.05 09-10 19:45 - hp48-like drop (backspace but not editing value)
                 - error on insufficient arguments for command
                 - command backspacing
                 - some unit conversion (mostly lengths) from menu
                 - q for sq(rt) (formerly quit, now only ^D/quit)
1.06 09-15 23:10 - menu contents in module
                 - new commands: a?(sin|cos|tan)h, inv, !, rand
                 - x and v shortkeys
1.07 09-24 23:50 - numeric modifiers hardcoded instead of in action hash
                 - action undo: last stack alteration can be undone
                 - enter on no value repeats last val on stack
                 - new commands: sr/sr, shortkeys ( )
1.08 09-26 22:10 - additional digits were not correctly applied to negative values
                 - negative numbers displayed correctly in different bases
                 - second undo redoes
                 - fixed %
                 - stack command (cursor up) cycles through values in stack
1.09 09-27 00:57 - all key aliases moved to module DCT::Bindings
     09-29 12:15 - number of menu items depends on screen width
     10-11 21:30 - hooks allowing for extra code at reload, showentry, and precmd
           21:50 - all menu related functions moved to menu.pm
           22:05 - unit conversion out of main program (entirely into unitconv.pm)
     10-12 01:50 - backspace becomes "back" (soft drop, like old "drop")
                 - normal drop command (alt+bs) removes input/stack value at once
           02:13 - $val{frac} default undefined instead of 0
=cut
