]> git.gir.st - solVItaire.git/blob - sol.c
argh! a semicolon too many!
[solVItaire.git] / sol.c
1 #define _DEFAULT_SOURCE /* for getopt, sigaction, usleep */
2 #include <poll.h>
3 #include <signal.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <sys/ioctl.h>
7 #include <time.h>
8 #include <termios.h>
9 #include <unistd.h>
10
11 #include "sol.h"
12 #include "schemes.h"
13
14 struct playfield f;
15 struct opts op;
16
17 // action table {{{
18 /* stores a function pointer for every takeable action; called by game loop */
19 int (*action[NUM_PLACES][10])(int,int,int) = {
20 #ifdef KLONDIKE
21 /* 1 2 3 4 5 6 7 stk wst fnd*/
22 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, nop, nop, t2f },
23 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, nop, nop, t2f },
24 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, nop, nop, t2f },
25 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, nop, nop, t2f },
26 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, nop, nop, t2f },
27 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, nop, nop, t2f },
28 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, nop, nop, t2f },
29 /*stk*/ { nop, nop, nop, nop, nop, nop, nop, nop, s2w, nop },
30 /*wst*/ { w2t, w2t, w2t, w2t, w2t, w2t, w2t, w2s, w2f, w2f },
31 /*fnd*/ { f2t, f2t, f2t, f2t, f2t, f2t, f2t, nop, nop, nop },
32 #elif defined SPIDER
33 /* 1 2 3 4 5 6 7 8 9 10*/
34 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
35 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
36 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
37 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t },
38 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t },
39 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t },
40 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t },
41 /* 8 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t },
42 /* 9 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t },
43 /*10 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f },
44 /*stk*/ { s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t },
45 #elif defined FREECELL
46 /* 1 2 3 4 5 6 7 8 cll fnd*/
47 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2c, t2f },
48 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2c, t2f },
49 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2c, t2f },
50 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2c, t2f },
51 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2c, t2f },
52 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2c, t2f },
53 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2c, t2f },
54 /* 8 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2c, t2f },
55 /*cll*/ { c2t, c2t, c2t, c2t, c2t, c2t, c2t, c2t, c2f, c2f },
56 /*fnd*/ { f2t, f2t, f2t, f2t, f2t, f2t, f2t, f2t, f2c, nop },
57 #endif
58 };
59 // }}}
60
61 // argv parsing, game loops, cleanup {{{
62 int main(int argc, char** argv) {
63 /* opinionated defaults: */
64 op.s = &unicode_large_color;
65 op.v = 1; /* enable fake visbell by default */
66 #ifdef SPIDER
67 op.m = MEDIUM;
68 #endif
69
70 int optget;
71 opterr = 0; /* don't print message on unrecognized option */
72 while ((optget = getopt (argc, argv, "+:hs:vbcmMV")) != -1) {
73 switch (optget) {
74 #ifdef SPIDER
75 case 's': /* number of suits */
76 switch (optarg[0]) {
77 case '1': op.m = EASY; break;
78 case '2': op.m = MEDIUM; break;
79 case '4': op.m = NORMAL; break;
80 default: goto error;
81 } break;
82 #endif
83 case 'b': op.s = &unicode_large_mono; break;
84 case 'c': op.s = &unicode_large_color; break;
85 case 'm': op.s = &unicode_small_mono; break; /* "mini, monochrome" */
86 case 'M': op.s = &unicode_small_color; break; /* "mini, colorful" */
87 case 'V': op.v = 0; break; /* WARN: experimental; might change */
88 case 'h': default: goto error;
89 error:
90 fprintf (stderr, SHORTHELP LONGHELP KEYHELP, argv[0]);
91 return optget != 'h';
92 }
93 }
94
95 signal_setup();
96 atexit (*quit);
97
98 signal_handler(SIGWINCH); /* initialize window size */
99
100 newgame:
101 screen_setup(1);
102
103 switch(sol()) {
104 case GAME_NEW: goto newgame;
105 case GAME_WON:
106 print_table(NO_HI, NO_HI);
107 win_anim();
108 if (getch(NULL)=='q') return 0;
109 goto newgame;
110 case GAME_QUIT: return 0;
111 }
112 }
113
114 #define is_tableu(where) (where <= TAB_MAX) // "card games helper functions"
115
116 int sol(void) {
117 int ret;
118 long seed = time(NULL);
119 restart:
120 free_undo(f.u);
121 deal(seed);
122
123 int from, to, opt;
124 for(;;) {
125 switch (get_cmd(&from, &to, &opt)) {
126 case CMD_MOVE:
127 ret = action[from][to](from,to,opt);
128 if (ret == ERR && is_tableu(from) && is_tableu(to))
129 /* try again with from/to swapped: */
130 ret = action[to][from](to,from,opt);
131 switch (ret) {
132 case OK: break;
133 case ERR: visbell(); break;
134 case WON: return GAME_WON;
135 }
136 break;
137 case CMD_JOIN:
138 switch (join(to)) {
139 case OK: break;
140 case ERR: visbell(); break;
141 case WON: return GAME_WON;
142 }
143 break;
144 case CMD_HINT: break;//TODO: show a possible (and sensible) move. if possible, involve active cursor
145 case CMD_UNDO: undo_pop(f.u); break;
146 case CMD_INVAL: visbell(); break;
147 case CMD_NEW: return GAME_NEW;
148 case CMD_AGAIN: goto restart;
149 case CMD_QUIT: return GAME_QUIT;
150 case CMD_HELP:
151 printf (KEYHELP "\nPress any key to continue.");
152 getch(NULL);
153 break;
154 }
155 }
156 }
157
158 void quit(void) {
159 screen_setup(0);
160 free_undo(f.u);
161 }
162 //}}}
163
164 // card games helper functions {{{
165 #define get_suit(card) \
166 ((card-1) % NUM_SUITS)
167 #define get_rank(card) \
168 ((card-1) / NUM_SUITS)
169 #define get_color(card) \
170 ((get_suit(card) ^ get_suit(card)>>1) & 1)
171
172 int find_top(card_t* pile) {
173 int i;
174 for(i=PILE_SIZE-1; i>=0 && !pile[i]; i--);
175 return i;
176 }
177 int first_movable(card_t* pile) {
178 /* NOTE: in FREECELL this does not take max_move into account! */
179 int i = 0;
180 for (;pile[i] && !is_movable(pile, i); i++);
181 return i;
182 }
183 int turn_over(card_t* pile) {
184 int top = find_top(pile);
185 if (pile[top] < 0) {
186 pile[top] *= -1;
187 return 1;
188 } else return 0;
189 }
190 int check_won(void) {
191 for (int pile = 0; pile < NUM_DECKS*NUM_SUITS; pile++)
192 if (f.f[pile][NUM_RANKS-1] == NO_CARD) return 0;
193
194 return 1;
195 }
196 int rank_next (card_t a, card_t b) {
197 return get_rank(a) == get_rank(b)-1;
198 }
199 int is_consecutive (card_t* pile, int pos) {
200 if (pos+1 >= PILE_SIZE) return 1; /* card is last */
201 if (pile[pos+1] == NO_CARD) return 1; /* card is first */
202
203 #if defined KLONDIKE || defined FREECELL
204 /* ranks consecutive? */
205 if (!rank_next(pile[pos+1], pile[pos])) return 0;
206 /* color opposite? */
207 if (get_color(pile[pos+1]) == get_color(pile[pos])) return 0;
208 #elif defined SPIDER
209 /* ranks consecutive? */
210 if (!rank_next(pile[pos+1], pile[pos])) return 0;
211 /* same suit? */
212 if (get_suit(pile[pos+1]) != get_suit(pile[pos])) return 0;
213 #endif
214
215 return 1;
216 }
217
218 int is_movable(card_t* pile, int n) {
219 #ifdef KLONDIKE
220 return(pile[n] > NO_CARD); /*non-movable cards don't exist in klondike*/
221 #elif defined SPIDER || defined FREECELL
222 int top = find_top(pile);
223 for (int i = top; i >= 0; i--) {
224 if (pile[i] <= NO_CARD) return 0; /*no card or card face down?*/
225 if (!is_consecutive(pile, i)) return 0;
226 if (i == n) return 1; /* card reached, must be movable */
227 }
228 return 0;
229 #endif
230 }
231 //}}}
232
233 // takeable actions {{{
234 #ifdef KLONDIKE
235 card_t stack_take(void) { /*NOTE: assert(f.w >= 0) */
236 card_t card = f.s[f.w];
237 /* move stack one over, so there are no gaps in it: */
238 for (int i = f.w; i < f.z-1; i++)
239 f.s[i] = f.s[i+1];
240 f.z--;
241 f.w--; /* make previous card visible again */
242 return card;
243 }
244 int t2f(int from, int to, int opt) { /* tableu to foundation */
245 (void) to; (void) opt; /* don't need */
246 int top_from = find_top(f.t[from]);
247 to = get_suit(f.t[from][top_from]);
248 int top_to = find_top(f.f[to]);
249 if ((top_to < 0 && get_rank(f.t[from][top_from]) == RANK_A)
250 || (top_to >= 0 && rank_next(f.f[to][top_to],f.t[from][top_from]))) {
251 f.f[to][top_to+1] = f.t[from][top_from];
252 f.t[from][top_from] = NO_CARD;
253 undo_push(from, FOUNDATION, to,
254 turn_over(f.t[from]));
255 if (check_won()) return WON;
256 return OK;
257 } else return ERR;
258 }
259 int w2f(int from, int to, int opt) { /* waste to foundation */
260 (void) from; (void) to; (void) opt; /* don't need */
261 if (f.w < 0) return ERR;
262 to = get_suit(f.s[f.w]);
263 int top_to = find_top(f.f[to]);
264 if ((top_to < 0 && get_rank(f.s[f.w]) == RANK_A)
265 || (top_to >= 0 && rank_next(f.f[to][top_to], f.s[f.w]))) {
266 undo_push(WASTE, FOUNDATION, f.w | to<<16, 0);//ugly encoding :|
267 f.f[to][top_to+1] = stack_take();
268 if (check_won()) return WON;
269 return OK;
270 } else return ERR;
271
272 }
273 int s2w(int from, int to, int opt) { /* stock to waste */
274 (void) from; (void) to; (void) opt; /* don't need */
275 if (f.z == 0) return ERR;
276 f.w++;
277 if (f.w == f.z) f.w = -1;
278 return OK;
279 }
280 int w2s(int from, int to, int opt) { /* waste to stock (undo stock to waste) */
281 (void) from; (void) to; (void) opt; /* don't need */
282 if (f.z == 0) return ERR;
283 f.w--;
284 if (f.w < -1) f.w = f.z-1;
285 return OK;
286 }
287 int f2t(int from, int to, int opt) { /* foundation to tableu */
288 (void) from; /* don't need */
289 int top_to = find_top(f.t[to]);
290 from = opt;
291 int top_from = find_top(f.f[from]);
292
293 if ((get_color(f.t[to][top_to]) != get_color(f.f[from][top_from]))
294 && (rank_next(f.f[from][top_from], f.t[to][top_to]))) {
295 f.t[to][top_to+1] = f.f[from][top_from];
296 f.f[from][top_from] = NO_CARD;
297 undo_push(FOUNDATION, to, from, 0);
298 return OK;
299 } else return ERR;
300 }
301 int w2t(int from, int to, int opt) { /* waste to tableu */
302 (void) from; (void) opt; /* don't need */
303 if (f.w < 0) return ERR;
304 int top_to = find_top(f.t[to]);
305 if (((get_color(f.t[to][top_to]) != get_color(f.s[f.w]))
306 && (rank_next(f.s[f.w], f.t[to][top_to])))
307 || (top_to < 0 && get_rank(f.s[f.w]) == RANK_K)) {
308 undo_push(WASTE, to, f.w, 0);
309 f.t[to][top_to+1] = stack_take();
310 return OK;
311 } else return ERR;
312 }
313 int t2t(int from, int to, int opt) { /* tableu to tableu */
314 (void) opt; /* don't need */
315 int top_to = find_top(f.t[to]);
316 int top_from = find_top(f.t[from]);
317 int count = 0; //NOTE: could probably be factored out
318 for (int i = top_from; i >=0; i--) {
319 if (((get_color(f.t[to][top_to]) != get_color(f.t[from][i]))
320 && (rank_next(f.t[from][i], f.t[to][top_to]))
321 && f.t[from][i] > NO_CARD) /* card face up? */
322 || (top_to < 0 && get_rank(f.t[from][i]) == RANK_K)) {
323 /* move cards [i..top_from] to their destination */
324 for (;i <= top_from; i++) {
325 top_to++;
326 f.t[to][top_to] = f.t[from][i];
327 f.t[from][i] = NO_CARD;
328 count++;
329 }
330 undo_push(from, to, count,
331 turn_over(f.t[from]));
332 return OK;
333 }
334 }
335 return ERR; /* no such move possible */
336 }
337 #elif defined SPIDER
338 int remove_if_complete (int pileno) { //cleanup!
339 card_t* pile = f.t[pileno];
340 /* test if K...A complete; move to foundation if so */
341 int top_from = find_top(pile);
342 if (get_rank(pile[top_from]) != RANK_A) return 0;
343 for (int i = top_from; i>=0; i--) {
344 if (!is_consecutive (pile, i)) return 0;
345 if (i+RANK_K == top_from /* if ace to king: remove it */
346 && get_rank(pile[top_from-RANK_K]) == RANK_K) {
347 for(int i=top_from, j=0; i>top_from-NUM_RANKS; i--,j++){
348 f.f[f.w][j] = pile[i];
349 pile[i] = NO_CARD;
350 }
351 undo_push(pileno, FOUNDATION, f.w,
352 turn_over(pile));
353 f.w++;
354 return 1;
355 }
356 }
357
358 return 0;
359 }
360 int t2t(int from, int to, int opt) { //in dire need of cleanup
361 int top_from = find_top(f.t[from]);
362 int top_to = find_top(f.t[to]);
363 int empty_to = (top_to < 0)? opt: -1; /* empty pile? */
364 int count = 0; //NOTE: could probably be factored out
365
366 for (int i = top_from; i >= 0; i--) {
367 if (!is_consecutive(f.t[from], i)) break;
368
369 /* is consecutive OR to empty pile and rank ok? */
370 if (rank_next(f.t[from][i], f.t[to][top_to])
371 || (empty_to >= RANK_A && get_rank(f.t[from][i]) == empty_to)) {
372 for (;i <= top_from; i++) {
373 top_to++;
374 f.t[to][top_to] = f.t[from][i];
375 f.t[from][i] = NO_CARD;
376 count++;
377 }
378 undo_push(from, to, count,
379 turn_over(f.t[from]));
380 remove_if_complete(to);
381 if (check_won()) return WON;
382 return OK;
383 }
384 }
385
386 return ERR; /* no such move possible */
387 }
388 int s2t(int from, int to, int opt) {
389 (void) from; (void) to; (void) opt; /* don't need */
390 if (f.z <= 0) return ERR; /* stack out of cards */
391 for (int pile = 0; pile < NUM_PILES; pile++)
392 if (f.t[pile][0]==NO_CARD) return ERR; /*no piles may be empty*/
393 for (int pile = 0; pile < NUM_PILES; pile++) {
394 f.t[pile][find_top(f.t[pile])+1] = f.s[--f.z];
395 remove_if_complete(pile);
396 if (check_won()) return WON;
397 }
398 undo_push(STOCK, TABLEU, 1, 0);/*NOTE: puts 1 card on each tableu pile*/
399 return OK;
400 }
401 int t2f(int from, int to, int opt) {
402 (void) to; (void) opt; /* don't need */
403 /* manually retrigger remove_if_complete() (e.g. after undo_pop) */
404 return remove_if_complete(from)?OK:ERR;
405 }
406 #elif defined FREECELL
407 int max_move(int from, int to) {
408 /* returns the maximum number of cards that can be moved */
409 /* see also: https://boardgames.stackexchange.com/a/45157/26498 */
410 int free_tabs = 0, free_cells = 0;
411 for (int i = 0; i < NUM_PILES; i++) free_tabs += f.t[i][0] == NO_CARD;
412 for (int i = 0; i < NUM_CELLS; i++) free_cells += f.s[i] == NO_CARD;
413
414 /* don't count the tableau we are moving to: */
415 if (to >= 0 && f.t[to][0] == NO_CARD) free_tabs--;
416
417 /* theoretic maximum is limited by the number of cards on the pile */
418 int max_theory = (1<<free_tabs) * (free_cells + 1);
419 int max_effective = 1 + find_top(f.t[from]) - first_movable(f.t[from]);
420 return max_effective < max_theory? max_effective : max_theory;
421 }
422 //TODO FREECELL: auto move to tableu after each move (not all cards possible, only when it is the smallest rank still on the board)
423 int t2t(int from, int to, int opt) {
424 int top_to = find_top(f.t[to]);
425 int top_from = find_top(f.t[from]);
426 int count = 0; //NOTE: could probably be factored out
427 int cards = max_move(from, to);
428 if (top_to < 0) { /* moving to empty pile? */
429 if (opt > cards)
430 return ERR; /* cannot execute move */
431 cards = opt; /* user wants to move n cards*/
432 }
433
434 for (int i = top_from; i >=0; i--) {
435 if (cards-->0/*enough space and not more attempted than wanted*/
436 && ((top_to >= 0 /* if destn. not empty: check rank/color */
437 && ((get_color(f.t[to][top_to]) != get_color(f.t[from][i]))
438 && (rank_next(f.t[from][i], f.t[to][top_to]))))
439 || (top_to < 0 && !cards))) {/*if dest empty and right # cards*/
440 /* move cards [i..top_from] to their destination */
441 for (;i <= top_from; i++) {
442 top_to++;
443 f.t[to][top_to] = f.t[from][i];
444 f.t[from][i] = NO_CARD;
445 count++;
446 }
447 undo_push(from, to, count, 0);
448 return OK;
449 }
450 }
451 return ERR; /* no such move possible */
452 }
453 int t2f(int from, int to, int opt) { /* 1:1 copy from KLONDIKE */
454 (void) to; (void) opt; /* don't need */
455 int top_from = find_top(f.t[from]);
456 to = get_suit(f.t[from][top_from]);
457 int top_to = find_top(f.f[to]);
458 if ((top_to < 0 && get_rank(f.t[from][top_from]) == RANK_A)
459 || (top_to >= 0 && rank_next(f.f[to][top_to],f.t[from][top_from]))) {
460 f.f[to][top_to+1] = f.t[from][top_from];
461 f.t[from][top_from] = NO_CARD;
462 undo_push(from, FOUNDATION, to, 0);
463 if (check_won()) return WON;
464 return OK;
465 } else return ERR;
466 }
467 int f2t(int from, int to, int opt) {
468 (void) from; /* don't need */
469 int top_to = find_top(f.t[to]);
470 from = opt;
471 int top_from = find_top(f.f[from]);
472
473 if (top_to < 0 /* empty tableu? */
474 ||((get_color(f.t[to][top_to]) != get_color(f.f[from][top_from]))
475 && (rank_next(f.f[from][top_from], f.t[to][top_to])))) {
476 f.t[to][top_to+1] = f.f[from][top_from];
477 f.f[from][top_from] = NO_CARD;
478 undo_push(FOUNDATION, to, from, 0);
479 return OK;
480 } else return ERR;
481 }
482 int t2c(int from, int to, int opt) {
483 (void) to; (void) opt; /* don't need */
484 /* is a cell free? */
485 if (f.w == (1<<NUM_CELLS)-1)
486 return ERR;
487 for (to = 0; to < NUM_CELLS; to++)
488 if (!(f.w>>to&1)) break;
489 /* move 1 card */
490 int top_from = find_top(f.t[from]);
491 f.s[to] = f.t[from][top_from];
492 f.t[from][top_from] = NO_CARD;
493 f.w |= 1<<to; /* mark cell as occupied */
494 undo_push(from, STOCK, to, 0);
495
496 return OK;
497 }
498 int c2t(int from, int to, int opt) {
499 (void) from; /* don't need */
500 int top_to = find_top(f.t[to]);
501 from = opt;
502
503 if (top_to < 0 /* empty tableu? */
504 ||((get_color(f.t[to][top_to]) != get_color(f.s[from]))
505 && (rank_next(f.s[from], f.t[to][top_to])))) {
506 f.t[to][top_to+1] = f.s[from];
507 f.s[from] = NO_CARD;
508 f.w &= ~(1<<from); /* mark cell as free */
509 undo_push(STOCK, to, from, 0);
510 return OK;
511 } else return ERR;
512 return ERR;
513 }
514 int c2f(int from, int to, int opt) {
515 (void) from; (void) to; /* don't need */
516 from = opt;
517 to = get_suit(f.s[from]);
518 int top_to = find_top(f.f[to]);
519 if ((top_to < 0 && get_rank(f.s[from]) == RANK_A)
520 || (top_to >= 0 && rank_next(f.f[to][top_to],f.s[from]))) {
521 f.f[to][top_to+1] = f.s[from];
522 f.s[from] = NO_CARD;
523 f.w &= ~(1<<from); /* mark cell as free */
524 undo_push(STOCK, FOUNDATION, from | to<<16, 0);
525 if (check_won()) return WON;
526 return OK;
527 } else return ERR;
528 }
529 int f2c(int from, int to, int opt) {
530 (void) from; (void) to; /* don't need */
531 /* is a cell free? */
532 if (f.w == (1<<NUM_CELLS)-1)
533 return ERR;
534 for (to = 0; to < NUM_CELLS; to++)
535 if (!(f.w>>to&1)) break;
536 /* move 1 card */
537 from = opt;
538 int top_from = find_top(f.f[from]);
539 f.s[to] = f.f[from][top_from];
540 f.f[from][top_from] = NO_CARD;
541 f.w |= 1<<to; /* mark cell as occupied */
542 undo_push(FOUNDATION, STOCK, from | to<<16, 0);
543
544 return OK;
545 }
546 #endif
547
548 //TODO: generalize prediction engine for CMD_HINT
549 #ifdef KLONDIKE
550 #define would_complete(pile) 0
551 #elif defined SPIDER
552 #define would_complete(pile) \
553 (get_rank(f.t[pile][r[pile].top]) == RANK_A \
554 && get_rank(f.t[to][bottom_to]) == RANK_K)
555 #elif defined FREECELL
556 #define would_complete(pile) 0
557 #endif
558 #define would_turn(pile) \
559 (f.t[pile][r[pile].pos-1] < 0)
560 #define would_empty(pile) \
561 (r[pile].pos == 0)
562
563 int join(int to) {
564 int top_to = find_top(f.t[to]);
565 #ifdef SPIDER
566 int bottom_to = first_movable(f.t[to]);
567 #endif
568
569 #ifdef KLONDIKE
570 if (to == WASTE || to == STOCK) return ERR; /*why would you do that!?*/
571
572 if (to == FOUNDATION) {
573 int status = ERR;
574 for (int i = 0; i <= TAB_MAX; i++)
575 switch ((i?t2f:w2f)(i-1, FOUNDATION, 0)) {
576 case WON: return WON;
577 case OK: status = OK;
578 case ERR: /* nop */;
579 }
580 return status;
581 }
582
583 if (top_to < 0) { /* move a king to empty pile: */
584 for (int i = 0; i < TAB_MAX; i++) {
585 if (f.t[i][0] < 0) /* i.e. would turn? */
586 if (t2t(i, to, 0) == OK) return OK;
587 }
588 return w2t(WASTE, to, 0);
589 }
590 #endif
591
592 struct rating {
593 int ok:1; /* card to move in pile? */
594 int above; /* number of movable cards above */
595 int below; /* number of cards below ours */
596 int pos; /* where the card to move is in the pile */
597 int top; /* find_top() */
598 } r[NUM_PILES] = {{0}};
599 int complete = 0;/* SPIDER: true if any pile would complete a stack */
600 int turn = 0; /* SPIDER: true if any pile would turn_over */
601 int empty = 0; /* true if any pile would become empty */
602
603 /* 1. rate each pile: */
604 #ifdef SPIDER
605 if (top_to < 0) {
606 for (int pile = 0; pile < NUM_PILES; pile++) {
607 if (pile == to) continue;
608 int top = find_top(f.t[pile]);
609 int bottom = first_movable(f.t[pile]);
610 r[pile].pos = bottom; /* need for would_empty */
611
612 if (top < 0) continue; /* no cards to move */
613 if (would_empty(pile)) continue; /* doesn't help */
614
615 r[pile].ok++;
616 r[pile].above = 0; /* always take as many as possible */
617 r[pile].below = top - bottom;
618 r[pile].top = top;
619 complete |= would_complete(pile); /* never happens */
620 turn |= would_turn(pile);
621 empty |= would_empty(pile);
622 }
623 } else
624 #endif
625 for (int pile = 0; pile < NUM_PILES; pile++) {
626 r[pile].top = r[pile].pos = find_top(f.t[pile]);
627 /* backtrack until we find a compatible-to-'to'-pile card: */
628 while (r[pile].pos >= 0 && is_movable(f.t[pile], r[pile].pos)) {
629 int rankdiff = get_rank(f.t[pile][r[pile].pos])
630 - get_rank(f.t[to][top_to]);
631 if (rankdiff >= 0) break; /* past our card */
632 if (rankdiff == -1 /* rank matches */
633 #ifdef KLONDIKE
634 && get_color(f.t[pile][r[pile].pos]) /* color OK */
635 != get_color(f.t[to][top_to])
636 #elif defined SPIDER
637 && get_suit(f.t[pile][r[pile].pos]) /* color OK */
638 == get_suit(f.t[to][top_to])
639 #endif
640 ) {
641 r[pile].ok++;
642 complete |= would_complete(pile);
643 turn |= would_turn(pile);
644 empty |= would_empty(pile);
645 for (int i = r[pile].pos; i >= 0; i--)
646 if (is_movable(f.t[pile], i-1))
647 r[pile].above++;
648 else break;
649 break;
650 }
651 r[pile].pos--;
652 r[pile].below++;
653 }
654 }
655
656 /* 2. find optimal pile: (optimized for spider) */
657 //todo: in spider, prefer longest piles if above==0 (faster completions)
658 int from = -1;
659 for (int pile = 0, above = 99, below = 99; pile < NUM_PILES; pile++) {
660 if (!r[pile].ok) continue;
661 /* don't bother if another pile would be better: prefer ... */
662 /* ... to complete a stack: */
663 if (!would_complete(pile) && complete) continue;
664 /* ... emptying piles: */
665 if (!would_empty(pile) && empty && !complete) continue;
666 /* ... to turn_over: */
667 if (!would_turn(pile) && turn && !complete && !empty) continue;
668 /* ... not to rip apart too many cards: */
669 if (r[pile].above > above) continue;
670 /* if tied, prefer ... */
671 if (r[pile].above == above
672 /* ... larger pile if destination is empty */
673 && (top_to < 0? r[pile].below < below
674 /* ... shorter pile otherwise */
675 : r[pile].below > below))
676 continue;
677
678 from = pile;
679 above = r[pile].above;
680 below = r[pile].below;
681 }
682
683 /* 3. move cards over and return: */
684 #ifdef KLONDIKE
685 /* prefer waste if it wouldn't turn_over: */
686 /* NOTE: does not attempt to take from froundation */
687 if (!turn && w2t(WASTE, to, 0) == OK) //TODO: gives higher priority to waste than to empty!
688 return OK;
689 if (from < 0) /* nothing found */
690 return ERR;
691 return t2t(from, to, 0);
692 #elif defined SPIDER
693 if (from < 0) /* nothing found */
694 return ERR;
695 int bottom = first_movable(f.t[from]);
696 return t2t(from, to, get_rank(f.t[from][bottom]));
697 #elif defined FREECELL
698 (void)from;
699 return ERR; //TODO FREECELL: implement join
700 #endif
701 }
702 #undef would_empty
703 #undef would_turn
704 #undef would_complete
705 int nop(int from, int to, int opt) { (void)from;(void)to;(void)opt;return ERR; }
706 // }}}
707
708 // keyboard input handling {{{
709 // cursor functions{{{
710 #ifdef KLONDIKE
711 void cursor_left (struct cursor* cursor) {
712 op.h = 1;
713 if (is_tableu(cursor->pile)) {
714 if (cursor->pile > 0) cursor->pile--;
715 cursor->opt = 0;
716 } else { /* stock/waste/foundation*/
717 switch (cursor->pile) {
718 case WASTE: cursor->pile = STOCK; cursor->opt = 0; break;
719 case FOUNDATION:
720 if (cursor->opt <= 0)
721 cursor->pile = WASTE;
722 else
723 cursor->opt--;
724 }
725 }
726 }
727 void cursor_down (struct cursor* cursor) {
728 op.h = 1;
729 if (!is_tableu(cursor->pile)) {
730 switch (cursor->pile) {
731 case STOCK: cursor->pile = TAB_1; break;
732 case WASTE: cursor->pile = TAB_2; break;
733 case FOUNDATION:
734 cursor->pile = TAB_4 + cursor->opt;
735 }
736 cursor->opt = 0;
737 }
738 }
739 void cursor_up (struct cursor* cursor) {
740 op.h = 1;
741 if (is_tableu(cursor->pile)) {
742 switch (cursor->pile) { //ugly :|
743 case TAB_1: cursor->pile = STOCK; break;
744 case TAB_2: cursor->pile = WASTE; break;
745 case TAB_3: cursor->pile = WASTE; break;
746 case TAB_4: case TAB_5: case TAB_6: case TAB_7:
747 cursor->opt=cursor->pile-TAB_4;
748 cursor->pile = FOUNDATION;
749 break;
750 }
751 }
752 }
753 void cursor_right (struct cursor* cursor) {
754 op.h = 1;
755 if (is_tableu(cursor->pile)) {
756 if (cursor->pile < TAB_MAX) cursor->pile++;
757 cursor->opt = 0;
758 } else {
759 switch (cursor->pile) {
760 case STOCK: cursor->pile = WASTE; break;
761 case WASTE: cursor->pile = FOUNDATION;cursor->opt = 0; break;
762 case FOUNDATION:
763 if (cursor->opt < NUM_SUITS-1)
764 cursor->opt++;
765 }
766 }
767 }
768 #elif defined SPIDER
769 /*NOTE: one can't highlight the stock due to me being too lazy to implement it*/
770 void cursor_left (struct cursor* cursor) {
771 op.h = 1;
772 if (cursor->pile > 0) cursor->pile--;
773 cursor->opt = 0;
774 }
775 void cursor_down (struct cursor* cursor) {
776 op.h = 1;
777 int first = first_movable(f.t[cursor->pile]);
778 int top = find_top(f.t[cursor->pile]);
779 if (first + cursor->opt < top)
780 cursor->opt++;
781 }
782 void cursor_up (struct cursor* cursor) {
783 op.h = 1;
784 if (cursor->opt > 0) cursor->opt--;
785 }
786 void cursor_right (struct cursor* cursor) {
787 op.h = 1;
788 if (cursor->pile < TAB_MAX) cursor->pile++;
789 cursor->opt = 0;
790 }
791 #elif defined FREECELL
792 void cursor_left (struct cursor* cursor) {
793 op.h = 1;
794 if (is_tableu(cursor->pile)) {
795 if (cursor->pile > 0) cursor->pile--;
796 cursor->opt = 0;
797 } else { /* cells/foundation*/
798 switch (cursor->pile) {
799 case STOCK:
800 if (cursor->opt > 0)
801 cursor->opt--;
802 break;
803 case FOUNDATION:
804 if (cursor->opt <= 0) {
805 cursor->pile = STOCK;
806 cursor->opt = 3;
807 } else {
808 cursor->opt--;
809 }
810 }
811 }
812 }
813 void cursor_down (struct cursor* cursor) {
814 op.h = 1;
815 if (is_tableu(cursor->pile)) {
816 if (cursor->opt < max_move(cursor->pile, -1)-1)
817 cursor->opt++;
818 } else {
819 cursor->pile = cursor->opt+NUM_CELLS*(cursor->pile==FOUNDATION);
820 cursor->opt = 0;
821 }
822 }
823 void cursor_up (struct cursor* cursor) {
824 op.h = 1;
825 if (is_tableu(cursor->pile)) {
826 if (cursor->opt > 0) {
827 cursor->opt--;
828 } else {
829 switch (cursor->pile) {
830 case TAB_1: case TAB_2: case TAB_3: case TAB_4:
831 cursor->opt = cursor->pile; /*assumes TAB_1==0*/
832 cursor->pile = STOCK;
833 break;
834 case TAB_5: case TAB_6: case TAB_7: case TAB_8:
835 cursor->opt = cursor->pile - NUM_CELLS;
836 cursor->pile = FOUNDATION;
837 }
838 }
839 }
840 }
841 void cursor_right (struct cursor* cursor) {
842 op.h = 1;
843 if (is_tableu(cursor->pile)) {
844 if (cursor->pile < TAB_MAX) cursor->pile++;
845 cursor->opt = 0;
846 } else {
847 switch (cursor->pile) {
848 case STOCK:
849 if (cursor->opt < NUM_SUITS-1) {
850 cursor->opt++;
851 } else {
852 cursor->pile = FOUNDATION;
853 cursor->opt = 0;
854 } break;
855 case FOUNDATION:
856 if (cursor->opt < NUM_SUITS-1)
857 cursor->opt++;
858 }
859 }
860 }
861 #endif
862 void cursor_to (struct cursor* cursor, int pile) {
863 op.h = 1;
864 cursor->pile = pile;
865 cursor->opt = 0;
866 }
867 int set_mouse(int pile, int* main, int* opt) {
868 //TODO: this should set cursor.opt, so card selector choice dialog does not trigger!
869 op.h = 0;
870 if (pile < 0) return 1;
871 *main = pile;
872 #ifdef KLONDIKE
873 if (pile >= FOUNDATION)//TODO: check upper bound!
874 *main = FOUNDATION,
875 *opt = pile - FOUNDATION;
876 #elif defined SPIDER
877 (void)opt;
878 #elif defined FREECELL
879 if (pile > TAB_MAX) {
880 *main = pile-STOCK < NUM_CELLS? STOCK : FOUNDATION;
881 *opt = (pile-STOCK) % 4;
882 }
883 #endif
884 return 0;
885 }
886 //}}}
887 int get_cmd (int* from, int* to, int* opt) {
888 int _f, t;
889 unsigned char mouse[6] = {0}; /* must clear [3]! */
890 struct cursor inactive = {-1,-1};
891 static struct cursor active = {0,0};
892 if (is_tableu(active.pile))
893 active.opt = 0;
894
895 /***/
896 from_l: print_table(&active, &inactive);
897 _f = getch(mouse);
898
899 switch (_f) {
900 /* direct addressing: */
901 case '1': *from = TAB_1; break;
902 case '2': *from = TAB_2; break;
903 case '3': *from = TAB_3; break;
904 case '4': *from = TAB_4; break;
905 case '5': *from = TAB_5; break;
906 case '6': *from = TAB_6; break;
907 case '7': *from = TAB_7; break;
908 #ifdef SPIDER
909 case '8': *from = TAB_8; break;
910 case '9': *from = TAB_9; break;
911 case '0': *from = TAB_10;break;
912 #elif defined FREECELL
913 case '8': *from = TAB_8; break;
914 case '9': *from = STOCK; break;
915 case '0': *from = FOUNDATION; break;
916 #elif defined KLONDIKE
917 case '9': *from = WASTE; break;
918 case '0': *from = FOUNDATION; break;
919 case '8': /* fallthrough */
920 #endif
921 #ifndef FREECELL
922 case '\n': *from = STOCK; break;
923 #endif
924 /* cursor keys addressing: */
925 case KEY_LEFT:
926 case 'h': cursor_left (&active); goto from_l;
927 case KEY_DOWN:
928 case 'j': cursor_down (&active); goto from_l;
929 case KEY_UP:
930 case 'k': cursor_up (&active); goto from_l;
931 case KEY_RIGHT:
932 case 'l': cursor_right(&active); goto from_l;
933 case KEY_HOME:
934 case 'H': cursor_to(&active,TAB_1); goto from_l; /* leftmost tableu */
935 case KEY_END:
936 case 'L': cursor_to(&active,TAB_MAX);goto from_l; /* rigthmost tableu */
937 case KEY_INS:
938 case 'M': cursor_to(&active,TAB_MAX/2); goto from_l; /* center tableu */
939 case ' ': /* continue with second cursor */
940 *from = active.pile;
941 #ifdef KLONDIKE
942 *opt = active.opt; /* when FOUNDATION */
943 #endif
944 inactive = active;
945 break;
946 #ifdef FREECELL
947 //TODO: instead of backspace, use doublespace (first try x2t, then x2c)
948 case 0x7f: case '\b': /* backspace key sends DEL on most terminals */
949 if (active.pile == STOCK) return CMD_INVAL;
950 *from = active.pile;
951 *opt = active.opt; /* when FOUNDATION */
952 *to = STOCK;
953 return CMD_MOVE;
954 case '\n': return CMD_INVAL;//TODO: move card to foundation?
955 #endif
956 /* mouse addressing: */
957 case MOUSE_MIDDLE: return CMD_NONE;
958 case MOUSE_RIGHT:
959 if (set_mouse(term2pile(mouse), to, opt))
960 return CMD_INVAL;
961 goto join_l;
962 case MOUSE_LEFT:
963 if (set_mouse(term2pile(mouse), from, opt))
964 return CMD_INVAL;
965 if (!is_tableu(*from))
966 inactive.opt = *opt; /* prevents card selector dialog */
967 break;
968 /* misc keys: */
969 case ':':
970 {char buf[256];
971 fprintf (stderr, ":");
972 raw_mode(0); /* turn on echo */
973 fgets (buf, 256, stdin);
974 raw_mode(1);
975 switch(buf[0]) {
976 case 'q': return CMD_QUIT;
977 case 'n': return CMD_NEW;
978 case 'r': return CMD_AGAIN;
979 case 'h': return CMD_HELP;
980 default: return CMD_INVAL;
981 }}
982 case 'J':
983 *to = active.pile;
984 join_l:
985 #ifdef KLONDIKE
986 if (*to == FOUNDATION) return CMD_JOIN;
987 #endif
988 if (*to > TAB_MAX) return CMD_INVAL;
989 return CMD_JOIN;
990 case 'K': /* fallthrough */
991 case '?': return CMD_HINT;
992 case 'u': return CMD_UNDO;
993 case 002: return CMD_NONE; /* sent by SIGWINCH */
994 case EOF: return CMD_NONE; /* sent by SIGCONT */
995 default: return CMD_INVAL;
996 }
997 inactive.pile = *from; /* for direct addressing highlighting */
998 if (is_tableu(*from) && f.t[*from][0] == NO_CARD) return CMD_INVAL;
999
1000 #ifndef FREECELL
1001 if (*from == STOCK) {
1002 *to = WASTE;
1003 return CMD_MOVE;
1004 }
1005 #endif
1006
1007 /***/
1008 to_l: print_table(&active, &inactive);
1009 t = getch(mouse);
1010
1011 switch (t) {
1012 case KEY_LEFT:
1013 case 'h': cursor_left (&active); goto to_l;
1014 case KEY_DOWN:
1015 case 'j': cursor_down (&active); goto to_l;
1016 case KEY_UP:
1017 case 'k': cursor_up (&active); goto to_l;
1018 case KEY_RIGHT:
1019 case 'l': cursor_right(&active); goto to_l;
1020 case KEY_HOME:
1021 case 'H': cursor_to(&active,TAB_1); goto to_l;
1022 case KEY_END:
1023 case 'L': cursor_to(&active,TAB_MAX); goto to_l;
1024 case KEY_INS:
1025 case 'M': cursor_to(&active,TAB_MAX/2); goto to_l;
1026 case 'J': /* fallthrough; just join selected pile */
1027 case ' ':
1028 *to = active.pile;
1029 break; /* continues with the foundation/empty tableu check */
1030 case MOUSE_MIDDLE:
1031 case MOUSE_RIGHT: return CMD_NONE;
1032 case MOUSE_LEFT:
1033 if (set_mouse(term2pile(mouse), to, opt))
1034 return CMD_INVAL;
1035 /*#ifdef SPIDER
1036 //TODO: set opt if to field is empty; suppress "up do" dialog from below
1037 if (is_tableu(*to) && f.t[*to][0] == NO_CARD) {
1038 int top = find_top(f.t[*from]);
1039 if (top < 0) return CMD_INVAL;
1040 if (top >= 0 && !is_movable(f.t[*from], top-1)) {
1041 *opt = get_rank(f.t[*from][top]);
1042 } else {
1043 // ask user
1044 }
1045 }
1046 #endif*/
1047 break;
1048 case 'K': /* fallthrough */
1049 case '?': return CMD_HINT;
1050 case 'u': return CMD_NONE; /* cancel selection */
1051 case EOF: return CMD_NONE; /* sent by SIGCONT */
1052 default:
1053 if (t < '0' || t > '9') return CMD_INVAL;
1054 if (t == '0')
1055 #ifdef KLONDIKE
1056 *to = FOUNDATION;
1057 #elif defined SPIDER
1058 *to = TAB_10;
1059 #elif defined FREECELL
1060 *to = FOUNDATION;
1061 else if (t == '9')
1062 *to = STOCK;
1063 #endif
1064 else
1065 *to = t-'1';
1066 }
1067
1068 /***/
1069 #ifdef KLONDIKE
1070 if (*from == FOUNDATION) {
1071 if (inactive.opt >= 0) {
1072 *opt = inactive.opt;
1073 return CMD_MOVE;
1074 }
1075 int top = find_top(f.t[*to]);
1076 if (top < 0) return CMD_INVAL;
1077 int color = get_color(f.t[*to][top]);
1078 int choice_1 = 1-color; /* selects piles of */
1079 int choice_2 = 2+color; /* the opposite color */
1080 int top_c1 = find_top(f.f[choice_1]);
1081 int top_c2 = find_top(f.f[choice_2]);
1082
1083 switch ((rank_next(f.f[choice_1][top_c1], f.t[*to][top])
1084 && top_c1 >= 0 ) << 0
1085 |(rank_next(f.f[choice_2][top_c2], f.t[*to][top])
1086 && top_c2 >= 0 ) << 1) {
1087 case ( 1<<0): *opt = choice_1; break; /* choice_1 only */
1088 case (1<<1 ): *opt = choice_2; break; /* choice_2 only */
1089 case (1<<1 | 1<<0): /* both, ask user which to pick from */
1090 printf ("take from (1-4): "); fflush (stdout);
1091 *opt = getch(NULL) - '1';
1092 if (*opt < 0 || *opt > 3) return CMD_INVAL;
1093 break;
1094 default: return CMD_INVAL; /* none matched */
1095 }
1096 /* `opt` is the foundation index (0..3) */
1097 }
1098 #elif defined SPIDER
1099 /* moving to empty tableu? */
1100 if (is_tableu(*to) && f.t[*to][0] == NO_CARD) {
1101 int bottom = first_movable(f.t[*from]);
1102 if (inactive.opt >= 0) { /*if from was cursor addressed: */
1103 *opt = get_rank(f.t[*from][bottom + inactive.opt]);
1104 return CMD_MOVE;
1105 }
1106 int top = find_top(f.t[*from]);
1107 if (top < 0) return CMD_INVAL;
1108 if (top >= 0 && !is_movable(f.t[*from], top-1)) {
1109 *opt = get_rank(f.t[*from][top]);
1110 } else { /* only ask the user if it's unclear: */
1111 printf ("\rup to ([a23456789xjqk] or space/return): ");
1112 *opt = getch(NULL);
1113 switch (*opt) {
1114 case ' ': *opt = get_rank(f.t[*from][top]); break;
1115 case'\n': *opt = get_rank(f.t[*from][bottom]); break;
1116 case 'a': case 'A': *opt = RANK_A; break;
1117 case '0': /* fallthrough */
1118 case 'x': case 'X': *opt = RANK_X; break;
1119 case 'j': case 'J': *opt = RANK_J; break;
1120 case 'q': case 'Q': *opt = RANK_Q; break;
1121 case 'k': case 'K': *opt = RANK_K; break;
1122 default: *opt -= '1';
1123 }
1124 if (*opt < RANK_A || *opt > RANK_K) return ERR;
1125 }
1126 /* `opt` is the rank of the highest card to move */
1127 }
1128 #elif defined FREECELL
1129 //TODO FREECELL: card selector choice dialog
1130
1131 /* if it was selected with a cursor, it's obvious: */
1132 if (inactive.opt >= 0) {
1133 if (is_tableu(*from)) {
1134 /* NOTE: max_move same as in cursor_down() */
1135 *opt = max_move(*from, -1) - inactive.opt;
1136 } else {
1137 *opt = inactive.opt;
1138 }
1139 /* moving from tableu to empty tableu? */
1140 } else if (is_tableu(*from) && is_tableu(*to) && f.t[*to][0] == NO_CARD) {
1141 // how many cards? (NOTE: spider asks "up to rank?"; do this then convert to number of cards?
1142 printf ("take how many (1-9): "); fflush (stdout);
1143 *opt = getch(NULL) - '0';
1144 if (*opt < 1 || *opt > 9) return CMD_INVAL;
1145 /* moving between stock/foundation? */
1146 } else if (*from == FOUNDATION && *to == STOCK) {
1147 //can take from all non-empty foundations
1148 printf ("take from (1-4): "); fflush (stdout);
1149 *opt = getch(NULL) - '1';
1150 if (*opt < 0 || *opt > 3) return CMD_INVAL;
1151 } else if (*from == STOCK && *to == FOUNDATION) {
1152 //check all non-empty cells
1153 printf ("take from (1-4): "); fflush (stdout);
1154 *opt = getch(NULL) - '1';
1155 if (*opt < 0 || *opt > 3) return CMD_INVAL;
1156 } else if (*from == FOUNDATION || *from == STOCK) { /* -> tableu */
1157 //foundation: 2 choices
1158 //stock: 4 choices
1159 printf ("take from (1-4): "); fflush (stdout);
1160 *opt = getch(NULL) - '1';
1161 if (*opt < 0 || *opt > 3) return CMD_INVAL;
1162 }
1163 #endif
1164 return CMD_MOVE;
1165 }
1166
1167 int getctrlseq(unsigned char* buf) {
1168 int c;
1169 enum esc_states {
1170 START,
1171 ESC_SENT,
1172 CSI_SENT,
1173 MOUSE_EVENT,
1174 } state = START;
1175 int offset = 0x20; /* never sends control chars as data */
1176 while ((c = getchar()) != EOF) {
1177 switch (state) {
1178 case START:
1179 switch (c) {
1180 case '\033': state=ESC_SENT; break;
1181 default: return c;
1182 }
1183 break;
1184 case ESC_SENT:
1185 switch (c) {
1186 case '[': state=CSI_SENT; break;
1187 default: return KEY_INVAL;
1188 }
1189 break;
1190 case CSI_SENT:
1191 switch (c) {
1192 case 'A': return KEY_UP;
1193 case 'B': return KEY_DOWN;
1194 case 'C': return KEY_RIGHT;
1195 case 'D': return KEY_LEFT;
1196 /*NOTE: home/end send ^[[x~ . no support for modifiers*/
1197 case 'H': return KEY_HOME;
1198 case 'F': return KEY_END;
1199 case '2': getchar(); return KEY_INS;
1200 case '5': getchar(); return KEY_PGUP;
1201 case '6': getchar(); return KEY_PGDN;
1202 case 'M': state=MOUSE_EVENT; break;
1203 default: return KEY_INVAL;
1204 }
1205 break;
1206 case MOUSE_EVENT:
1207 if (buf == NULL) return KEY_INVAL;
1208 buf[0] = c - offset;
1209 buf[1] = getchar() - offset;
1210 buf[2] = getchar() - offset;
1211 return MOUSE_ANY;
1212 default:
1213 return KEY_INVAL;
1214 }
1215 }
1216 return 2;
1217 }
1218 int term2pile(unsigned char *mouse) {
1219 int line = (mouse[2]-1);
1220 int column = (mouse[1]-1) / op.s->width;
1221
1222 if (line < op.s->height) { /* first line */
1223 #ifdef KLONDIKE
1224 switch (column) {
1225 case 0: return STOCK;
1226 case 1: return WASTE;
1227 case 2: return -1; /* spacer */
1228 case 3: return FOUNDATION+0;
1229 case 4: return FOUNDATION+1;
1230 case 5: return FOUNDATION+2;
1231 case 6: return FOUNDATION+3;
1232 }
1233 #elif defined SPIDER
1234 if (column < 3) return STOCK;
1235 return -1;
1236 #elif defined FREECELL
1237 if (column < NUM_SUITS + NUM_CELLS) return STOCK+column;
1238 return -1;
1239 #endif
1240 } else if (line > op.s->height) { /* tableu */
1241 if (column <= TAB_MAX) return column;
1242 }
1243 return -1;
1244 }
1245 int wait_mouse_up(unsigned char* mouse) {
1246 //TODO: mouse drag: start gets inactive, hovering gets active cursors
1247 struct cursor cur = {-1,-1};
1248 int level = 1;
1249 /* note: if dragged [3]==1 and second position is in mouse[0,4,5] */
1250
1251 /* display a cursor while mouse button is pushed: */
1252 int pile = term2pile(mouse);
1253 cur.pile = pile;
1254 #ifdef KLONDIKE
1255 if (pile >= FOUNDATION) {
1256 cur.pile = FOUNDATION;
1257 cur.opt = pile-FOUNDATION;
1258 }
1259 #elif defined FREECELL
1260 if (pile > TAB_MAX) {
1261 cur.pile = pile-STOCK < NUM_CELLS? STOCK : FOUNDATION;
1262 cur.opt = (pile-STOCK) % 4;
1263 }
1264 #endif
1265 /* need to temporarily show the cursor, then revert to last state: */
1266 int old_show_cursor_hi = op.h; //TODO: ARGH! that's awful!
1267 op.h = 1;
1268 print_table(&cur, NO_HI); //TODO: should not overwrite inactive cursor!
1269 op.h = old_show_cursor_hi;
1270
1271 while (level > 0) {
1272 if (getctrlseq (mouse+3) == MOUSE_ANY) {
1273 /* ignore mouse wheel events: */
1274 if (mouse[3] & 0x40) continue;
1275
1276 else if((mouse[3]&3) == 3) level--; /* release event */
1277 else level++; /* another button pressed */
1278 }
1279 }
1280
1281 int success = mouse[1] == mouse[4] && mouse[2] == mouse[5];
1282 if (success) {
1283 mouse[3] = 0;
1284 }
1285 return success;
1286 }
1287
1288 int getch(unsigned char* buf) {
1289 /* returns a character, EOF, or constant for an escape/control sequence - NOT
1290 compatible with the ncurses implementation of same name */
1291 int action;
1292 if (buf && buf[3]) {
1293 /* mouse was dragged; return 'ungetted' previous destination */
1294 action = MOUSE_DRAG;
1295 /* keep original [0], as [3] only contains release event */
1296 buf[1] = buf[4];
1297 buf[2] = buf[5];
1298 buf[3] = 0;
1299 } else {
1300 action = getctrlseq(buf);
1301 }
1302
1303 switch (action) {
1304 case MOUSE_ANY:
1305 if (buf[0] > 3) break; /* ignore wheel events */
1306 wait_mouse_up(buf);
1307 /* fallthrough */
1308 case MOUSE_DRAG:
1309 switch (buf[0]) {
1310 case 0: return MOUSE_LEFT;
1311 case 1: return MOUSE_MIDDLE;
1312 case 2: return MOUSE_RIGHT;
1313 }
1314 }
1315
1316 return action;
1317 }
1318 // }}}
1319
1320 // shuffling and dealing {{{
1321 void deal(long seed) {
1322 f = (const struct playfield){0}; /* clear playfield */
1323 card_t deck[DECK_SIZE*NUM_DECKS];
1324 int avail = DECK_SIZE*NUM_DECKS;
1325 for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) deck[i] = (i%DECK_SIZE)+1;
1326 #ifdef SPIDER
1327 if (op.m != NORMAL) for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) {
1328 if (op.m == MEDIUM) deck[i] = 1+((deck[i]-1) | 2);
1329 if (op.m == EASY) deck[i] = 1+((deck[i]-1) | 2 | 1);
1330 /* the 1+ -1 dance gets rid of the offset created by NO_CARD */
1331 }
1332 #endif
1333 srand (seed);
1334 for (int i = DECK_SIZE*NUM_DECKS-1; i > 0; i--) { /* fisher-yates */
1335 int j = rand() % (i+1);
1336 if (j-i) deck[i]^=deck[j],deck[j]^=deck[i],deck[i]^=deck[j];
1337 }
1338
1339 /* deal cards: */
1340 for (int i = 0; i < NUM_PILES; i++) {
1341 #ifdef KLONDIKE
1342 #define SIGN -
1343 int count = i; /* pile n has n closed cards, then 1 open */
1344 #elif defined SPIDER
1345 #define SIGN -
1346 int count = i<4?5:4; /* pile 1-4 have 5, 5-10 have 4 closed */
1347 #elif defined FREECELL
1348 #define SIGN +
1349 int count = i<4?6:5;/*like spider, but cards are dealt face-up*/
1350 #endif
1351 /* "SIGN": face down cards are negated */
1352 for (int j = 0; j < count; j++) f.t[i][j] = SIGN deck[--avail];
1353 f.t[i][count] = deck[--avail]; /* the face-up card */
1354 #undef SIGN
1355 }
1356 /* rest of the cards to the stock: */
1357 /* NOTE: assert(avail==50) for spider, assert(avail==0) for freecell */
1358 for (f.z = 0; avail; f.z++) f.s[f.z] = deck[--avail];
1359 #ifdef KLONDIKE
1360 f.w = -1; /* @start: nothing on waste */
1361 #elif defined SPIDER
1362 f.w = 0; /* number of used foundations */
1363 #elif defined FREECELL
1364 f.w = 0; /* bitmask of used free cells */
1365 #endif
1366
1367 f.u = &undo_sentinel;
1368 }
1369 //}}}
1370
1371 // screen drawing routines {{{
1372 void print_hi(int invert, int grey_bg, int bold, char* str) {
1373 if (!op.h) invert = 0; /* don't show invert if we used the mouse last */
1374 if (bold && op.s == &unicode_large_color){ //awful hack for bold + faint
1375 int offset = str[3]==017?16:str[4]==017?17:0;
1376 printf ("%s%s%s""%.*s%s%s""%s%s%s",
1377 "\033[1m", invert?"\033[7m":"", grey_bg?"\033[100m":"",
1378 offset, str, bold?"\033[1m":"", str+offset,
1379 grey_bg?"\033[49m":"", invert?"\033[27m":"","\033[22m");
1380 return;
1381 }
1382 printf ("%s%s%s%s%s%s%s",
1383 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
1384 str,
1385 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
1386 }
1387 void print_table(const struct cursor* active, const struct cursor* inactive) {
1388 printf("\033[2J\033[H"); /* clear screen, reset cursor */
1389 #ifdef KLONDIKE
1390 /* print stock, waste and foundation: */
1391 for (int line = 0; line < op.s->height; line++) {
1392 /* stock: */
1393 print_hi (active->pile == STOCK, inactive->pile == STOCK, 1, (
1394 (f.w < f.z-1)?op.s->facedown
1395 :op.s->placeholder)[line]);
1396 /* waste: */
1397 print_hi (active->pile == WASTE, inactive->pile == WASTE, 1, (
1398 /* NOTE: cast, because f.w sometimes is (short)-1 !? */
1399 ((short)f.w >= 0)?op.s->card[f.s[f.w]]
1400 :op.s->placeholder)[line]);
1401 printf ("%s", op.s->card[NO_CARD][line]); /* spacer */
1402 /* foundation: */
1403 for (int pile = 0; pile < NUM_SUITS; pile++) {
1404 int card = find_top(f.f[pile]);
1405 print_hi (active->pile==FOUNDATION && active->opt==pile,
1406 inactive->pile==FOUNDATION && (
1407 /* cursor addr. || direct addr. */
1408 inactive->opt==pile || inactive->opt < 0
1409 ), 1,
1410 (card < 0)?op.s->placeholder[line]
1411 :op.s->card[f.f[pile][card]][line]);
1412 }
1413 printf("\n");
1414 }
1415 printf("\n");
1416 #elif defined SPIDER
1417 int fdone; for (fdone = NUM_DECKS*NUM_SUITS; fdone; fdone--)
1418 if (f.f[fdone-1][RANK_K]) break; /*number of completed stacks*/
1419 int spacer_from = f.z?(f.z/10-1) * op.s->halfwidth[0] + op.s->width:0;
1420 int spacer_to = NUM_PILES*op.s->width -
1421 ((fdone?(fdone-1) * op.s->halfwidth[1]:0)+op.s->width);
1422 for (int line = 0; line < op.s->height; line++) {
1423 /* available stock: */
1424 for (int i = f.z/10; i; i--) {
1425 if (i==1) printf ("%s", op.s->facedown[line]);
1426 else printf ("%s", op.s->halfstack[line]);
1427 }
1428 /* spacer: */
1429 for (int i = spacer_from; i < spacer_to; i++) printf (" ");
1430 /* foundation (overlapping): */
1431 for (int i = NUM_DECKS*NUM_SUITS-1, half = 0; i >= 0; i--) {
1432 int overlap = half? op.s->halfcard[line]: 0;
1433 if (f.f[i][RANK_K]) printf ("%.*s", op.s->halfwidth[2],
1434 op.s->card[f.f[i][RANK_K]][line]+overlap),
1435 half++;
1436 }
1437 printf("\n");
1438 }
1439 printf("\n");
1440 #elif defined FREECELL
1441 /* print open cells, foundation: */
1442 for (int line = 0; line < op.s->height; line++) {
1443 //FREECELL TODO: cells and foundation look the same! (different placeholder?)
1444 for (int pile = 0; pile < NUM_CELLS; pile++)
1445 print_hi (active->pile==STOCK && active->opt==pile,
1446 inactive->pile==STOCK && (
1447 /* cursor addr. || direct addr. */
1448 inactive->opt==pile || inactive->opt < 0
1449 ), 1,
1450 ((f.s[pile])?op.s->card[f.s[pile]]
1451 :op.s->placeholder)[line]);
1452 for (int pile = 0; pile < NUM_SUITS; pile++) {
1453 int card = find_top(f.f[pile]);
1454 print_hi (active->pile==FOUNDATION && active->opt==pile,
1455 inactive->pile==FOUNDATION && (
1456 /* cursor addr. || direct addr. */
1457 inactive->opt==pile || inactive->opt < 0
1458 ), 1,
1459 (card < 0)?op.s->placeholder[line]
1460 :op.s->card[f.f[pile][card]][line]);
1461 }
1462 printf("\n");
1463 }
1464 printf("\n");
1465 #endif
1466 #ifdef KLONDIKE
1467 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty))
1468 #define TOP_HI(c) 1 /* can't select partial stacks in KLONDIKE */
1469 #elif defined SPIDER || defined FREECELL
1470 int offset[NUM_PILES]={0}; /* first card to highlight */
1471 # ifdef FREECELL
1472 int bottom[NUM_PILES]; /* first movable card */
1473 for (int i=0; i<NUM_PILES; i++)
1474 bottom[i] = find_top(f.t[i]) - max_move(i,-1);
1475 # endif
1476 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty) \
1477 && offset[pile] >= cursor->opt)
1478 #define TOP_HI(cursor) (cursor->pile == pile && movable \
1479 && offset[pile] == cursor->opt)
1480 #endif
1481 /* print tableu piles: */
1482 int row[NUM_PILES] = {0};
1483 int line[NUM_PILES]= {0};
1484 int label[NUM_PILES]={0};
1485 int line_had_card;
1486 int did_placeholders = 0;
1487 do {
1488 line_had_card = 0;
1489 for (int pile = 0; pile < NUM_PILES; pile++) {
1490 card_t card = f.t[pile][row[pile]];
1491 card_t next = f.t[pile][row[pile]+1];
1492 int movable = is_movable(f.t[pile], row[pile]);
1493 #ifdef FREECELL
1494 if(row[pile] <= bottom[pile]) movable = 0;
1495 #endif
1496 int empty = !card && row[pile] == 0;
1497
1498 print_hi (DO_HI(active), DO_HI(inactive), movable, (
1499 (!card && row[pile] == 0)?op.s->placeholder
1500 :(card<0)?op.s->facedown
1501 :op.s->card[card]
1502 )[line[pile]]);
1503
1504 int extreme_overlap = ( 3 /* spacer, labels, status */
1505 + 2 * op.s->height /* stock, top tableu card */
1506 + find_top(f.t[pile]) * op.s->overlap) >op.w[0];
1507 /* normal overlap: */
1508 if (++line[pile] >= (next?op.s->overlap:op.s->height)
1509 /* extreme overlap on closed cards: */
1510 || (extreme_overlap &&
1511 line[pile] >= 1 &&
1512 f.t[pile][row[pile]] < 0 &&
1513 f.t[pile][row[pile]+1] <0)
1514 /* extreme overlap on sequences: */
1515 || (extreme_overlap &&
1516 !TOP_HI(active) && /*always show top selected card*/
1517 line[pile] >= 1 && row[pile] > 0 &&
1518 f.t[pile][row[pile]-1] > NO_CARD &&
1519 is_consecutive (f.t[pile], row[pile]) &&
1520 is_consecutive (f.t[pile], row[pile]-1) &&
1521 f.t[pile][row[pile]+1] != NO_CARD)
1522 ) {
1523 line[pile]=0;
1524 row[pile]++;
1525 #if defined SPIDER || defined FREECELL
1526 if (movable) offset[pile]++;
1527 #endif
1528 }
1529 /* tableu labels: */
1530 if(!card && !label[pile] && row[pile]>0&&line[pile]>0) {
1531 label[pile] = 1;
1532 printf ("\b\b%d ", (pile+1) % 10); //XXX: hack
1533 }
1534 line_had_card |= !!card;
1535 did_placeholders |= row[pile] > 0;
1536 }
1537 printf ("\n");
1538 } while (line_had_card || !did_placeholders);
1539 }
1540
1541 void visbell (void) {
1542 if (!op.v) return;
1543 printf ("\033[?5h"); fflush (stdout);
1544 usleep (100000);
1545 printf ("\033[?5l"); fflush (stdout);
1546 }
1547 void win_anim(void) {
1548 printf ("\033[?25l"); /* hide cursor */
1549 for (;;) {
1550 /* set cursor to random location */
1551 int row = 1+rand()%(1+op.w[0]-op.s->height);
1552 int col = 1+rand()%(1+op.w[1]-op.s->width);
1553
1554 /* draw random card */
1555 int face = 1 + rand() % 52;
1556 for (int l = 0; l < op.s->height; l++) {
1557 printf ("\033[%d;%dH", row+l, col);
1558 printf ("%s", op.s->card[face][l]);
1559 }
1560 fflush (stdout);
1561
1562 /* exit on keypress */
1563 struct pollfd p = {STDIN_FILENO, POLLIN, 0};
1564 if (poll (&p, 1, 80)) goto fin;
1565 }
1566 fin:
1567 printf ("\033[?25h"); /* show cursor */
1568 return;
1569 }
1570 //}}}
1571
1572 // undo logic {{{
1573 void undo_push (int _f, int t, int n, int o) {
1574 struct undo* new = malloc(sizeof(struct undo));
1575 new->f = _f;
1576 new->t = t;
1577 new->n = n;
1578 new->o = o;
1579 new->prev = f.u;
1580 new->next = NULL;
1581 f.u->next = new;
1582 f.u = f.u->next;
1583 }
1584 void undo_pop (struct undo* u) {
1585 if (u == &undo_sentinel) return;
1586
1587 #ifdef KLONDIKE
1588 if (u->f == FOUNDATION) {
1589 /* foundation -> tableu */
1590 int top_f = find_top(f.f[u->n]);
1591 int top_t = find_top(f.t[u->t]);
1592 f.f[u->n][top_f+1] = f.t[u->t][top_t];
1593 f.t[u->t][top_t] = NO_CARD;
1594 } else if (u->f == WASTE && u->t == FOUNDATION) {
1595 /* waste -> foundation */
1596 /* split u->n into wst and fnd: */
1597 int wst = u->n & 0xffff;
1598 int fnd = u->n >> 16;
1599 /* move stock cards one position up to make room: */
1600 for (int i = f.z; i >= wst; i--) f.s[i+1] = f.s[i];
1601 /* move one card from foundation to waste: */
1602 int top = find_top(f.f[fnd]);
1603 f.s[wst] = f.f[fnd][top];
1604 f.f[fnd][top] = NO_CARD;
1605 f.z++;
1606 f.w++;
1607 } else if (u->f == WASTE) {
1608 /* waste -> tableu */
1609 /* move stock cards one position up to make room: */
1610 for (int i = f.z-1; i >= u->n; i--) f.s[i+1] = f.s[i];
1611 /* move one card from tableu to waste: */
1612 int top = find_top(f.t[u->t]);
1613 f.s[u->n] = f.t[u->t][top];
1614 f.t[u->t][top] = NO_CARD;
1615 f.z++;
1616 f.w++;
1617 } else if (u->t == FOUNDATION) {
1618 /* tableu -> foundation */
1619 int top_f = find_top(f.t[u->f]);
1620 int top_t = find_top(f.f[u->n]);
1621 /* close topcard if previous action caused turn_over(): */
1622 if (u->o) f.t[u->f][top_f] *= -1;
1623 /* move one card from foundation to tableu: */
1624 f.t[u->f][top_f+1] = f.f[u->n][top_t];
1625 f.f[u->n][top_t] = NO_CARD;
1626 } else {
1627 /* tableu -> tableu */
1628 int top_f = find_top(f.t[u->f]);
1629 int top_t = find_top(f.t[u->t]);
1630 /* close topcard if previous action caused turn_over(): */
1631 if (u->o) f.t[u->f][top_f] *= -1;
1632 /* move n cards from tableu[f] to tableu[t]: */
1633 for (int i = 0; i < u->n; i++) {
1634 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
1635 f.t[u->t][top_t-i] = NO_CARD;
1636 }
1637 }
1638 #elif defined SPIDER
1639 if (u->f == STOCK) {
1640 /* stock -> tableu */
1641 /*remove a card from each pile and put it back onto the stock:*/
1642 for (int pile = NUM_PILES-1; pile >= 0; pile--) {
1643 int top = find_top(f.t[pile]);
1644 f.s[f.z++] = f.t[pile][top];
1645 f.t[pile][top] = NO_CARD;
1646 }
1647 } else if (u->t == FOUNDATION) {
1648 /* tableu -> foundation */
1649 int top = find_top(f.t[u->f]);
1650 /* close topcard if previous action caused turn_over(): */
1651 if (u->o) f.t[u->f][top] *= -1;
1652 /* append cards from foundation to tableu */
1653 for (int i = RANK_K; i >= RANK_A; i--) {
1654 f.t[u->f][++top] = f.f[u->n][i];
1655 f.f[u->n][i] = NO_CARD;
1656 }
1657 f.w--; /* decrement complete-foundation-counter */
1658
1659 } else {
1660 /* tableu -> tableu */
1661 int top_f = find_top(f.t[u->f]);
1662 int top_t = find_top(f.t[u->t]);
1663 /* close topcard if previous action caused turn_over(): */
1664 if (u->o) f.t[u->f][top_f] *= -1;
1665 /* move n cards from tableu[f] to tableu[t]: */
1666 for (int i = 0; i < u->n; i++) {
1667 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
1668 f.t[u->t][top_t-i] = NO_CARD;
1669 }
1670 }
1671 #elif defined FREECELL
1672 /*NOTE: if from and to are both stock/foundation, opt = from | to<<16 */
1673 if (u->f == STOCK && u->t == FOUNDATION) {
1674 /* free cells -> foundation */
1675 /* split u->n into cll and fnd: */
1676 int cll = u->n & 0xffff;
1677 int fnd = u->n >> 16;
1678 /* move one card from foundation to free cell: */
1679 int top = find_top(f.f[fnd]);
1680 f.s[cll] = f.f[fnd][top];
1681 f.f[fnd][top] = NO_CARD;
1682 f.w |= 1<<cll; /* mark cell as occupied */
1683 } else if (u->f == STOCK) {
1684 /* free cells -> cascade */
1685 int top_t = find_top(f.t[u->t]);
1686 f.s[u->n] = f.t[u->t][top_t];
1687 f.t[u->t][top_t] = NO_CARD;
1688 f.w |= 1<<u->n; /* mark cell as occupied */
1689 } else if (u->f == FOUNDATION && u->t == STOCK) {
1690 /* foundation -> free cells */
1691 /* split u->n into cll and fnd: */
1692 int cll = u->n >> 16;
1693 int fnd = u->n & 0xffff;
1694 /* move 1 card from free cell to foundation: */
1695 int top_f = find_top(f.f[fnd]);
1696 f.f[fnd][top_f+1] = f.s[cll];
1697 f.s[cll] = NO_CARD;
1698 f.w &= ~(1<<cll); /* mark cell as free */
1699 } else if (u->f == FOUNDATION) {
1700 /* foundation -> cascade */
1701 int top_f = find_top(f.f[u->n]);
1702 int top_t = find_top(f.t[u->t]);
1703 f.f[u->n][top_f+1] = f.t[u->t][top_t];
1704 f.t[u->t][top_t] = NO_CARD;
1705 } else if (u->t == STOCK) {
1706 /* cascade -> free cells */
1707 int top_f = find_top(f.t[u->f]);
1708 f.t[u->f][top_f+1] = f.s[u->n];
1709 f.s[u->n] = NO_CARD;
1710 f.w &= ~(1<<u->n); /* mark cell as free */
1711 } else if (u->t == FOUNDATION) {
1712 /* cascade -> foundation */
1713 int top_f = find_top(f.t[u->f]);
1714 int top_t = find_top(f.f[u->n]);
1715 /* move one card from foundation to cascade: */
1716 f.t[u->f][top_f+1] = f.f[u->n][top_t];
1717 f.f[u->n][top_t] = NO_CARD;
1718 } else {
1719 /* cascade -> cascade */
1720 int top_f = find_top(f.t[u->f]);
1721 int top_t = find_top(f.t[u->t]);
1722 /* move n cards from tableu[f] to tableu[t]: */
1723 for (int i = 0; i < u->n; i++) {
1724 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
1725 f.t[u->t][top_t-i] = NO_CARD;
1726 }
1727 }
1728 #endif
1729
1730 void* old = f.u;
1731 f.u = f.u->prev;
1732 free(old);
1733 }
1734 void free_undo (struct undo* u) {
1735 while (u && u != &undo_sentinel) {
1736 void* old = u;
1737 u = u->prev;
1738 free (old);
1739 }
1740 }
1741 //}}}
1742
1743 // initialization stuff {{{
1744 void screen_setup (int enable) {
1745 if (enable) {
1746 raw_mode(1);
1747 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
1748 printf ("\033[H\033[J"); /* reset cursor, clear screen */
1749 printf ("\033[?1000h"); /* enable mouse */
1750 } else {
1751 printf ("\033[?1000l"); /* disable mouse */
1752 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
1753 raw_mode(0);
1754 }
1755 }
1756
1757 void raw_mode(int enable) {
1758 static struct termios saved_term_mode;
1759 struct termios raw_term_mode;
1760
1761 if (enable) {
1762 if (saved_term_mode.c_lflag == 0)/*don't overwrite stored mode*/
1763 tcgetattr(STDIN_FILENO, &saved_term_mode);
1764 raw_term_mode = saved_term_mode;
1765 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
1766 raw_term_mode.c_cc[VMIN] = 1 ;
1767 raw_term_mode.c_cc[VTIME] = 0;
1768 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
1769 } else {
1770 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
1771 }
1772 }
1773
1774 void signal_handler (int signum) {
1775 struct winsize w;
1776 switch (signum) {
1777 case SIGTSTP:
1778 screen_setup(0);
1779 signal(SIGTSTP, SIG_DFL); /* NOTE: assumes SysV semantics! */
1780 raise(SIGTSTP);
1781 break;
1782 case SIGCONT:
1783 screen_setup(1);
1784 print_table(NO_HI, NO_HI);
1785 break;
1786 case SIGINT: //TODO: don't exit; just warn like vim does
1787 exit(128+SIGINT);
1788 case SIGWINCH:
1789 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
1790 op.w[0] = w.ws_row;
1791 op.w[1] = w.ws_col;
1792 break;
1793 }
1794 }
1795 void signal_setup(void) {
1796 struct sigaction saction;
1797
1798 saction.sa_handler = signal_handler;
1799 sigemptyset(&saction.sa_mask);
1800 saction.sa_flags = 0;
1801 if (sigaction(SIGTSTP, &saction, NULL) < 0) {
1802 perror ("SIGTSTP");
1803 exit (1);
1804 }
1805 if (sigaction(SIGCONT, &saction, NULL) < 0) {
1806 perror ("SIGCONT");
1807 exit (1);
1808 }
1809 if (sigaction(SIGINT, &saction, NULL) < 0) {
1810 perror ("SIGINT");
1811 exit (1);
1812 }
1813 if (sigaction(SIGWINCH, &saction, NULL) < 0) {
1814 perror ("SIGWINCH");
1815 exit (1);
1816 }
1817 }
1818 //}}}
1819
1820 //vim: foldmethod=marker
Imprint / Impressum