calc.c (1704B)
1 #include <stdio.h> 2 #include <string.h> 3 #include <swk.h> 4 5 static int bufferi = 0; 6 static char buffer[256]; 7 8 static void button(SwkEvent *e) { 9 FILE *pd; 10 static char buffer2[sizeof(buffer)+32]; 11 if(e->type==EClick) { 12 int key = *e->box->text; 13 switch(key) { 14 case 'C': 15 bufferi = buffer[0] = 0; 16 break; 17 case '<': 18 if(bufferi>0) 19 buffer[--bufferi] = 0; 20 break; 21 case '=': 22 snprintf(buffer2, sizeof(buffer2), "echo '%s' | bc -q", buffer); 23 pd = popen(buffer2, "r"); 24 if(pd) { 25 fgets(buffer, sizeof(buffer), pd); 26 bufferi = strlen(buffer)-1; 27 buffer[bufferi] = 0; 28 pclose(pd); 29 } 30 break; 31 default: 32 if(bufferi<sizeof(buffer)) { 33 buffer[bufferi++] = key; 34 buffer[bufferi] = 0; 35 } 36 break; 37 } 38 } 39 return swk_bigbutton(e); 40 } 41 42 static SwkBox contents[] = { 43 SWK_BOX_NEWLINE(1), 44 { .cb=swk_label, .text=buffer }, 45 { .cb=button, .text="<" }, 46 SWK_BOX_NEWLINE(2), 47 { .cb=button, .text="1" }, 48 { .cb=button, .text="2" }, 49 { .cb=button, .text="3" }, 50 { .cb=button, .text="C" }, 51 SWK_BOX_NEWLINE(1), 52 { .cb=button, .text="4" }, 53 { .cb=button, .text="5" }, 54 { .cb=button, .text="6" }, 55 { .cb=button, .text="+" }, 56 SWK_BOX_NEWLINE(1), 57 { .cb=button, .text="7" }, 58 { .cb=button, .text="8" }, 59 { .cb=button, .text="9" }, 60 { .cb=button, .text="-" }, 61 SWK_BOX_NEWLINE(1), 62 { .cb=button, .text="%" }, 63 { .cb=button, .text="0" }, 64 { .cb=button, .text="/" }, 65 { .cb=button, .text="*" }, 66 SWK_BOX_NEWLINE(1), 67 { .cb=swk_separator }, 68 { .cb=button, .text="." }, 69 { .cb=button, .text="=" }, 70 { .cb=NULL } 71 }; 72 73 int main() { 74 SwkWindow w = { 75 .title="Calculator", 76 .boxes={contents,NULL}, 77 .box=contents, 78 }; 79 if(!swk_use(&w)) 80 return 1; 81 *buffer = 0; 82 swk_loop(); 83 return 0; 84 }