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