/
main.c
639 lines (460 loc) · 18.7 KB
/
main.c
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
#include <getopt.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <ncurses.h>
#include <unistd.h>
#include <signal.h>
#include "global.h"
#include "draw.h"
#include "history.h"
#include "numberstack.h"
#include "operators.h"
#include "parser.h"
#define VERSION "v3.0"
/*---- Function Prototypes ----------------------------------------*/
static void process_prompt(operation**, char*);
static void get_input(char*);
static void apply_operations(numberstack*, operation**);
static void exit_pcalc_success();
/*---- Main Logic -------------------------------------------------*/
int main(int argc, char* argv[])
{
// Set all long arguments that can be used
struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 'v'},
{"history", no_argument, NULL, 'i'},
{"binary", no_argument, NULL, 'b'},
{"hex", no_argument, NULL, 'x'},
{"ascii", no_argument, NULL, 'A'},
{"decimal", no_argument, NULL, 'd'},
{"operation", no_argument, NULL, 'o'},
{"symbol", no_argument, NULL, 's'},
{"colors", no_argument, NULL, 'c'},
{"alternate-colors", no_argument, NULL, 'a'},
{"no-interface", no_argument, NULL, 'n'},
{NULL, 0, NULL, 0}
};
// Get command line options to hide parts of the display
int opt;
while ((opt = getopt_long(argc, argv, "hvibxdoscan", long_options, NULL)) != -1) {
switch (opt) {
case 'h':
puts("Currently --help only displays the following information about the program options.");
puts("If you think something else should be here let us know @ github.com/alt-romes/programmer-calculator");
puts("The following options customize the interface: -ibxdos");
puts("--history = -i\t\t\tdisables command history");
puts("--binary = -b\t\t\tdisables binary representation");
puts("--hex = -x\t\t\tdisables hexadecimal representation");
puts("--ascii = -A\t\t\tdisables ASCII representation");
puts("--decimal = -d\t\t\tdisables decimal representation");
puts("--operation = -o\t\tdisables the display of the current operation");
puts("--symbol = -s\t\t\tdisables the display of helper command symbols");
puts("Other options:");
puts("--colors = -c\t\t\tenables colors");
puts("--alternate-colors = -a \tenables alternate colors for 1s and 0s in binary");
puts("--no-interface = -n\t\tdisables graphical interface");
exit(0);
break;
case 'v':
printf("Programmer calculator %s\n", VERSION);
exit(0);
break;
case 'i':
history_enabled = 0;
break;
case 'b':
binary_enabled = 0;
break;
case 'x':
hex_enabled = 0;
break;
case 'A':
ascii_enabled = 0;
break;
case 'd':
decimal_enabled = 0;
break;
case 'o':
operation_enabled = 0;
break;
case 's':
symbols_enabled = 0;
break;
case 'n':
use_interface = 0;
break;
case 'c':
colors_enabled = 1;
break;
case 'a':
colors_enabled = 1;
alt_colors_enabled = 1;
break;
default:
exit(EXIT_FAILURE);
}
}
init_gui(&displaywin, &inputwin);
// Set handler for CTRL+C to clean exit
signal(SIGINT, exit_pcalc_success);
/*
* The numberstack is used to store numbers used in calculations
* It's a normal stack data structure (LIFO) that holds uint64_t integers
* Check the stack.h file for its operations
*
* The operation structure holds information regarding the ASCII character the operation uses,
* The number of operands the operation takes, and the function to execute when applied
*
* Numbers get pushed to the numberstack "numbers", and operations are set as the "current_op"
*
* After receiving user input, if there's a current operation, the program compares the
* current stack size to the number of operands needed for that operation
*
* Should the operation be executed, the needed operands are popped from the stack,
* the operation is executed, and the result of the calculation is pushed to the stack
*/
numbers = create_numberstack(4);
//operation* current_op = NULL;
// Initalize history pointers with NULL (realloc will bahave like malloc)
history.records = NULL;
searchHistory.records = NULL;
// Start numberstack and history with 0
push_numberstack(numbers, 0);
add_to_history(&history, "0");
// Display number on top of the stack (0)
draw(numbers, current_op);
// No longer add empty string to history bottom, because the scroll was reversed
/* add_to_history(&searchHistory, ""); */
//Main Loop
for (;;) {
// Get input
char in[MAX_IN + 1];
// Make sure that if enter is pressed, a len == 0 null terminated string is in "in"
in[0] = '\0';
get_input(in);
process_prompt(¤t_op, in);
// Display number on top of the stack
draw(numbers, current_op);
}
endwin();
return 0;
}
static void process_prompt(operation** current_op, char* prompt) {
// Process input
// Try to find a known command and handle it
if (!strcmp(prompt, "quit") || !strcmp(prompt, "q") || !strcmp(prompt, "exit"))
exit_pcalc(0);
else if (!strcmp(prompt, "binary"))
binary_enabled = !binary_enabled;
else if (!strcmp(prompt, "hex"))
hex_enabled = !hex_enabled;
else if (!strcmp(prompt, "ascii"))
ascii_enabled = !ascii_enabled;
else if (!strcmp(prompt, "decimal"))
decimal_enabled = !decimal_enabled;
else if (!strcmp(prompt, "history"))
history_enabled = !history_enabled;
else if (!strcmp(prompt, "operation"))
operation_enabled = !operation_enabled;
else if (strstr(prompt, "bit") != NULL) {
// Command to change the number of bits
int requestedmasksize = atoi(prompt);
globalmasksize = requestedmasksize > DEFAULT_MASK_SIZE || requestedmasksize <= 0 ? DEFAULT_MASK_SIZE : requestedmasksize;
//globalmask cant be 0x16f's
globalmask = shr((DEFAULT_MASK_SIZE-globalmasksize), DEFAULT_MASK);
// apply mask to all numbers in stack
numberstack* aux = create_numberstack(numbers->size);
for (int i=0; i<numbers->size; i++)
push_numberstack(aux, *pop_numberstack(numbers) & globalmask);
for (int i=0; i<aux->size; i++)
push_numberstack(numbers, *pop_numberstack(aux) & globalmask);
}
else {
// It's not a known command - handle input as expression
// Remove any unknown characters from prompt
char* input = sanitize(prompt);
// We need to check if the last token is an operation before it gets freed,
// And save it, to set it as the current op after the input is processed
operation* suffix_op = NULL;
// Search for an operation symbol as the first token
/* There are four valid situations when an operation symbol
* is found in the tokens
*
* 1 - just the op i.e. "+"
* 2 - an expression ending with an op i.e. "2+"
* 3 - an op then an expression i.e. "+2"
* 4 - an expression i.e. "1+2*3" (this case is handled as a number)
*/
int inputlen = strlen(input);
if (input[0] != '\0' && strchr(ALL_OPS, input[0]) &&
(inputlen == 1 || (input[0] != NOT_SYMBOL && input[0] != TWOSCOMPLEMENT_SYMBOL && input[0] != SWAPENDIANNESS_SYMBOL))) {
// The input is either just an op, or an expression that starts with an op that isn't a prefix | case 1 or case 3
// Set the current operation as the operation structure for that symbol
*current_op = getopcode(input[0]);
// Add the operation to history
char opchar[2] = {input[0], '\0'};
add_to_history(&history, opchar);
// Duplicate the *tokens* string starting from the immediate next position, and free previous tokens afterwards
char* tokens_wout_op = strdup(input+1);
free(input);
input = tokens_wout_op;
// The length of the input is now 1 character smaller
inputlen--;
}
if (inputlen > 0 && strchr(ALL_OPS, input[inputlen-1])) {
// Last char is an op | case 2
// Set a new operation from the last symbol
suffix_op = getopcode(input[inputlen-1]);
// Remove the last token from the string
input[inputlen-1] = '\0';
inputlen--;
}
if (*current_op == NULL ||
(prompt[0] == '\0' && !(*current_op = NULL))) {
// There's no current operation and we're going to process a new number
// -> clear the stack and history before processing it
// Or the input was empty. When the input is empty set the operation to NULL
clear_numberstack(numbers);
clear_history();
}
if (inputlen > 0) {
// Add the tokens to history as a whole, for now...
add_to_history(&history, input);
// Parse the tokens into an expression
// This function will free *tokens*
exprtree expression = parse(input);
// Calculate the result of the expression
// The globalmask is applied inside calculate
uint64_t result = calculate(expression);
// The expression is no longer needed since we have its value
free_exprtree(expression);
// Push result to the numberstack
push_numberstack(numbers, result);
if (suffix_op != NULL) {
// Last token is an op | case 2
// Apply pending operation right away, to then set a new one
apply_operations(numbers, current_op);
// Set a new operation from the symbol
*current_op = suffix_op;
char opchar[2] = {suffix_op->character, '\0'};
add_to_history(&history, opchar);
}
}
else {
// The input expression generated an empty token string.
// Because parse() isn't called, we must free *tokens* manually
free(input);
total_tokens_freed++;
}
if (inputlen == 0 && *current_op == NULL) {
// The op is null (means we cleared the stack before reading a number)
// But we didn't read a number - so the stack is empty
// Add needed 0 to history and to stack
push_numberstack(numbers, 0);
add_to_history(&history, "0");
}
}
// Apply operations
apply_operations(numbers, current_op);
}
static void apply_operations(numberstack* numbers, operation** current_op) {
if (*current_op != NULL) {
unsigned char noperands = (*current_op)->noperands;
if (numbers->size >= noperands) {
uint64_t operands[2] = {0};
for (unsigned char i=0; i < noperands; i++)
operands[i] = *pop_numberstack(numbers);
uint64_t result = (*current_op)->execute(operands[0], operands[1]) & globalmask;
push_numberstack(numbers, result);
*current_op = NULL; // Set to invalid operation
}
}
}
static void get_input(char* in) {
char inp;
int history_counter = searchHistory.size;
// Is the cursor at the end of the line or somewhere in the middle
int browsing = 0;
// Collect input until enter is pressed
for (int pos = 0, len = 0; (inp = getchar()) != 13 && inp != '\n';) {
// Get max possible input length
int max = getmaxx(inputwin) - INPUT_START;
int searched = 0;
/* Check for forbidden keys
* -1 is a key that indicates the terminal got resized
* 5 is a key that indicates mouse wheel down
* 25 is a key that indicates mouse wheel up
* 27 is a key that indicates an arrow key was pressed
* 127 is a key that indicates the brackspace key was pressed
*/
switch(inp) {
case -1:
update_win_borders(numbers);
case 25:
continue;
break;
case 1:
//CTRL-A
pos = 0;
browsing = searched = 1;
break;
case 5:
//CTRL-E
pos = len;
browsing = 0;
searched = 1;
break;
case 4:
//CTRL-D
exit_pcalc(0);
break;
case 12:
//CTRL-L
clear_history();
pos = len = 0;
in[0] = '\0';
return;
break;
case 8:
//CTRL-Backspace
case 23:
//CTRL-W
inp = '\0';
if(pos == 0)
continue;
int jump = 0; //Amount of characters removed
while(in[pos-1] == ' ' && pos > 0) { //Delete trailing spaces
pos--; len--; //Delete 1 character
jump++;
}
while(in[pos-1] != ' ' && pos > 0) { //Delete last typed word
pos--; len--;
jump++;
}
if(browsing) {
for (int i = pos; i <= len + jump; i++) {
in[i] = in[i + jump - 1];
}
}
in[len + 1] = '\0';
break;
case 27:
getchar();
inp = getchar();
switch (inp) {
case 'A':
// Up arrow
browsehistory(in, -1, &history_counter);
len = strlen(in);
searched = 1;
browsing = 0;
break;
case 'B':
// Down arrow
browsehistory(in, 1, &history_counter);
len = strlen(in);
searched = 1;
browsing = 0;
break;
case 'C':
// Right arrow
if (browsing) { // The right arrow should only work while in the middle of the input
pos++;
// Exit browsing mode if the cursor is at the end of the input
if (pos == len) {
browsing = 0;
}
}
searched = 1;
break;
case 'D':
// Left arrow
if (pos != 0) {
pos--;
browsing = 1; // The left arrow will always be in browsing mode, so no need for a check
}
searched = 1;
break;
}
break;
case 127:
// Backspace
if (pos != 0) {
pos--;
len--;
inp = '\0';
}
else {
// Skip printing if backspace was pressed but nothing was done, otherwise a strange undefined character is printed
searched = 1;
}
break;
}
// Prevent user to input more than MAX_IN
if(!searched && len <= MAX_IN && (len <= max || !use_interface)) {
if (!browsing) {
// If the cursor is at the end of the text
// Append char to in array
in[pos] = inp;
in[++pos] = '\0';
len++; // Make sure that len is still equal to pos
if (inp == '\0') {
// Clear screen from previous input
sweepline(inputwin, 1, 22 + --len);
}
}
else {
// If the cursor is in the text, not at the end
if (inp == '\0') {
// Backspace
// Move all of in after pos one space back
for (int i = pos; i <= len; i++) {
in[i] = in[i + 1];
}
sweepline(inputwin, 1, 22 + len);
}
else {
// Everything except backspace
// Move all of in after pos one space forward to make room for the new input
len++;
for (int i = len; i > pos; i--) {
in[i] = in[i - 1];
}
// Append char to in array
in[pos++] = inp;
}
}
}
// This saves having to increment pos everytime len is incremented when youre not browsing
if (!browsing) { pos = len; }
// Clear input (only necessary because of the history feature)
sweepline(inputwin, 1, 22);
// Finaly print input
if (use_interface)
mvwprintw_colors(inputwin, 1, 22, COLOR_PAIR_DEFAULT, "%s", in);
else
mvwprintw(inputwin, 1, 22, "%s", in);
wmove(inputwin, 1, 22 + pos); // Move the cursor
wrefresh(inputwin);
}
if (in[0] != '\0' && (searchHistory.size == 0 || strcmp(in, searchHistory.records[searchHistory.size - 1]))) {
add_to_history(&searchHistory, in);
}
}
void exit_pcalc(int code) {
free_history(&history);
free_history(&searchHistory);
free_numberstack(numbers);
endwin();
switch (code) {
case 0: break;
case MEM_FAIL: fprintf(stderr, "OUT OF MEMORY\n"); break;
}
exit(code);
}
static void exit_pcalc_success() {
exit_pcalc(0);
}