summaryrefslogtreecommitdiff
path: root/bin/hangman/hangman.c
blob: 381c13e110081617474313b02e340c0a959375e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
/*
 * hangman - Part of my GTK+ workshop.
 *
 * Written in 2016 and 2017 by Florian Pelz <pelzflorian@pelzflorian.de>
 *
 * To the extent possible under law, the author(s) have dedicated all
 * copyright and related and neighboring rights to this software to
 * the public domain worldwide. This software is distributed without
 * any warranty.
 *
 * You should have received a copy of the CC0 Public Domain Dedication
 * along with this software. If not, see
 * <http://creativecommons.org/publicdomain/zero/1.0/>.
 *
 */

#include <gtk/gtk.h>
#include <string.h>

struct _GameData
{
  gint          state;
  gchar        *word;
  gchar        *word_state;
  gchar        *used;
  gint          unichar_count;
  PangoLogAttr *log_attrs;
  gunichar      default_isolate;
};

typedef struct _GameData GameData;

struct _AppData
{
  GameData      *game_data;
  GtkLabel      *guessed;
  GtkWidget     *gallow;
  GtkIMContext  *input_method;
  GtkAccelGroup *accel_group;
};

typedef struct _AppData AppData;

#define BUFFER_SIZE 8192

static gchar *
get_word (void)
{
  GFile *file;
  GFileInputStream *in;
  gchar *readbuf;
  gssize bytes_read;
  gint32 line_count, random_line;
  gboolean found;
  GString *builder;
  gchar *result, *result_up, *result_normalized;

  file = g_file_new_for_path ("/usr/share/dict/usa");
  in = g_file_read (file, NULL, NULL);

  line_count = 0;

  readbuf = g_malloc (BUFFER_SIZE);
  bytes_read = BUFFER_SIZE;
  while (bytes_read >= BUFFER_SIZE)
    {
      gint i;

      bytes_read = g_input_stream_read (G_INPUT_STREAM (in),
                                        readbuf,
                                        BUFFER_SIZE,
                                        NULL,
                                        NULL);

      for (i = 0; i < bytes_read; i++)
        if (readbuf[i] == '\n')
          line_count++;
    }

  g_assert (line_count > 0);

  random_line = g_random_int_range (0, line_count);

  line_count = 0;

  g_object_unref (in);
  in = g_file_read (file, NULL, NULL);

  if (random_line == 0)
    found = TRUE;
  else
    found = FALSE;

  builder = g_string_new (NULL);

  bytes_read = BUFFER_SIZE;
  while (bytes_read >= BUFFER_SIZE)
    {
      gint i;

      bytes_read = g_input_stream_read (G_INPUT_STREAM (in),
                                        readbuf,
                                        BUFFER_SIZE,
                                        NULL,
                                        NULL);

      i = 0;
      if (found == FALSE)
        while (i < bytes_read)
          {
            if (readbuf[i] == '\n')
              {
                line_count++;
                if (line_count == random_line)
                  {
                    found = TRUE;
                    i++;
                    break;
                  }
              }
            i++;
          }
      if (found == TRUE)
        while (i < bytes_read)
          {
            if (readbuf[i] == '\n')
              goto get_word_end;
            else
              g_string_append_c (builder, readbuf[i]);
            i++;
          }
    }

 get_word_end:
  g_free (readbuf);
  g_object_unref (in);
  g_object_unref (file);

  result = g_string_free (builder, FALSE);
  result_up = g_utf8_strup (result, -1);
  g_free (result);
  result_normalized = g_utf8_normalize (result_up,
                                        -1,
                                        G_NORMALIZE_ALL);
  g_free (result_up);
  return result_normalized;
}

static void
update_label (AppData *app_data)
{
  gchar *markup;

  markup = g_strdup_printf ("<tt>%s</tt>",
                            app_data->game_data->word_state);
  gtk_label_set_markup (app_data->guessed, markup);
  g_free (markup);
}

static void
get_log_attrs (const gchar   *string,
               gint           byte_count,
               gint           unichar_count,
               PangoLogAttr **log_attrs_location)
{
  PangoLogAttr *log_attrs;

  log_attrs = g_malloc ((unichar_count + 1) * sizeof (PangoLogAttr));
  *log_attrs_location = log_attrs;

  pango_get_log_attrs (string,
                       byte_count,
                       0, /* bidirectional embedding level */
                       pango_language_get_default (),
                       log_attrs,
                       unichar_count + 1);
}

