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