summaryrefslogtreecommitdiff
path: root/demos/gtk-demo/peg_solitaire.c
blob: 00fdca3d56c3437ac55f75849b0c9ec8808010e8 (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
/* Peg Solitaire
 *
 * This demo demonstrates how to use drag'n'drop to implement peg solitaire.
 *
 */

#include <gtk/gtk.h>

static GtkWidget *window = NULL;

/* Create an object for the pegs that get moved around in the game.
 *
 * We implement the GdkPaintable interface for them, so we can use GtkPicture
 * objects for the wholes we put the pegs into.
 */
#define SOLITAIRE_TYPE_PEG (solitaire_peg_get_type ())
G_DECLARE_FINAL_TYPE (SolitairePeg, solitaire_peg, SOLITAIRE, PEG, GObject)

/* Declare the struct. */
struct _SolitairePeg
{
  GObject parent_instance;

  int x;
  int y;
};

struct _SolitairePegClass
{
  GObjectClass parent_class;
};

/* Here, we implement the functionality required by the GdkPaintable interface */
static void
solitaire_peg_snapshot (GdkPaintable *paintable,
                        GdkSnapshot  *snapshot,
                        double        width,
                        double        height)
{
  /* The snapshot function is the only function we need to implement.
   * It does the actual drawing of the paintable.
   */
  gtk_snapshot_append_color (snapshot,
                             &(GdkRGBA) { 0.6, 0.3, 0.0, 1.0 },
                             &GRAPHENE_RECT_INIT (0, 0, width, height));
}

static GdkPaintableFlags
solitaire_peg_get_flags (GdkPaintable *paintable)
{
  /* The flags are very useful to let GTK know that this image
   * is never going to change.
   * This allows many optimizations and should therefore always
   * be set.
   */
  return GDK_PAINTABLE_STATIC_CONTENTS | GDK_PAINTABLE_STATIC_SIZE;
}

static void
solitaire_peg_paintable_init (GdkPaintableInterface *iface)
{
  iface->snapshot = solitaire_peg_snapshot;
  iface->get_flags = solitaire_peg_get_flags;
}

/* When defining the GType, we need to implement the GdkPaintable interface */
G_DEFINE_TYPE_WITH_CODE (SolitairePeg, solitaire_peg, G_TYPE_OBJECT,
                         G_IMPLEMENT_INTERFACE (GDK_TYPE_PAINTABLE,
                                                solitaire_peg_paintable_init))

/* Here's the boilerplate for the GObject declaration.
 * We don't need to do anything special here, because we keep no
 * data of our own.
 */
static void
solitaire_peg_class_init (SolitairePegClass *klass)
{
}

static void
solitaire_peg_init (SolitairePeg *peg)
{
}

/* Add a little setter for the peg's position.
 * We want to track those so that we can check for legal moves
 * during drag'n'drop operations.
 */
static void
solitaire_peg_set_position (SolitairePeg *peg,
                            guint         x,
                            guint         y)
{
  peg->x = x;
  peg->y = y;
}

/* And finally, we add a simple constructor.
 */
static SolitairePeg *
solitaire_peg_new (void)
{
  return g_object_new (SOLITAIRE_TYPE_PEG, NULL);
}

/*** DRAG AND DROP ***/

/* The user tries to start a drag operation.
 * We check if the image contains a peg, and if so, we return the
 * peg as the content to be dragged.
 */
static GdkContentProvider *
drag_prepare (GtkDragSource *source,
              double         x,
              double         y,
              GtkWidget     *image)
{
  GdkPaintable *paintable = gtk_image_get_paintable (GTK_IMAGE (image));

  if (!SOLITAIRE_IS_PEG (paintable))
    return NULL;

  return gdk_content_provider_new_typed (SOLITAIRE_TYPE_PEG, paintable);
}

/* This notifies us that the drag has begun.
 * We can now set up the icon and the widget for the ongoing drag.
 */
static void
drag_begin (GtkDragSource *source,
            GdkDrag       *drag,
            GtkWidget     *image)
{
  GdkPaintable *paintable = gtk_image_get_paintable (GTK_IMAGE (image));

  /* We guaranteed in the drag_prepare function above that we
   * only start a drag if a peg is available.
   * So let's make sure we did not screw that up.
   */
  g_assert (SOLITAIRE_IS_PEG (paintable));

  /* We use the peg as the drag icon.
   */
  gtk_drag_source_set_icon (source, paintable, -2, -2);

  /* We also attach it to the drag operation as custom user data,
   * so that we can get it back later if the drag fails.
   */
  g_object_set_data (G_OBJECT (drag), "the peg", paintable);

  /* Because we are busy dragging the peg, we want to unset it
   * on the image.
   */
  gtk_image_clear (GTK_IMAGE (image));
}

/* Thie is called once a drag operation has ended (successfully or not).
 * We want to undo what we did in drag_begin() above and react
 * to a potential move of the peg.
 */
static void
drag_end (GtkDragSource *source,
          GdkDrag       *drag,
          gboolean       delete_data,
          GtkWidget     *image)
{
  SolitairePeg *peg;

  /* If the drag was successful, we should now delete the peg.
   * We did this in drag_begin() above to prepare for the drag, so
   * there's no need to do anything anymore.
   */
  if (delete_data)
    return;

  /* However, if the drag did not succeed, we need to undo what
   * we did in drag_begin() and reinsert the peg here.
   * Because we used it as the drag data
   */
  peg = g_object_get_data (G_OBJECT (drag), "the peg");
  gtk_image_set_from_paintable (GTK_IMAGE (image), GDK_PAINTABLE (peg));
}

/* Whenever a new drop operation starts, we need to check if we can
 * accept it.
 * The default check unfortunately is not good enough, because it only
 * checks the data type. But we also need to check if our image can
 * even accept data.
 */
static gboolean
drop_accept (GtkDropTarget *target,
             GdkDrop       *drop,
             GtkWidget     *image)
{
  /* First, check the drop is actually trying to drop a peg */
  if (!gdk_content_formats_contain_gtype (gdk_drop_get_formats (drop), SOLITAIRE_TYPE_PEG))
    return FALSE;

  /* If the image already contains a peg, we cannot accept another one */
  if (SOLITAIRE_IS_PEG (gtk_image_get_paintable (GTK_IMAGE (image))))
    return FALSE;

  return TRUE;
}

static gboolean
drop_drop (GtkDropTarget *target,
           const GValue  *value,
           double         x,
           double         y,
           GtkWidget     *image)
{
  GtkGrid *grid;
  SolitairePeg *peg;
  int image_x, image_y;
  GtkWidget *jumped;

  grid = GTK_GRID (gtk_widget_get_parent (image));
  /* The value contains the data in the type we demanded.
   * We demanded a SolitairePeg, so that's what we get.
   */
  peg = g_value_get_object (value);

  /* Make sure this was a legal move. */
  /* First, figure out the image's position in the grid. */
  gtk_grid_query_child (grid,
                        image,
                        &image_x, &image_y,
                        NULL, NULL);

  /* If the peg was not moved 2 spaces horizontally or vertically,
   * this was not a valid jump. Reject it.
   */
  if (!((ABS (image_x - peg->x) == 2 && image_y == peg->y) ||
        (ABS (image_y - peg->y) == 2 && image_x == peg->x)))
    return FALSE;

  /* Get the widget that was jumped over
   */
  jumped = gtk_grid_get_child_at (grid,
                                  (image_x + peg->x) / 2,
                                  (image_y + peg->y) / 2);
  /* If the jumped widget does not have a peg in it, this move
   * isn't valid.
   */
  if (!SOLITAIRE_IS_PEG (gtk_image_get_paintable (GTK_IMAGE (jumped))))
    return FALSE;

  /* Finally, we know it's a legal move. */

  /* Clear the peg of the jumped-over image */
  gtk_image_clear (GTK_IMAGE (jumped));

  /* Add the peg to this image */
  solitaire_peg_set_position (peg, image_x, image_y);
  gtk_image_set_from_paintable (GTK_IMAGE (image), GDK_PAINTABLE (peg));

  /* Success! */
  return TRUE;
}

GtkWidget *
do_peg_solitaire (GtkWidget *do_widget)
{
  if (!window)
    {
      GtkWidget *header;
      GtkWidget *restart;
      GtkWidget *grid;
      GtkWidget *image;
      int x, y;
      GtkDragSource *source;
      GtkDropTarget *target;

      restart = gtk_button_new_from_icon_name ("view-refresh-symbolic");
      g_signal_connect (restart, "clicked", G_CALLBACK (restart), NULL);

      header = gtk_header_bar_new ();
      gtk_header_bar_set_show_title_buttons (GTK_HEADER_BAR (header), TRUE);
      gtk_header_bar_pack_start (GTK_HEADER_BAR (header), restart);
      window = gtk_window_new ();
      gtk_window_set_display (GTK_WINDOW (window),
                              gtk_widget_get_display (do_widget));
      gtk_window_set_title (GTK_WINDOW (window), "Peg Solitaire");
      gtk_window_set_titlebar (GTK_WINDOW (window), header);
      gtk_window_set_default_size (GTK_WINDOW (window), 400, 300);
      g_signal_connect (window, "destroy",
                        G_CALLBACK (gtk_widget_destroyed), &window);

      grid = gtk_grid_new ();
      gtk_widget_set_halign (grid, GTK_ALIGN_CENTER);
      gtk_widget_set_valign (grid, GTK_ALIGN_CENTER);
      gtk_grid_set_row_spacing (GTK_GRID (grid), 6);
      gtk_grid_set_column_spacing (GTK_GRID (grid), 6);
      gtk_grid_set_row_homogeneous (GTK_GRID (grid), TRUE);
      gtk_grid_set_column_homogeneous (GTK_GRID (grid), TRUE);
      gtk_window_set_child (GTK_WINDOW (window), grid);

      for (x = 0; x < 7; x++)
        {
          for (y = 0; y < 7; y++)
            {
              if ((x < 2 || x >= 5) && (y < 2 || y >= 5))
                continue;

              image = gtk_image_new ();
              if (x != 3 || y != 3)
                {
                  SolitairePeg *peg = solitaire_peg_new ();
                  solitaire_peg_set_position (peg, x, y);
                  gtk_image_set_from_paintable (GTK_IMAGE (image), GDK_PAINTABLE (peg));
                }

              gtk_grid_attach (GTK_GRID (grid), image, x, y, 1, 1);

              /* Set up the drag source.
               * This is rather straightforward: Set the supported actions
               * (in our case, pegs can only be moved) and connect all the
               * relevant signals.
               * And because all drag'n'drop handling is done via event controllers,
               * we need to add the controller to the widget.
               */
              source = gtk_drag_source_new ();
              gtk_drag_source_set_actions (source, GDK_ACTION_MOVE);
              g_signal_connect (source, "prepare", G_CALLBACK (drag_prepare), image);
              g_signal_connect (source, "drag-begin", G_CALLBACK (drag_begin), image);
              g_signal_connect (source, "drag-end", G_CALLBACK (drag_end), image);
              gtk_widget_add_controller (image, GTK_EVENT_CONTROLLER (source));

              /* Set up the drop target.
               * This is more involved, because the game logic goes here.
               */

              /* First we specify the data we accept: pegs.
               * And we only want moves.
               */
              target = gtk_drop_target_new (SOLITAIRE_TYPE_PEG, GDK_ACTION_MOVE);
              /* Then we connect our signals.
               */
              g_signal_connect (target, "accept", G_CALLBACK (drop_accept), image);
              g_signal_connect (target, "drop", G_CALLBACK (drop_drop), image);
              /* Finally, like above, we add it to the widget.
               */
              gtk_widget_add_controller (image, GTK_EVENT_CONTROLLER (target));
            }
        }
    }

  if (!gtk_widget_get_visible (window))
    gtk_widget_show (window);
  else
    gtk_widget_destroy (window);

  return window;
}