static void
append_underscore_for_char (GString  *builder,
                            gunichar  chr,
                            GameData *game_data)
{
  switch (pango_unichar_direction (chr))
    {
    case PANGO_DIRECTION_LTR:
    case PANGO_DIRECTION_TTB_LTR:
      g_string_append_unichar (builder, 0x2066); /* ltr isolate */
      g_string_append_unichar (builder, '_');
      g_string_append_unichar (builder, 0x2069); /* pop */
      break;
    case PANGO_DIRECTION_RTL:
    case PANGO_DIRECTION_TTB_RTL:
      g_string_append_unichar (builder, 0x2067); /* rtl isolate */
      g_string_append_unichar (builder, '_');
      g_string_append_unichar (builder, 0x2069); /* pop */
      break;
    case PANGO_DIRECTION_WEAK_LTR:
    case PANGO_DIRECTION_WEAK_RTL:
      g_string_append_unichar (builder, '_');
      break;
    default:
      g_string_append_unichar (builder, game_data->default_isolate);
      g_string_append_unichar (builder, '_');
      g_string_append_unichar (builder, 0x2069); /* pop */
    }
}

static void
new_game (AppData *app_data)
{
  GameData *game_data;

  GString *builder;
  gchar *tmp;
  gint byte_count, unichar_count;
  PangoLogAttr *log_attrs;

  PangoDirection direction;

  game_data = app_data->game_data;

  game_data->state = 0;

  g_free (game_data->word);
  tmp = get_word ();
  game_data->word = tmp;

  builder = g_string_new (NULL);

  byte_count = strlen (tmp);
  unichar_count = g_utf8_strlen (tmp, -1);
  game_data->unichar_count = unichar_count;

  g_free (game_data->log_attrs);
  get_log_attrs (tmp, byte_count, unichar_count, &log_attrs);
  game_data->log_attrs = log_attrs;

  direction = pango_find_base_dir (tmp, byte_count);
  if (direction == PANGO_DIRECTION_RTL)
    game_data->default_isolate = 0x2067; /* rtl isolate */
  else
    game_data->default_isolate = 0x2066; /* ltr isolate */

  for (int i = 0; i < unichar_count; i++)
    {
      if (log_attrs[i].is_cursor_position)
        {
          gunichar chr;

          chr = g_utf8_get_char (tmp);

          if (chr == 0x0020) /* if space */
            g_string_append_unichar (builder, chr);
          else
            append_underscore_for_char (builder, chr, game_data);
        }

      tmp = g_utf8_next_char (tmp);
    }

  game_data->word_state = g_string_free (builder, FALSE);

  g_free (game_data->used);
  /* Reveal space character by default: */
  game_data->used = g_strdup (" ");

  update_label (app_data);

  gtk_widget_queue_draw (app_data->gallow);
}

static void
play_characters_in_string (const gchar *text,
                           AppData     *app_data)
{
  GameData *game_data;
  PangoLogAttr *log_attrs, *input_log_attrs;
  gint input_byte_count, input_uchar_count;
  gchar *tmp, *str, *remaining;
  gint new_char_count;

  if (!g_utf8_validate (text, -1, NULL))
    return;

  game_data = app_data->game_data;
  log_attrs = game_data->log_attrs;

  /* Make str uppercase and normalized. */
  tmp = g_utf8_strup (text, -1);
  str = g_utf8_normalize (tmp, -1, G_NORMALIZE_ALL);
  g_free (tmp);

  input_byte_count = strlen (str);
  input_uchar_count = g_utf8_strlen (str, -1);

  get_log_attrs (str,
                 input_byte_count,
                 input_uchar_count,
                 &input_log_attrs);

  remaining = str;
  new_char_count = 0;

  for (int i = 0; i < input_uchar_count; i++)
    {
      if (input_log_attrs[i].is_cursor_position)
        {
          gunichar cur = g_utf8_get_char (remaining);

          if (g_utf8_strchr (game_data->used, -1, cur) == NULL)
            {
              gchar *cur_utf8;
              gchar *tmp;

              /* Add cur to the used characters. */
              cur_utf8 = g_ucs4_to_utf8 (&cur, 1, NULL, NULL, NULL);
              tmp = g_strdup_printf ("%s%s", game_data->used, cur_utf8);
              g_free (game_data->used);
              g_free (cur_utf8);
              game_data->used = tmp;

              new_char_count++;
            }

          remaining = g_utf8_next_char (remaining);
        }
    }

  g_free (input_log_attrs);

  if (new_char_count > 0)
    {
      gboolean write_chars;
      gint unichar_count;
      gchar *tmp;
      GString *builder;

      /* Since the first character should always be a grapheme cluster
         boundary, initializing write_chars is probably unnecessary,
         but let’s do it anyway. */
      write_chars = FALSE;

      unichar_count = game_data->unichar_count;
      tmp = game_data->word;

      builder = g_string_new (NULL);

      /* Rebuild the word. */
      for (int i = 0; i < unichar_count; i++)
        {
          /* If this character is at a grapheme cluster boundary… */
          if (log_attrs[i].is_cursor_position)
            {
              gunichar first_in_cluster;

              first_in_cluster = g_utf8_get_char (tmp);

              /* Check if the grapheme cluster starts with a used
                 character. */
              write_chars = FALSE;
              for (gchar *tmp2 = game_data->used;
                   *tmp2 != '\0';
                   tmp2 = g_utf8_next_char (tmp2))
                {
                  gunichar used_char;

                  used_char = g_utf8_get_char (tmp2);

                  if (used_char == first_in_cluster)
                    {
                      /* Yes! Write all characters in the
                         cluster. */
                      write_chars = TRUE;
                      goto after_cluster_check;
                    }
                }

              /* No used character in grapheme cluster. */
              append_underscore_for_char (builder,
                                          g_utf8_get_char (tmp),
                                          game_data);
            }
         after_cluster_check:

          if (write_chars)
            {
              g_string_append_unichar (builder, g_utf8_get_char (tmp));
            }

          tmp = g_utf8_next_char (tmp);
        }


      tmp = g_string_free (builder, FALSE);

      if (strcmp (tmp, game_data->word_state) == 0)
        {
          game_data->state += new_char_count;
          g_free (tmp);

          if (game_data->state >= 6)
            {
              game_data->state = 6;

              g_free (game_data->word_state);
              game_data->word_state = game_data->word;

              update_label (app_data);
            }
        }
      else
        {
          g_free (game_data->word_state);
          game_data->word_state = tmp;

          update_label (app_data);

          if (strcmp (game_data->word_state, game_data->word) == 0)
            {
              game_data->state = -1;
            }
        }
    }

  g_free (str);

  gtk_widget_queue_draw (app_data->gallow);
}

