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