pygi-marshal-from-py.c 62.5 KB
Newer Older
1
2
3
/* -*- Mode: C; c-basic-offset: 4 -*-
 * vim: tabstop=4 shiftwidth=4 expandtab
 *
4
 * Copyright (C) 2011 John (J5) Palmieri <johnp@redhat.com>,  Red Hat, Inc.
5
 *
6
 *   pygi-marshal-from-py.c: Functions to convert PyObjects to C types.
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
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
 * USA
 */

#include "pygi-private.h"

#include <string.h>
#include <time.h>
#include <pygobject.h>
#include <pyglib-python-compat.h>

#include "pygi-cache.h"
32
#include "pygi-marshal-cleanup.h"
33
#include "pygi-marshal-from-py.h"
34

35
static gboolean
David Malcolm's avatar
David Malcolm committed
36
37
38
39
40
41
42
gi_argument_from_py_ssize_t (GIArgument   *arg_out,
                             Py_ssize_t    size_in,
                             GITypeTag     type_tag)                             
{
    switch (type_tag) {
    case GI_TYPE_TAG_VOID:
    case GI_TYPE_TAG_BOOLEAN:
43
44
        goto unhandled_type;

David Malcolm's avatar
David Malcolm committed
45
    case GI_TYPE_TAG_INT8:
46
47
48
49
50
51
52
        if (size_in >= G_MININT8 && size_in <= G_MAXINT8) {
            arg_out->v_int8 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

David Malcolm's avatar
David Malcolm committed
53
    case GI_TYPE_TAG_UINT8:
54
55
56
57
58
59
60
        if (size_in >= 0 && size_in <= G_MAXUINT8) {
            arg_out->v_uint8 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

David Malcolm's avatar
David Malcolm committed
61
    case GI_TYPE_TAG_INT16:
62
63
64
65
66
67
68
        if (size_in >= G_MININT16 && size_in <= G_MAXINT16) {
            arg_out->v_int16 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

David Malcolm's avatar
David Malcolm committed
69
    case GI_TYPE_TAG_UINT16:
70
71
72
73
74
75
        if (size_in >= 0 && size_in <= G_MAXUINT16) {
            arg_out->v_uint16 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }
David Malcolm's avatar
David Malcolm committed
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

        /* Ranges assume two's complement */
    case GI_TYPE_TAG_INT32:
        if (size_in >= G_MININT32 && size_in <= G_MAXINT32) {
            arg_out->v_int32 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

    case GI_TYPE_TAG_UINT32:
        if (size_in >= 0 && size_in <= G_MAXUINT32) {
            arg_out->v_uint32 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }

    case GI_TYPE_TAG_INT64:
        arg_out->v_int64 = size_in;
        return TRUE;

    case GI_TYPE_TAG_UINT64:
        if (size_in >= 0) {
            arg_out->v_uint64 = size_in;
            return TRUE;
        } else {
            goto overflow;
        }
            
    case GI_TYPE_TAG_FLOAT:
    case GI_TYPE_TAG_DOUBLE:
    case GI_TYPE_TAG_GTYPE:
    case GI_TYPE_TAG_UTF8:
    case GI_TYPE_TAG_FILENAME:
    case GI_TYPE_TAG_ARRAY:
    case GI_TYPE_TAG_INTERFACE:
    case GI_TYPE_TAG_GLIST:
    case GI_TYPE_TAG_GSLIST:
    case GI_TYPE_TAG_GHASH:
    case GI_TYPE_TAG_ERROR:
    case GI_TYPE_TAG_UNICHAR:
    default:
        goto unhandled_type;
    }

 overflow:
    PyErr_Format (PyExc_OverflowError,
                  "Unable to marshal C Py_ssize_t %zd to %s",
                  size_in,
                  g_type_tag_to_string (type_tag));
    return FALSE;

 unhandled_type:
    PyErr_Format (PyExc_TypeError,
                  "Unable to marshal C Py_ssize_t %zd to %s",
                  size_in,
                  g_type_tag_to_string (type_tag));
    return FALSE;
}

137
static gboolean
David Malcolm's avatar
David Malcolm committed
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
gi_argument_from_c_long (GIArgument *arg_out,
                         long        c_long_in,
                         GITypeTag   type_tag)
{
    switch (type_tag) {
      case GI_TYPE_TAG_INT8:
          arg_out->v_int8 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT8:
          arg_out->v_uint8 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_INT16:
          arg_out->v_int16 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT16:
          arg_out->v_uint16 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_INT32:
          arg_out->v_int32 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT32:
          arg_out->v_uint32 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_INT64:
          arg_out->v_int64 = c_long_in;
          return TRUE;
      case GI_TYPE_TAG_UINT64:
          arg_out->v_uint64 = c_long_in;
          return TRUE;
      default:
          PyErr_Format (PyExc_TypeError,
                        "Unable to marshal C long %ld to %s",
                        c_long_in,
                        g_type_tag_to_string (type_tag));
          return FALSE;
    }
}

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
/*
 * _is_union_member - check to see if the py_arg is actually a member of the
 * expected C union
 */
static gboolean
_is_union_member (PyGIInterfaceCache *iface_cache, PyObject *py_arg) {
    gint i;
    gint n_fields;
    GIUnionInfo *union_info;
    GIInfoType info_type;
    gboolean is_member = FALSE;

    info_type = g_base_info_get_type (iface_cache->interface_info);

    if (info_type != GI_INFO_TYPE_UNION)
        return FALSE;

    union_info = (GIUnionInfo *) iface_cache->interface_info;
    n_fields = g_union_info_get_n_fields (union_info);

    for (i = 0; i < n_fields; i++) {
        GIFieldInfo *field_info;
        GITypeInfo *field_type_info;

        field_info = g_union_info_get_field (union_info, i);
        field_type_info = g_field_info_get_type (field_info);

        /* we can only check if the members are interfaces */
        if (g_type_info_get_tag (field_type_info) == GI_TYPE_TAG_INTERFACE) {
205
            GIInterfaceInfo *field_iface_info;
206
207
            PyObject *py_type;

208
209
            field_iface_info = g_type_info_get_interface (field_type_info);
            py_type = _pygi_type_import_by_gi_info ((GIBaseInfo *) field_iface_info);
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

            if (py_type != NULL && PyObject_IsInstance (py_arg, py_type)) {
                is_member = TRUE;
            }

            Py_XDECREF (py_type);
            g_base_info_unref ( ( GIBaseInfo *) field_iface_info);
        }

        g_base_info_unref ( ( GIBaseInfo *) field_type_info);
        g_base_info_unref ( ( GIBaseInfo *) field_info);

        if (is_member)
            break;
    }

    return is_member;
}

229
gboolean
230
231
232
233
234
_pygi_marshal_from_py_void (PyGIInvokeState   *state,
                            PyGICallableCache *callable_cache,
                            PyGIArgCache      *arg_cache,
                            PyObject          *py_arg,
                            GIArgument        *arg)
235
236
237
{
    g_warn_if_fail (arg_cache->transfer == GI_TRANSFER_NOTHING);

238
239
240
241
242
    if (PYGLIB_CPointer_Check(py_arg)) {
        arg->v_pointer = PYGLIB_CPointer_GetPointer (py_arg, NULL);
    } else {
        arg->v_pointer = py_arg;
    }
243
244
245
246
247

    return TRUE;
}

gboolean
248
249
250
251
252
_pygi_marshal_from_py_boolean (PyGIInvokeState   *state,
                               PyGICallableCache *callable_cache,
                               PyGIArgCache      *arg_cache,
                               PyObject          *py_arg,
                               GIArgument        *arg)
253
{
254
    arg->v_boolean = PyObject_IsTrue (py_arg);
255
256
257
258
259

    return TRUE;
}

gboolean
260
261
262
263
264
_pygi_marshal_from_py_int8 (PyGIInvokeState   *state,
                            PyGICallableCache *callable_cache,
                            PyGIArgCache      *arg_cache,
                            PyObject          *py_arg,
                            GIArgument        *arg)
265
266
267
268
{
    PyObject *py_long;
    long long_;

269
    if (PYGLIB_PyBytes_Check (py_arg)) {
270

271
272
273
274
        if (PYGLIB_PyBytes_Size (py_arg) != 1) {
            PyErr_Format (PyExc_TypeError, "Must be a single character");
            return FALSE;
        }
275

276
277
278
279
280
        long_ = (char)(PYGLIB_PyBytes_AsString (py_arg)[0]);
    } else if (PyNumber_Check (py_arg)) {
        py_long = PYGLIB_PyNumber_Long (py_arg);
        if (!py_long)
            return FALSE;
281

282
283
284
285
286
287
288
289
290
291
292
        long_ = PYGLIB_PyLong_AsLong (py_long);
        Py_DECREF (py_long);

        if (PyErr_Occurred ()) {
            PyErr_Clear ();
            PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, -128, 127);
            return FALSE;
        }
    } else {
        PyErr_Format (PyExc_TypeError, "Must be number or single byte string, not %s",
                      py_arg->ob_type->tp_name);
293
        return FALSE;
294
    }
295
296
297
298
299
300

    if (long_ < -128 || long_ > 127) {
        PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, -128, 127);
        return FALSE;
    }

301
    arg->v_int8 = long_;
302
303
304
305
306

    return TRUE;
}

gboolean
307
308
309
310
311
_pygi_marshal_from_py_uint8 (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
312
313
314
{
    unsigned long long_;

315
    if (PYGLIB_PyBytes_Check (py_arg)) {
316

317
        if (PYGLIB_PyBytes_Size (py_arg) != 1) {
318
319
320
321
            PyErr_Format (PyExc_TypeError, "Must be a single character");
            return FALSE;
        }

322
        long_ = (unsigned char)(PYGLIB_PyBytes_AsString (py_arg)[0]);
323

324
    } else if (PyNumber_Check (py_arg)) {
325
        PyObject *py_long;
326
        py_long = PYGLIB_PyNumber_Long (py_arg);
327
328
329
        if (!py_long)
            return FALSE;

330
331
        long_ = PYGLIB_PyLong_AsLong (py_long);
        Py_DECREF (py_long);
332

333
334
335
336
        if (PyErr_Occurred ()) {
            PyErr_Clear();

            PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, 0, 255);
337
            return FALSE;
338
        }
339
340
341
342
343
344
345
346
347
348
349
    } else {
        PyErr_Format (PyExc_TypeError, "Must be number or single byte string, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    if (long_ < 0 || long_ > 255) {
        PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, 0, 255);
        return FALSE;
    }

350
    arg->v_uint8 = long_;
351
352
353
354
355

    return TRUE;
}

gboolean
356
357
358
359
360
_pygi_marshal_from_py_int16 (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
361
362
363
364
{
    PyObject *py_long;
    long long_;

365
    if (!PyNumber_Check (py_arg)) {
366
367
368
369
370
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

371
    py_long = PYGLIB_PyNumber_Long (py_arg);
372
373
374
    if (!py_long)
        return FALSE;

375
376
    long_ = PYGLIB_PyLong_AsLong (py_long);
    Py_DECREF (py_long);
377

378
379
380
    if (PyErr_Occurred ()) {
        PyErr_Clear ();
        PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, -32768, 32767);
381
        return FALSE;
382
    }
383
384
385
386
387
388

    if (long_ < -32768 || long_ > 32767) {
        PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, -32768, 32767);
        return FALSE;
    }

389
    arg->v_int16 = long_;
390
391
392
393
394

    return TRUE;
}

gboolean
395
396
397
398
399
_pygi_marshal_from_py_uint16 (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
                              GIArgument        *arg)
400
401
402
403
{
    PyObject *py_long;
    long long_;

404
    if (!PyNumber_Check (py_arg)) {
405
406
407
408
409
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

410
    py_long = PYGLIB_PyNumber_Long (py_arg);
411
412
413
    if (!py_long)
        return FALSE;

414
415
    long_ = PYGLIB_PyLong_AsLong (py_long);
    Py_DECREF (py_long);
416

417
418
    if (PyErr_Occurred ()) {
        PyErr_Clear ();
419
        PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, 0, 65535);
420
        return FALSE;
421
    }
422
423

    if (long_ < 0 || long_ > 65535) {
424
        PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, 0, 65535);
425
426
427
        return FALSE;
    }

428
    arg->v_uint16 = long_;
429
430
431
432
433

    return TRUE;
}

gboolean
434
435
436
437
438
_pygi_marshal_from_py_int32 (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
439
440
441
442
{
    PyObject *py_long;
    long long_;

443
    if (!PyNumber_Check (py_arg)) {
444
445
446
447
448
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

449
    py_long = PYGLIB_PyNumber_Long (py_arg);
450
451
452
    if (!py_long)
        return FALSE;

453
454
    long_ = PYGLIB_PyLong_AsLong (py_long);
    Py_DECREF (py_long);
455

456
457
458
    if (PyErr_Occurred ()) {
        PyErr_Clear();
        PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, G_MININT32, G_MAXINT32);
459
        return FALSE;
460
    }
461
462
463
464
465
466

    if (long_ < G_MININT32 || long_ > G_MAXINT32) {
        PyErr_Format (PyExc_ValueError, "%ld not in range %d to %d", long_, G_MININT32, G_MAXINT32);
        return FALSE;
    }

467
    arg->v_int32 = long_;
468
469
470
471
472

    return TRUE;
}

gboolean
473
474
475
476
477
_pygi_marshal_from_py_uint32 (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
                              GIArgument        *arg)
478
479
480
481
{
    PyObject *py_long;
    long long long_;

482
    if (!PyNumber_Check (py_arg)) {
483
484
485
486
487
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

488
    py_long = PYGLIB_PyNumber_Long (py_arg);
489
490
491
492
493
494
495
496
    if (!py_long)
        return FALSE;

#if PY_VERSION_HEX < 0x03000000
    if (PyInt_Check (py_long))
        long_ = PyInt_AsLong (py_long);
    else
#endif
497
        long_ = PyLong_AsLongLong (py_long);
498

499
    Py_DECREF (py_long);
500

501
502
    if (PyErr_Occurred ()) {
        PyErr_Clear ();
503
        PyErr_Format (PyExc_ValueError, "%lld not in range %i to %u", long_, 0, G_MAXUINT32);
504
        return FALSE;
505
    }
506
507

    if (long_ < 0 || long_ > G_MAXUINT32) {
508
        PyErr_Format (PyExc_ValueError, "%lld not in range %i to %u", long_, 0, G_MAXUINT32);
509
510
511
        return FALSE;
    }

512
    arg->v_uint32 = long_;
513
514
515
516
517

    return TRUE;
}

gboolean
518
519
520
521
522
_pygi_marshal_from_py_int64 (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
523
524
{
    PyObject *py_long;
525
    gint64 long_;
526

527
    if (!PyNumber_Check (py_arg)) {
528
529
530
531
532
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

533
    py_long = PYGLIB_PyNumber_Long (py_arg);
534
535
536
537
538
    if (!py_long)
        return FALSE;

#if PY_VERSION_HEX < 0x03000000
    if (PyInt_Check (py_long))
539
        long_ = (gint64) PyInt_AS_LONG (py_long);
540
541
    else
#endif
542
        long_ = (gint64) PyLong_AsLongLong (py_long);
543

544
    Py_DECREF (py_long);
545

546
    if (PyErr_Occurred ()) {
547
548
        /* OverflowError occured but range errors should be returned as ValueError */
        char *long_str;
549
550
551
552
553
        PyObject *py_str;

        PyErr_Clear ();

        py_str = PyObject_Str (py_long);
554

555
556
        if (PyUnicode_Check (py_str)) {
            PyObject *py_bytes = PyUnicode_AsUTF8String (py_str);
557
558
            Py_DECREF (py_str);

559
560
561
            if (py_bytes == NULL)
                return FALSE;

562
            long_str = g_strdup (PYGLIB_PyBytes_AsString (py_bytes));
563
            if (long_str == NULL) {
564
                PyErr_NoMemory ();
565
566
567
                return FALSE;
            }

568
            Py_DECREF (py_bytes);
569
        } else {
570
            long_str = g_strdup (PYGLIB_PyBytes_AsString(py_str));
571
            Py_DECREF (py_str);
572
573
        }

574
575
        PyErr_Format (PyExc_ValueError, "%s not in range %lld to %lld",
                      long_str, (long long) G_MININT64, (long long) G_MAXINT64);
576

577
        g_free (long_str);
578
579
580
581
582
583
584
585
586
        return FALSE;
    }

    arg->v_int64 = long_;

    return TRUE;
}

gboolean
587
588
589
590
591
_pygi_marshal_from_py_uint64 (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
                              GIArgument        *arg)
592
593
594
595
{
    PyObject *py_long;
    guint64 ulong_;

596
    if (!PyNumber_Check (py_arg)) {
597
598
599
600
601
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

602
    py_long = PYGLIB_PyNumber_Long (py_arg);
603
604
605
606
607
    if (!py_long)
        return FALSE;

#if PY_VERSION_HEX < 0x03000000
    if (PyInt_Check (py_long)) {
608
609
        long long_ =  PyInt_AsLong (py_long);
        if (long_ < 0 || long_ > G_MAXUINT64) {
610
611
            PyErr_Format (PyExc_ValueError, "%" G_GUINT64_FORMAT " not in range %d to %" G_GUINT64_FORMAT,
                          (gint64) long_, 0, G_MAXUINT64);
612
613
            return FALSE;
        }
614
        ulong_ = (guint64) long_;
615
616
    } else
#endif
617
        ulong_ = PyLong_AsUnsignedLongLong (py_long);
618

619
    Py_DECREF (py_long);
620

621
    if (PyErr_Occurred ()) {
622
623
        /* OverflowError occured but range errors should be returned as ValueError */
        char *long_str;
624
625
626
627
628
        PyObject *py_str;

        PyErr_Clear ();

        py_str = PyObject_Str (py_long);
629

630
631
        if (PyUnicode_Check (py_str)) {
            PyObject *py_bytes = PyUnicode_AsUTF8String (py_str);
632
633
            Py_DECREF (py_str);

634
635
636
            if (py_bytes == NULL)
                return FALSE;

637
            long_str = g_strdup (PYGLIB_PyBytes_AsString (py_bytes));
638
            if (long_str == NULL) {
639
                PyErr_NoMemory ();
640
641
642
                return FALSE;
            }

643
            Py_DECREF (py_bytes);
644
        } else {
645
            long_str = g_strdup (PYGLIB_PyBytes_AsString (py_str));
646
            Py_DECREF (py_str);
647
648
        }

649
        PyErr_Format (PyExc_ValueError, "%s not in range %d to %" G_GUINT64_FORMAT,
650
                      long_str, 0, G_MAXUINT64);
651

652
        g_free (long_str);
653
654
655
656
        return FALSE;
    }

    if (ulong_ > G_MAXUINT64) {
657
        PyErr_Format (PyExc_ValueError, "%" G_GUINT64_FORMAT " not in range %d to %" G_GUINT64_FORMAT, ulong_, 0, G_MAXUINT64);
658
659
660
661
662
663
664
665
        return FALSE;
    }

    arg->v_uint64 = ulong_;

    return TRUE;
}

666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
static gboolean
check_valid_double (double x, double min, double max)
{
    char buf[100];

    if ((x < min || x > max) && x != INFINITY && x != -INFINITY && x != NAN) {
        if (PyErr_Occurred())
            PyErr_Clear ();

        /* we need this as PyErr_Format() does not support float types */
        snprintf (buf, sizeof (buf), "%g not in range %g to %g", x, min, max);
        PyErr_SetString (PyExc_ValueError, buf);
        return FALSE;
    }
    return TRUE;
}

683
gboolean
684
685
686
687
688
_pygi_marshal_from_py_float (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
689
690
691
692
{
    PyObject *py_float;
    double double_;

693
    if (!PyNumber_Check (py_arg)) {
694
695
696
697
698
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

699
    py_float = PyNumber_Float (py_arg);
700
701
702
    if (!py_float)
        return FALSE;

703
704
    double_ = PyFloat_AsDouble (py_float);
    Py_DECREF (py_float);
705

706
    if (PyErr_Occurred () || !check_valid_double (double_, -G_MAXFLOAT, G_MAXFLOAT))
707
708
709
710
711
712
713
714
        return FALSE;

    arg->v_float = double_;

    return TRUE;
}

gboolean
715
716
717
718
719
_pygi_marshal_from_py_double (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
                              GIArgument        *arg)
720
721
722
723
{
    PyObject *py_float;
    double double_;

724
    if (!PyNumber_Check (py_arg)) {
725
726
727
728
729
        PyErr_Format (PyExc_TypeError, "Must be number, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

730
    py_float = PyNumber_Float (py_arg);
731
732
733
    if (!py_float)
        return FALSE;

734
735
    double_ = PyFloat_AsDouble (py_float);
    Py_DECREF (py_float);
736

737
    if (PyErr_Occurred () || !check_valid_double (double_, -G_MAXDOUBLE, G_MAXDOUBLE))
738
739
740
741
742
743
744
745
        return FALSE;

    arg->v_double = double_;

    return TRUE;
}

gboolean
746
747
748
749
750
_pygi_marshal_from_py_unichar (PyGIInvokeState   *state,
                               PyGICallableCache *callable_cache,
                               PyGIArgCache      *arg_cache,
                               PyObject          *py_arg,
                               GIArgument        *arg)
751
752
753
754
755
756
757
758
{
    Py_ssize_t size;
    gchar *string_;

    if (PyUnicode_Check (py_arg)) {
       PyObject *py_bytes;

       size = PyUnicode_GET_SIZE (py_arg);
759
760
761
       py_bytes = PyUnicode_AsUTF8String (py_arg);
       string_ = strdup(PYGLIB_PyBytes_AsString (py_bytes));
       Py_DECREF (py_bytes);
762
763
764
765
766
767
768
769

#if PY_VERSION_HEX < 0x03000000
    } else if (PyString_Check (py_arg)) {
       PyObject *pyuni = PyUnicode_FromEncodedObject (py_arg, "UTF-8", "strict");
       if (!pyuni)
           return FALSE;

       size = PyUnicode_GET_SIZE (pyuni);
770
771
       string_ = g_strdup (PyString_AsString(py_arg));
       Py_DECREF (pyuni);
772
773
774
775
776
777
778
779
#endif
    } else {
       PyErr_Format (PyExc_TypeError, "Must be string, not %s",
                     py_arg->ob_type->tp_name);
       return FALSE;
    }

    if (size != 1) {
780
781
       PyErr_Format (PyExc_TypeError, "Must be a one character string, not %lld characters",
                     (long long) size);
782
       g_free (string_);
783
784
785
       return FALSE;
    }

786
787
    arg->v_uint32 = g_utf8_get_char (string_);
    g_free (string_);
788
789
790
791

    return TRUE;
}
gboolean
792
793
794
795
796
_pygi_marshal_from_py_gtype (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
797
798
799
800
801
802
803
804
805
806
807
808
809
{
    long type_ = pyg_type_from_object (py_arg);

    if (type_ == 0) {
        PyErr_Format (PyExc_TypeError, "Must be gobject.GType, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    arg->v_long = type_;
    return TRUE;
}
gboolean
810
811
812
813
814
_pygi_marshal_from_py_utf8 (PyGIInvokeState   *state,
                            PyGICallableCache *callable_cache,
                            PyGIArgCache      *arg_cache,
                            PyObject          *py_arg,
                            GIArgument        *arg)
815
816
817
818
819
820
821
822
{
    gchar *string_;

    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

823
    if (PyUnicode_Check (py_arg)) {
824
825
826
827
        PyObject *pystr_obj = PyUnicode_AsUTF8String (py_arg);
        if (!pystr_obj)
            return FALSE;

828
829
        string_ = g_strdup (PYGLIB_PyBytes_AsString (pystr_obj));
        Py_DECREF (pystr_obj);
830
831
    }
#if PY_VERSION_HEX < 0x03000000
832
833
    else if (PyString_Check (py_arg)) {
        string_ = g_strdup (PyString_AsString (py_arg));
834
835
836
837
838
839
840
841
842
843
844
845
846
    }
#endif
    else {
        PyErr_Format (PyExc_TypeError, "Must be string, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    arg->v_string = string_;
    return TRUE;
}

gboolean
847
848
849
850
851
_pygi_marshal_from_py_filename (PyGIInvokeState   *state,
                                PyGICallableCache *callable_cache,
                                PyGIArgCache      *arg_cache,
                                PyObject          *py_arg,
                                GIArgument        *arg)
852
853
854
855
{
    gchar *string_;
    GError *error = NULL;

856
    if (PyUnicode_Check (py_arg)) {
857
858
859
860
        PyObject *pystr_obj = PyUnicode_AsUTF8String (py_arg);
        if (!pystr_obj)
            return FALSE;

861
862
        string_ = g_strdup (PYGLIB_PyBytes_AsString (pystr_obj));
        Py_DECREF (pystr_obj);
863
864
    }
#if PY_VERSION_HEX < 0x03000000
865
866
    else if (PyString_Check (py_arg)) {
        string_ = g_strdup (PyString_AsString (py_arg));
867
868
869
870
871
872
873
874
875
    }
#endif
    else {
        PyErr_Format (PyExc_TypeError, "Must be string, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    arg->v_string = g_filename_from_utf8 (string_, -1, NULL, NULL, &error);
876
    g_free (string_);
877
878
879

    if (arg->v_string == NULL) {
        PyErr_SetString (PyExc_Exception, error->message);
880
        g_error_free (error);
881
882
883
884
885
886
887
888
        /* TODO: Convert the error to an exception. */
        return FALSE;
    }

    return TRUE;
}

gboolean
889
890
891
892
893
_pygi_marshal_from_py_array (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
894
{
895
    PyGIMarshalFromPyFunc from_py_marshaller;
896
    int i = 0;
897
    Py_ssize_t length;
898
    gssize item_size;
899
    gboolean is_ptr_array;
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
    GArray *array_ = NULL;
    PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;


    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    if (!PySequence_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

    length = PySequence_Length (py_arg);
    if (length < 0)
        return FALSE;

    if (sequence_cache->fixed_size >= 0 &&
        sequence_cache->fixed_size != length) {
        PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
                      sequence_cache->fixed_size, length);

        return FALSE;
    }

927
    item_size = sequence_cache->item_size;
928
929
930
931
932
933
    is_ptr_array = (sequence_cache->array_type == GI_ARRAY_TYPE_PTR_ARRAY);
    if (is_ptr_array) {
        array_ = (GArray *)g_ptr_array_new ();
    } else {
        array_ = g_array_sized_new (sequence_cache->is_zero_terminated,
                                    FALSE,
934
                                    item_size,
935
936
                                    length);
    }
937
938

    if (array_ == NULL) {
939
        PyErr_NoMemory ();
940
941
942
943
        return FALSE;
    }

    if (sequence_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8 &&
944
945
        PYGLIB_PyBytes_Check (py_arg)) {
        memcpy(array_->data, PYGLIB_PyBytes_AsString (py_arg), length);
Martin Pitt's avatar
Martin Pitt committed
946
        array_->len = length;
947
948
949
950
951
        if (sequence_cache->is_zero_terminated) {
            /* If array_ has been created with zero_termination, space for the
             * terminator is properly allocated, so we're not off-by-one here. */
            array_->data[length] = '\0';
        }
952
953
954
        goto array_success;
    }

955
    from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
956
957
958
959
960
961
    for (i = 0; i < length; i++) {
        GIArgument item;
        PyObject *py_item = PySequence_GetItem (py_arg, i);
        if (py_item == NULL)
            goto err;

962
963
964
965
966
        if (!from_py_marshaller ( state,
                                  callable_cache,
                                  sequence_cache->item_cache,
                                  py_item,
                                 &item))
967
968
            goto err;

969
970
971
972
        /* FIXME: it is much more efficent to have seperate marshaller
         *        for ptr arrays than doing the evaluation
         *        and casting each loop iteration
         */
973
        if (is_ptr_array) {
974
            g_ptr_array_add((GPtrArray *)array_, item.v_pointer);
975
976
977
978
979
980
981
982
983
984
985
986
987
        } else if (sequence_cache->item_cache->type_tag == GI_TYPE_TAG_INTERFACE) {
            PyGIInterfaceCache *item_iface_cache = (PyGIInterfaceCache *) sequence_cache->item_cache;
            GIBaseInfo *base_info = (GIBaseInfo *) item_iface_cache->interface_info;
            GIInfoType info_type = g_base_info_get_type (base_info);

            switch (info_type) {
                case GI_INFO_TYPE_UNION:
                case GI_INFO_TYPE_STRUCT:
                {
                    PyGIArgCache *item_arg_cache = (PyGIArgCache *)item_iface_cache;
                    PyGIMarshalCleanupFunc from_py_cleanup = item_arg_cache->from_py_cleanup;
                    gboolean is_boxed = g_type_is_a (item_iface_cache->g_type, G_TYPE_BOXED);
                    gboolean is_gvalue = item_iface_cache->g_type == G_TYPE_VALUE;
988
989
990
991
992
993
994
                    gboolean is_gvariant = item_iface_cache->g_type == G_TYPE_VARIANT;
                    
                    if (is_gvariant) {
                        /* Item size will always be that of a pointer,
                         * since GVariants are opaque hence always passed by ref */
                        g_assert (item_size == sizeof (item.v_pointer));
                        g_array_insert_val (array_, i, item.v_pointer);
995
996
997
998
999
1000
1001
1002
                    } else if (is_gvalue) {
                        GValue* dest = (GValue*) (array_->data + (i * item_size));
                        memset (dest, 0, item_size);
                        if (item.v_pointer != NULL) {
                            g_value_init (dest, G_VALUE_TYPE ((GValue*) item.v_pointer));
                            g_value_copy ((GValue*) item.v_pointer, dest);
                        }

1003
                        if (from_py_cleanup) {
1004
                            from_py_cleanup (state, item_arg_cache, item.v_pointer, TRUE);
1005
1006
1007
1008
1009
                            /* we freed the original copy already, the new one is a 
                             * struct in an array. _pygi_marshal_cleanup_from_py_array()
                             * must not free it again */
                            item_arg_cache->from_py_cleanup = NULL;
                        }
1010
                    } else if (!is_boxed) {
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
                        /* HACK: Gdk.Atom is merely an integer wrapped in a pointer,
                         * so we must not dereference it; just copy the pointer
                         * value, and don't attempt to free it. TODO: find out
                         * if there are other data types with similar behaviour
                         * and generalize. */
                        if (g_strcmp0 (item_iface_cache->type_name, "Gdk.Atom") == 0) {
                            g_assert (item_size == sizeof (item.v_pointer));
                            memcpy (array_->data + (i * item_size), &item.v_pointer, item_size);
                        } else {
                            memcpy (array_->data + (i * item_size), item.v_pointer, item_size);

                            if (from_py_cleanup)
                                from_py_cleanup (state, item_arg_cache, item.v_pointer, TRUE);
                        }
1025
1026
1027
1028
1029
1030
                    } else if (is_boxed && !item_iface_cache->arg_cache.is_pointer) {
                        /* The array elements are not expected to be pointers, but the
                         * elements obtained are boxed pointers themselves, so insert
                         * the pointed to data.
                         */
                        g_array_insert_vals (array_, i, item.v_pointer, 1);
1031
1032
1033
1034
1035
1036
1037
1038
1039
                    } else {
                        g_array_insert_val (array_, i, item);
                    }
                    break;
                }
                default:
                    g_array_insert_val (array_, i, item);
            }
        } else {
1040
            g_array_insert_val (array_, i, item);
1041
        }
1042
1043
        continue;
err:
1044
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
1045
1046
            gsize j;
            PyGIMarshalCleanupFunc cleanup_func =
1047
                sequence_cache->item_cache->from_py_cleanup;
1048
1049
1050
1051
1052
1053
1054

            for(j = 0; j < i; j++) {
                cleanup_func (state,
                              sequence_cache->item_cache,
                              g_array_index (array_, gpointer, j),
                              TRUE);
            }
1055
1056
        }

1057
        if (is_ptr_array)
1058
            g_ptr_array_free ( ( GPtrArray *)array_, TRUE);
1059
1060
        else
            g_array_free (array_, TRUE);
1061
1062
1063
1064
1065
1066
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

array_success:
    if (sequence_cache->len_arg_index >= 0) {
1067
1068
        /* we have an child arg to handle */
        PyGIArgCache *child_cache =
1069
            callable_cache->args_cache[sequence_cache->len_arg_index];
1070

1071
        if (child_cache->direction == PYGI_DIRECTION_BIDIRECTIONAL) {
1072
            gint *len_arg = (gint *)state->in_args[child_cache->c_arg_index].v_pointer;
1073
            /* if we are not setup yet just set the in arg */
David Malcolm's avatar
David Malcolm committed
1074
1075
1076
1077
1078
1079
1080
            if (len_arg == NULL) {
                if (!gi_argument_from_py_ssize_t (&state->in_args[child_cache->c_arg_index],
                                                  length,
                                                  child_cache->type_tag)) {
                    goto err;
                }
            } else {
1081
                *len_arg = length;
David Malcolm's avatar
David Malcolm committed
1082
            }
1083
        } else {
David Malcolm's avatar
David Malcolm committed
1084
1085
1086
1087
1088
            if (!gi_argument_from_py_ssize_t (&state->in_args[child_cache->c_arg_index],
                                              length,
                                              child_cache->type_tag)) {
                goto err;
            }
1089
1090
1091
1092
1093
        }
    }

    if (sequence_cache->array_type == GI_ARRAY_TYPE_C) {
        arg->v_pointer = array_->data;
1094
        g_array_free (array_, FALSE);
1095
1096
1097
1098
1099
1100
1101
1102
    } else {
        arg->v_pointer = array_;
    }

    return TRUE;
}

gboolean
1103
1104
1105
1106
1107
_pygi_marshal_from_py_glist (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
1108
{
1109
    PyGIMarshalFromPyFunc from_py_marshaller;
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
    int i;
    Py_ssize_t length;
    GList *list_ = NULL;
    PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;


    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    if (!PySequence_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

1127
    length = PySequence_Length (py_arg);
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
    if (length < 0)
        return FALSE;

    if (sequence_cache->fixed_size >= 0 &&
        sequence_cache->fixed_size != length) {
        PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
                      sequence_cache->fixed_size, length);

        return FALSE;
    }

1139
    from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
1140
1141
1142
1143
1144
1145
    for (i = 0; i < length; i++) {
        GIArgument item;
        PyObject *py_item = PySequence_GetItem (py_arg, i);
        if (py_item == NULL)
            goto err;

1146
1147
1148
1149
1150
        if (!from_py_marshaller ( state,
                                  callable_cache,
                                  sequence_cache->item_cache,
                                  py_item,
                                 &item))
1151
1152
            goto err;

1153
        list_ = g_list_prepend (list_, _pygi_arg_to_hash_pointer (&item, sequence_cache->item_cache->type_tag));
1154
1155
        continue;
err:
John (J5) Palmieri's avatar
John (J5) Palmieri committed
1156
        /* FIXME: clean up list
1157
1158
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
            PyGIMarshalCleanupFunc cleanup = sequence_cache->item_cache->from_py_cleanup;
1159
        }
John (J5) Palmieri's avatar
John (J5) Palmieri committed
1160
        */
1161
        g_list_free (list_);
1162
1163
1164
1165
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

1166
    arg->v_pointer = g_list_reverse (list_);
1167
1168
1169
1170
    return TRUE;
}

gboolean
1171
1172
1173
1174
1175
_pygi_marshal_from_py_gslist (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              PyObject          *py_arg,
                              GIArgument        *arg)
1176
{
1177
    PyGIMarshalFromPyFunc from_py_marshaller;
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
    int i;
    Py_ssize_t length;
    GSList *list_ = NULL;
    PyGISequenceCache *sequence_cache = (PyGISequenceCache *)arg_cache;

    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

    if (!PySequence_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError, "Must be sequence, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

1194
    length = PySequence_Length (py_arg);
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
    if (length < 0)
        return FALSE;

    if (sequence_cache->fixed_size >= 0 &&
        sequence_cache->fixed_size != length) {
        PyErr_Format (PyExc_ValueError, "Must contain %zd items, not %zd",
                      sequence_cache->fixed_size, length);

        return FALSE;
    }

1206
    from_py_marshaller = sequence_cache->item_cache->from_py_marshaller;
1207
1208
1209
1210
1211
1212
    for (i = 0; i < length; i++) {
        GIArgument item;
        PyObject *py_item = PySequence_GetItem (py_arg, i);
        if (py_item == NULL)
            goto err;

1213
        if (!from_py_marshaller ( state,
1214
1215
1216
1217
                             callable_cache,
                             sequence_cache->item_cache,
                             py_item,
                            &item))
1218
1219
            goto err;

1220
        list_ = g_slist_prepend (list_, _pygi_arg_to_hash_pointer (&item, sequence_cache->item_cache->type_tag));
1221
1222
        continue;
err:
John (J5) Palmieri's avatar
John (J5) Palmieri committed
1223
        /* FIXME: Clean up list
1224
1225
        if (sequence_cache->item_cache->from_py_cleanup != NULL) {
            PyGIMarshalCleanupFunc cleanup = sequence_cache->item_cache->from_py_cleanup;
1226
        }
John (J5) Palmieri's avatar
John (J5) Palmieri committed
1227
        */
1228

1229
        g_slist_free (list_);
1230
1231
1232
1233
        _PyGI_ERROR_PREFIX ("Item %i: ", i);
        return FALSE;
    }

1234
    arg->v_pointer = g_slist_reverse (list_);
1235
1236
1237
1238
    return TRUE;
}

gboolean
1239
1240
1241
1242
1243
_pygi_marshal_from_py_ghash (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             PyObject          *py_arg,
                             GIArgument        *arg)
1244
{
1245
1246
    PyGIMarshalFromPyFunc key_from_py_marshaller;
    PyGIMarshalFromPyFunc value_from_py_marshaller;
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262

    int i;
    Py_ssize_t length;
    PyObject *py_keys, *py_values;

    GHashFunc hash_func;
    GEqualFunc equal_func;

    GHashTable *hash_ = NULL;
    PyGIHashCache *hash_cache = (PyGIHashCache *)arg_cache;

    if (py_arg == Py_None) {
        arg->v_pointer = NULL;
        return TRUE;
    }

1263
    py_keys = PyMapping_Keys (py_arg);
1264
1265
1266
1267
1268
1269
    if (py_keys == NULL) {
        PyErr_Format (PyExc_TypeError, "Must be mapping, not %s",
                      py_arg->ob_type->tp_name);
        return FALSE;
    }

1270
    length = PyMapping_Length (py_arg);
1271
    if (length < 0) {
1272
        Py_DECREF (py_keys);
1273
1274
1275
        return FALSE;
    }

1276
    py_values = PyMapping_Values (py_arg);
1277
    if (py_values == NULL) {
1278
        Py_DECREF (py_keys);
1279
1280
1281
        return FALSE;
    }

1282
1283
    key_from_py_marshaller = hash_cache->key_cache->from_py_marshaller;
    value_from_py_marshaller = hash_cache->value_cache->from_py_marshaller;
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297

    switch (hash_cache->key_cache->type_tag) {
        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
            hash_func = g_str_hash;
            equal_func = g_str_equal;
            break;
        default:
            hash_func = NULL;
            equal_func = NULL;
    }

    hash_ = g_hash_table_new (hash_func, equal_func);
    if (hash_ == NULL) {
1298
1299
1300
        PyErr_NoMemory ();
        Py_DECREF (py_keys);
        Py_DECREF (py_values);
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
        return FALSE;
    }

    for (i = 0; i < length; i++) {
        GIArgument key, value;
        PyObject *py_key = PyList_GET_ITEM (py_keys, i);
        PyObject *py_value = PyList_GET_ITEM (py_values, i);
        if (py_key == NULL || py_value == NULL)
            goto err;

1311
1312
1313
1314
1315
        if (!key_from_py_marshaller ( state,
                                      callable_cache,
                                      hash_cache->key_cache,
                                      py_key,
                                     &key))
1316
1317
            goto err;

1318
1319
1320
1321
1322
        if (!value_from_py_marshaller ( state,
                                        callable_cache,
                                        hash_cache->value_cache,
                                        py_value,
                                       &value))
1323
1324
            goto err;

<