static void
handle_input (GtkIMContext *input_method,
              gchar        *text,
              AppData      *app_data)
{
  play_characters_in_string (text, app_data);
}

static void
handle_clipboard_recv (GtkClipboard *clipboard,
                       const gchar  *text,
                       AppData      *app_data)
{
  play_characters_in_string (text, app_data);
}

static gboolean
handle_paste (GtkAccelGroup *accel_group,
              GObject *acceleratable,
              guint accel_key,
              GdkModifierType accel_mod,
              AppData *app_data)
{
  GdkDisplay *display;
  GtkClipboard *clipboard;

  display = gtk_widget_get_display (app_data->gallow);
  clipboard = gtk_clipboard_get_default (display);

  gtk_clipboard_request_text (clipboard,
                              (GtkClipboardTextReceivedFunc)
                              handle_clipboard_recv,
                              app_data);

  return FALSE;
}

static gboolean
handle_key_press (GtkWidget   *window,
                  GdkEventKey *key,
                  AppData     *app_data)
{
  guint accel_key;
  GdkModifierType accel_mods;
  gint state;
  GtkIMContext *input_method;

  accel_key = key->keyval;
  accel_mods = key->state;
  gtk_accel_group_activate (app_data->accel_group,
                            0, /* no detail for accel-activate */
                            G_OBJECT (window),
                            accel_key,
                            accel_mods);

  state = app_data->game_data->state;
  if (state == -1 || state == 6)
    {
      new_game (app_data);
      return FALSE;
    }

  input_method = app_data->input_method;
  gtk_im_context_filter_keypress (input_method, key);

  return FALSE;
}

static gdouble lines[] =
{
  /* gallow */
   0.375,   0.35,    0.5,   0.25,
   0.625,   0.35,    0.5,   0.25,
     0.5,   0.25,    0.5,  -0.75,
     0.5,  -0.75, -0.125,  -0.75,
  -0.125,  -0.75, -0.125,   -0.5,
  /* hangman sans head */
  -0.125,  -0.25, -0.125,  0.375,
   -0.35,  0.125,  -0.13, -0.125,
     0.1,  0.125,  -0.12, -0.125,
   -0.35,  0.625,  -0.13,  0.375,
     0.1,  0.625,  -0.12,  0.375
};

static gboolean
draw_callback (GtkWidget *widget,
               cairo_t   *cr,
               GameData  *game_data)
{
  gint state;

  GtkStyleContext *style;
  GtkStateFlags    widget_state;
  GdkRGBA          draw_color;

  gdouble width, height;

  gint i;

  state = game_data->state;

  /* Set foreground color from theme. */
  style = gtk_widget_get_style_context (widget);
  widget_state = gtk_style_context_get_state (style);
  gtk_style_context_get_color (style, widget_state, &draw_color);
  gdk_cairo_set_source_rgba (cr, &draw_color);

  width = gtk_widget_get_allocated_width (widget);
  height = gtk_widget_get_allocated_height (widget);

  if (width == 0.0 || height == 0.0)
    return FALSE;

  cairo_save (cr);

  cairo_scale (cr, 0.5 * width, 0.5 * height);
  cairo_translate (cr, 1.0, 1.0);
  cairo_scale (cr, height / width, 1.0);

  if (state >= 1)
    {
      cairo_arc (cr,
                 -0.125, -0.375,
                 0.125,
                 0, 2 * G_PI);
      state--;
    }

  for (i = 0; i < state + 5; i++)
    {
      cairo_move_to (cr,
                     lines[4 * i + 0],
                     lines[4 * i + 1]);
      cairo_line_to (cr,
                     lines[4 * i + 2],
                     lines[4 * i + 3]);
    }

  cairo_set_line_width (cr, 0.05);
  cairo_set_line_cap (cr, CAIRO_LINE_CAP_SQUARE);
  cairo_stroke (cr);

  cairo_restore (cr);

  return FALSE;
}

static void
app_activate (GApplication *app)
{
  GList *window_list;
  GtkWindow *window;

  window_list = gtk_application_get_windows (GTK_APPLICATION (app));
  g_assert_nonnull (window_list);

  window = GTK_WINDOW (window_list->data);

  gtk_window_present (window);
}

static void
app_startup (GApplication *app)
{
  GtkWidget *window, *grid, *gallow, *guessed;

  GtkIMContext *input_method;

  GameData *game_data;
  AppData *app_data;

  GtkAccelGroup *accel_group;
  GClosure *handle_paste_closure;
  guint accel_key;
  GdkModifierType accel_mods;

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_default_size (GTK_WINDOW (window),
                               370,
                               300);
  gtk_widget_set_events (window,
                         gtk_widget_get_events (window) |
                         GDK_KEY_PRESS_MASK);

  grid = gtk_grid_new ();
  gtk_orientable_set_orientation (GTK_ORIENTABLE (grid),
                                  GTK_ORIENTATION_VERTICAL);

  gallow = gtk_drawing_area_new ();
  g_object_set (G_OBJECT (gallow),
                "expand", TRUE,
                NULL);

  guessed = gtk_label_new (NULL);
  g_object_set (G_OBJECT (guessed),
                "margin-top", 8,
                "margin-bottom", 8,
                NULL);

  gtk_container_add (GTK_CONTAINER (window),
                     grid);
  gtk_container_add (GTK_CONTAINER (grid),
                     gallow);
  gtk_container_add (GTK_CONTAINER (grid),
                     guessed);

  input_method = gtk_im_multicontext_new ();
  gtk_im_context_set_use_preedit (input_method, FALSE);

  game_data = g_malloc0 (sizeof (GameData));

  app_data = g_malloc (sizeof (AppData));

  handle_paste_closure = g_cclosure_new (G_CALLBACK (handle_paste),
                                         app_data,
                                         NULL);

  /* This accelerator group gets activated by handle_key_press. */
  accel_group = gtk_accel_group_new ();
  gtk_accelerator_parse ("<Control>v", &accel_key, &accel_mods);
  gtk_accel_group_connect (accel_group,
                           accel_key,
                           accel_mods,
                           0,
                           handle_paste_closure);
  gtk_window_add_accel_group (GTK_WINDOW (window), accel_group);

  app_data->game_data = game_data;
  app_data->guessed = GTK_LABEL (guessed);
  app_data->gallow = gallow;
  app_data->input_method = input_method;
  app_data->accel_group = accel_group;

  new_game (app_data);

  g_signal_connect (gallow,
                    "draw",
                    G_CALLBACK (draw_callback),
                    game_data);
  g_signal_connect (window,
                    "key-press-event",
                    G_CALLBACK (handle_key_press),
                    app_data);
  g_signal_connect (input_method,
                    "commit",
                    G_CALLBACK (handle_input),
                    app_data);

  gtk_application_add_window (GTK_APPLICATION (app),
                              GTK_WINDOW (window));
  gtk_widget_show_all (window);
}

int
main (int argc,
      char **argv)
{
  GtkApplication *app;

  app = gtk_application_new ("de.pelzflorian.Hangman",
                             G_APPLICATION_FLAGS_NONE);

  g_signal_connect (app,
                    "activate",
                    G_CALLBACK (app_activate),
                    app);
  g_signal_connect (app,
                    "startup",
                    G_CALLBACK (app_startup),
                    NULL);

  g_application_register (G_APPLICATION (app), NULL, NULL);

  return g_application_run (G_APPLICATION (app),
                            argc,
                            argv);
}