vtkPythonUtil.cxx 42.4 KB
Newer Older
Ken Martin's avatar
Ken Martin committed
1
2
3
4
5
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPythonUtil.cxx

6
  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
7
8
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
Ken Martin's avatar
Ken Martin committed
9

10
11
     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
12
     PURPOSE.  See the above copyright notice for more information.
Ken Martin's avatar
Ken Martin committed
13
14

=========================================================================*/
15

16
#include "vtkPythonUtil.h"
Ken Martin's avatar
Ken Martin committed
17

18
19
#include "vtkSystemIncludes.h"

Ken Martin's avatar
Ken Martin committed
20
#include "vtkObject.h"
21
#include "vtkSmartPointerBase.h"
22
#include "vtkWindows.h"
23

24
#include <vtksys/ios/sstream>
25
26
#include <vtkstd/map>
#include <vtkstd/string>
27
#include <vtkstd/utility>
28

29
30
31
32
33
34
35
36
// Silent warning like
// "dereferencing type-punned pointer will break strict-aliasing rules"
// it happens because this kind of expression: (long *)&ptr
// pragma GCC diagnostic is available since gcc>=4.2
#if defined(__GNUG__) && (__GNUC__>4) || (__GNUC__==4 && __GNUC_MINOR__>=2)
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif

37
38
39
40
41
#if defined ( _MSC_VER )
#  define vtkConvertPtrToLong(x) ((long)(PtrToUlong(x)))
#else
#  define vtkConvertPtrToLong(x) ((long)(x))
#endif
Ken Martin's avatar
Ken Martin committed
42

43
44
//--------------------------------------------------------------------
// There are three maps associated with the Python wrappers
45

46
47
48
49
class vtkPythonObjectMap
  : public vtkstd::map<vtkSmartPointerBase, PyObject*>
{
};
50

51
52
53
54
class vtkPythonClassMap
  : public vtkstd::map<vtkstd::string, PyObject*>
{
};
55

56
57
58
59
class vtkPythonSpecialTypeMap
  : public vtkstd::map<vtkstd::string, PyVTKSpecialType>
{
};
60

61
62
//--------------------------------------------------------------------
// The singleton for vtkPythonUtil
63

64
vtkPythonUtil *vtkPythonMap = NULL;
65

66
67
68
69
70
// destructs the singleton when python exits
void vtkPythonUtilDelete()
{
  delete vtkPythonMap;
  vtkPythonMap = NULL;
71
72
73
}

//--------------------------------------------------------------------
74
vtkPythonUtil::vtkPythonUtil()
75
{
76
77
78
  this->ObjectMap = new vtkPythonObjectMap;
  this->ClassMap = new vtkPythonClassMap;
  this->SpecialTypeMap = new vtkPythonSpecialTypeMap;
79
80
81
}

//--------------------------------------------------------------------
82
vtkPythonUtil::~vtkPythonUtil()
83
{
84
85
86
  delete this->ObjectMap;
  delete this->ClassMap;
  delete this->SpecialTypeMap;
87
88
89
}

//--------------------------------------------------------------------
90
91
92
93
// Concatenate an array of strings into a single string.  The resulting
// string is allocated via new.  The array of strings must be null-terminated,
// e.g. static char *strings[] = {"string1", "string2", NULL};
PyObject *vtkPythonUtil::BuildDocString(char *docstring[])
94
{
95
96
97
98
99
  PyObject *result;
  char *data;
  int i, j, n;
  int *m;
  int total = 0;
100

101
  for (n = 0; docstring[n] != NULL; n++)
102
    {
103
    ;
David Gobbi's avatar
David Gobbi committed
104
    }
105

106
  m = new int[n];
107

108
  for (i = 0; i < n; i++)
109
    {
110
111
    m[i] = static_cast<int>(strlen(docstring[i]));
    total += m[i];
112
113
    }

114
  result = PyString_FromStringAndSize(docstring[0], m[0]);
115

116
  if (n > 1)
117
    {
118
    _PyString_Resize(&result, total);
119
120
    }

121
  data = PyString_AsString(result);
122

123
124
  j = m[0];
  for (i = 1; i < n; i++)
125
    {
126
127
    strcpy(&data[j], docstring[i]);
    j += m[i];
128
129
    }

130
  delete [] m;
131

132
  return result;
133
134
}

135
//--------------------------------------------------------------------
136
// Enums for vtkPythonUtil::CheckArg, the values between VTK_PYTHON_GOOD_MATCH
137
138
139
// and VTK_PYTHON_NEEDS_CONVERSION are reserved for checking how
// many generations a vtkObject arg is from the requested arg type.

140
enum vtkPythonArgPenalties
141
142
143
144
145
146
147
{
  VTK_PYTHON_EXACT_MATCH = 0,
  VTK_PYTHON_GOOD_MATCH = 1,
  VTK_PYTHON_NEEDS_CONVERSION = 65534,
  VTK_PYTHON_INCOMPATIBLE = 65535
};

148
//--------------------------------------------------------------------
149
150
// A helper struct for CallOverloadedMethod
class vtkPythonOverloadHelper
151
152
{
public:
153
  vtkPythonOverloadHelper() : m_format(0), m_classname(0), m_penalty(0) {};
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
  void initialize(bool selfIsClass, const char *format);
  bool next(const char **format, const char **classname);
  int penalty() { return m_penalty; };
  int penalty(int penalty) {
    if (penalty > m_penalty) { m_penalty = penalty; };
    return m_penalty; };

private:
  const char *m_format;
  const char *m_classname;
  int m_penalty;
  PyCFunction m_meth;
};

// Construct the object with a penalty of VTK_PYTHON_EXACT_MATCH
169
void vtkPythonOverloadHelper::initialize(bool selfIsClass, const char *format)
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
{
  // remove the first arg check if "self" is not a PyVTKClass
  if (format[0] == '@' && !selfIsClass)
    {
    format++;
    }

  m_format = format;
  m_classname = format;
  while (*m_classname != '\0' && *m_classname != ' ')
    {
    m_classname++;
    }
  if (*m_classname == ' ')
    {
    m_classname++;
    }

  this->m_penalty = VTK_PYTHON_EXACT_MATCH;
}

// Get the next format char and, if char is 'O', the classname.
// The classname is terminated with space, not with null
193
bool vtkPythonOverloadHelper::next(const char **format, const char **classname)
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
{
  if (*m_format == '\0' || *m_format == ' ')
    {
    return false;
    }

  *format = m_format;

  if (*m_format == 'O')
    {
    *classname = m_classname;

    while (*m_classname != '\0' && *m_classname != ' ')
      {
      m_classname++;
      }
    if (*m_classname == ' ')
      {
      m_classname++;
      }
    }

  m_format++;
  if (!isalpha(*m_format) && *m_format != '(' && *m_format != ')' &&
      *m_format != '\0' && *m_format != ' ')
    {
    m_format++;
    }

  return true;
}

226
227
228
229
//--------------------------------------------------------------------
// If tmpi > VTK_INT_MAX, then penalize unless format == 'l'

#ifdef PY_LONG_LONG
230
int vtkPythonIntPenalty(PY_LONG_LONG tmpi, int penalty, char format)
231
#else
232
int vtkPythonIntPenalty(long tmpi, int penalty, char format)
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
#endif
{
#if VTK_SIZEOF_LONG != VTK_SIZEOF_INT
  if (tmpi > VTK_INT_MAX || tmpi < VTK_INT_MIN)
    {
    if (format != 'l')
      {
      if (penalty < VTK_PYTHON_GOOD_MATCH)
        {
        penalty = VTK_PYTHON_GOOD_MATCH;
        if (format != 'i')
          {
          penalty++;
          }
        }
      else
        {
        penalty++;
        }
      }
    }
  else
    {
    if (format != 'i')
      {
      if (penalty < VTK_PYTHON_GOOD_MATCH)
        {
        penalty = VTK_PYTHON_GOOD_MATCH;
        }
      else
        {
        penalty++;
        }
      }
    }
#endif
  return penalty;
}

272
273
274
//--------------------------------------------------------------------
// This must check the same format chars that are used by
// vtkWrapPython_FormatString() in vtkWrapPython.c
275
276
277
//
// The "level" parameter limits possible recursion of this method,
// it is incremented every time recursion occurs.
278

279
280
int vtkPythonUtil::CheckArg(
  PyObject *arg, const char *format, const char *classname, int level)
281
{
282
  int penalty = VTK_PYTHON_EXACT_MATCH;
283
284
285
286
287
288
289

  switch (*format)
    {
    case 'b':
    case 'h':
    case 'l':
    case 'i':
290
291
292
      if (PyBool_Check(arg))
        {
        penalty = VTK_PYTHON_GOOD_MATCH;
293
294
295
296
297
298
299
300
301
302
303
304
305
        if (*format != 'i')
          {
          penalty++;
          }
        }
      else if (PyInt_Check(arg))
        {
#if VTK_SIZEOF_LONG == VTK_SIZEOF_INT
        if (*format != 'i')
          {
          penalty = VTK_PYTHON_GOOD_MATCH;
          }
#else
306
        penalty = vtkPythonIntPenalty(PyInt_AsLong(arg), penalty, *format);
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#endif
        }
      else if (PyLong_Check(arg))
        {
        penalty = VTK_PYTHON_GOOD_MATCH;
#if VTK_SIZEOF_LONG == VTK_SIZEOF_INT
        if (*format != 'i')
          {
          penalty++;
          }
#else
# ifdef PY_LONG_LONG
        PY_LONG_LONG tmpi = PyLong_AsLongLong(arg);
# else
        long tmpi = PyLong_AsLong(arg);
# endif
        if (PyErr_Occurred())
          {
          PyErr_Clear();
          tmpi = VTK_LONG_MAX;
          }

329
        penalty = vtkPythonIntPenalty(tmpi, penalty, *format);
330
#endif
331
        }
332
      else // not PyInt or PyLong
333
        {
334
335
336
337
338
339
340
341
342
343
344
        if (level == 0)
          {
          penalty = VTK_PYTHON_NEEDS_CONVERSION;
          long tmpi = PyInt_AsLong(arg);
          if (tmpi == -1 || PyErr_Occurred())
            {
            PyErr_Clear();
            penalty = VTK_PYTHON_INCOMPATIBLE;
            }
          }
        else
345
          {
346
          penalty = VTK_PYTHON_INCOMPATIBLE;
347
348
349
350
351
352
353
354
          }
        }
      break;

#ifdef PY_LONG_LONG
    case 'L':
      if (!PyLong_Check(arg))
        {
355
        penalty = VTK_PYTHON_GOOD_MATCH;
356
357
        if (!PyInt_Check(arg))
          {
358
359
360
361
362
363
364
365
366
367
368
          if (level == 0)
            {
            penalty = VTK_PYTHON_NEEDS_CONVERSION;
            PyLong_AsLongLong(arg);
            if (PyErr_Occurred())
              {
              PyErr_Clear();
              penalty = VTK_PYTHON_INCOMPATIBLE;
              }
            }
          else
369
            {
370
            penalty = VTK_PYTHON_INCOMPATIBLE;
371
372
373
374
375
376
377
            }
          }
        }
      break;
#endif

    case 'f':
378
      penalty = VTK_PYTHON_GOOD_MATCH;
379
380
381
    case 'd':
      if (!PyFloat_Check(arg))
        {
382
        penalty = VTK_PYTHON_NEEDS_CONVERSION;
383
384
385
386
387
388
389
390
391
392
        if (level == 0)
          {
          PyFloat_AsDouble(arg);
          if (PyErr_Occurred())
            {
            PyErr_Clear();
            penalty = VTK_PYTHON_INCOMPATIBLE;
            }
          }
        else
393
          {
394
          penalty = VTK_PYTHON_INCOMPATIBLE;
395
396
397
398
399
          }
        }
      break;

    case 'c':
400
401
      // penalize chars, they must be converted from strings
      penalty = VTK_PYTHON_NEEDS_CONVERSION;
402
403
      if (!PyString_Check(arg) || PyString_Size(arg) != 1)
        {
404
        penalty = VTK_PYTHON_INCOMPATIBLE;
405
406
407
408
409
410
411
        }
      break;

    case 's':
    case 'z':
      if (format[1] == '#') // memory buffer
        {
412
413
        penalty = VTK_PYTHON_GOOD_MATCH;
        if (arg == Py_None)
414
          {
415
416
417
418
419
          penalty = VTK_PYTHON_NEEDS_CONVERSION;
          if (format[0] == 's')
            {
            penalty = VTK_PYTHON_INCOMPATIBLE;
            }
420
          }
421
        // make sure that arg can act as a buffer
422
423
424
425
426
427
428
429
430
        else if (arg->ob_type->tp_as_buffer == 0)
          {
          penalty = VTK_PYTHON_INCOMPATIBLE;
          }
        }
      else if (arg == Py_None)
        {
        penalty = VTK_PYTHON_NEEDS_CONVERSION;
        if (format[0] == 's')
431
          {
432
          penalty = VTK_PYTHON_INCOMPATIBLE;
433
434
          }
        }
435
#ifdef Py_USING_UNICODE
436
437
438
439
      else if (PyUnicode_Check(arg))
        {
        penalty = VTK_PYTHON_NEEDS_CONVERSION;
        }
440
#endif
441
      else if (!PyString_Check(arg))
442
        {
443
        penalty = VTK_PYTHON_INCOMPATIBLE;
444
445
446
        }
      break;

447
448
449
450
    case '@':
      // '@' is a placeholder that always succeeds
      break;

451
    case 'O':
452
453
454
455
456
457
      {
      // classname is terminated by a space, not a null
      const char *cp = classname;
      char name[128];
      int i = 0;
      for (; i < 127 && cp[i] != ' ' && cp[i] != '\0'; i++)
458
        {
459
460
461
        name[i] = cp[i];
        }
      name[i] = '\0';
462
      classname = name;
463

464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
      // booleans
      if (name[0] == 'b' && strcmp(classname, "bool") == 0)
        {
#if PY_VERSION_HEX >= 0x02030000
        if (!PyBool_Check(arg))
#endif
          {
          penalty = VTK_PYTHON_NEEDS_CONVERSION;
          int tmpi = PyObject_IsTrue(arg);
          if (tmpi == -1 || PyErr_Occurred())
            {
            PyErr_Clear();
            penalty = VTK_PYTHON_INCOMPATIBLE;
            }
          }
        }

481
      // unicode string
482
#ifdef Py_USING_UNICODE
483
484
485
486
      else if (name[0] == 'u' && strcmp(classname, "unicode") == 0)
        {
        if (!PyUnicode_Check(arg))
          {
487
          penalty = VTK_PYTHON_INCOMPATIBLE;
488
489
490
491
          }
        }
#endif

492
      // callback functions
493
      else if (name[0] == 'f' && strcmp(classname, "func") == 0)
494
495
        {
        if (!PyCallable_Check(arg))
496
          {
497
          penalty = VTK_PYTHON_GOOD_MATCH;
498
499
          if (arg != Py_None)
            {
500
            penalty = VTK_PYTHON_INCOMPATIBLE;
501
502
503
            }
          }
        }
504
505
506

      // Assume any pointers are vtkObjectBase-derived types
      else if (classname[0] == '*' && strncmp(&classname[1], "vtk", 3) == 0)
507
        {
508
509
510
511
512
513
        classname++;

        if (arg == Py_None)
          {
          penalty = VTK_PYTHON_GOOD_MATCH;
          }
514
        else if (PyVTKObject_Check(arg))
515
516
517
518
519
520
521
522
523
524
525
526
527
528
          {
          PyVTKObject *vobj = (PyVTKObject *)arg;
          if (strncmp(vobj->vtk_ptr->GetClassName(), classname, 127) != 0)
            {
            // Trace back through superclasses to look for a match
            PyVTKClass *cls = vobj->vtk_class;
            if (PyTuple_Size(cls->vtk_bases) == 0)
              {
              penalty = VTK_PYTHON_INCOMPATIBLE;
              }
            else
              {
              penalty = VTK_PYTHON_GOOD_MATCH;
              cls = (PyVTKClass *)PyTuple_GetItem(cls->vtk_bases,0);
529
              while (strncmp(PyString_AS_STRING(cls->vtk_name),
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
                     classname, 127) != 0)
                {
                if (PyTuple_Size(cls->vtk_bases) > 0)
                  {
                  cls = (PyVTKClass *)PyTuple_GetItem(cls->vtk_bases,0);
                  }
                else
                  {
                  penalty = VTK_PYTHON_INCOMPATIBLE;
                  break;
                  }
                if (penalty+1 < VTK_PYTHON_NEEDS_CONVERSION)
                  {
                  penalty++;
                  }
                }
              }
            }
          }
        else
550
          {
551
          penalty = VTK_PYTHON_INCOMPATIBLE;
552
          }
553
        }
554
555
556
557

      // Any other object starting with "vtk" is a special object
      else if ((classname[0] == '&' && strncmp(&classname[1], "vtk", 3) == 0)
               || strncmp(classname, "vtk", 3) == 0)
558
        {
559
560
561
562
563
564
565
        // Skip over the "&" that indicates a reference
        if (classname[0] == '&')
          {
          classname++;
          }

        // Check for an exact match
566
567
        if (!PyVTKSpecialObject_Check(arg) ||
            strncmp(PyString_AS_STRING(
568
569
                      ((PyVTKSpecialObject *)arg)->vtk_info->classname),
                    classname, 127) != 0)
570
          {
571
572
573
          // If it didn't match, then maybe conversion is possible
          penalty = VTK_PYTHON_NEEDS_CONVERSION;

574
575
          // Look up the required type in the map
          vtkPythonSpecialTypeMap::iterator i;
576
577

          if (level != 0 ||
578
579
              (i = vtkPythonMap->SpecialTypeMap->find(classname)) ==
              vtkPythonMap->SpecialTypeMap->end())
580
581
582
583
            {
            penalty = VTK_PYTHON_INCOMPATIBLE;
            }
          else
584
            {
585
            // Get info about the required type
586
            PyVTKSpecialType *info = &i->second;
587
588

            // Try out all the constructor methods
589
            if (!vtkPythonUtil::FindConversionMethod(info->constructors, arg))
590
              {
591
              penalty = VTK_PYTHON_INCOMPATIBLE;
592
              }
593
594
595
            }
          }
        }
596
597

      // An object of unrecognized type
598
599
      else
        {
600
        penalty = VTK_PYTHON_INCOMPATIBLE;
601
        }
602
      }
603
604
605
606
607
      break;

    default:
      vtkGenericWarningMacro("Unrecognized python format character "
                             << format[0]);
608
      penalty = VTK_PYTHON_INCOMPATIBLE;
609
610
611
612
613
614
    }

  return penalty;
}

//--------------------------------------------------------------------
615
616
617
// Call the overloaded method that is the best match for the arguments.
// The first arg is name of the class that the methods belong to, it
// is there for potential diagnostic usage but is currently unused.
618

619
PyObject *vtkPythonUtil::CallOverloadedMethod(
620
  PyMethodDef *methods, PyObject *self, PyObject *args)
621
622
{
  PyMethodDef *meth = &methods[0];
623
  int matchCount = 1;
624
625
626
627

  // Make sure there is more than one method
  if (methods[1].ml_meth != 0)
    {
628
629
630
    vtkPythonOverloadHelper helperStorage[16];
    vtkPythonOverloadHelper *helperArray = helperStorage;
    vtkPythonOverloadHelper *helper;
631
632
633

    const char *format;
    const char *classname;
634
635
    bool selfIsClass = 0;
    int sig;
636

637
638
    // Is self a PyVTKClass object, rather than a PyVTKObject?  If so,
    // then first arg is an object, and other args should follow format.
639
    if (self && PyVTKClass_Check(self))
640
641
642
      {
      selfIsClass = true;
      }
643
644
645
646
647
648
649

    for (sig = 0; methods[sig].ml_meth != 0; sig++)
      {
      // Have we overgrown the stack storage?
      if ((sig & 15) == 0 && sig != 0)
        {
        // Grab more space from the heap
650
651
        vtkPythonOverloadHelper *tmp = helperArray;
        helperArray = new vtkPythonOverloadHelper[sig+16];
652
653
654
655
656
657
658
659
660
661
662
        for (int k = 0; k < sig; k++)
          {
          helperArray[k] = tmp[k];
          }
        if (tmp != helperStorage)
          {
          delete [] tmp;
          }
        }

      // Initialize the helper for ths signature
663
      helperArray[sig].initialize(selfIsClass, methods[sig].ml_doc);
664
665
666
667
668
669
670
671
672
673
674
675
      }

    // Get the number of signatures
    int nsig = sig;

    // Go through the tuple and check each arg against each format, knocking
    // out mismatched functions as we go along.  For matches, prioritize:
    // 0) exact type matches first
    // 1) trivial conversions second, e.g. double to float
    // 2) other conversions third, e.g. double to int

    // Loop through args
676
677
    Py_ssize_t n = PyTuple_Size(args);
    for (Py_ssize_t i = 0; i < n; i++)
678
679
680
681
682
683
684
      {
      PyObject *arg = PyTuple_GetItem(args, i);

      for (sig = 0; sig < nsig; sig++)
        {
        helper = &helperArray[sig];

685
        if (helper->penalty() != VTK_PYTHON_INCOMPATIBLE &&
686
            helper->next(&format, &classname))
687
688
689
          {
          if (*format != '(')
            {
690
            helper->penalty(vtkPythonUtil::CheckArg(arg, format, classname));
691
692
693
694
695
            }
          else
            {
            if (!PySequence_Check(arg))
              {
696
              helper->penalty(VTK_PYTHON_INCOMPATIBLE);
697
698
699
              }
            else
              {
700
701
702
703
704
705
              // Note: we don't reject the method if the sequence count
              // doesn't match.  If that circumstance occurs, we want the
              // method to be called with an incorrect count so that a
              // useful error will be reported to the user.  Also, we want
              // to mimic C++ semantics, and C++ doesn't care about the
              // size of arrays when it resolves overloads.
706
707
              Py_ssize_t m = PySequence_Size(arg);
              for (Py_ssize_t j = 0;; j++)
708
                {
709
                if (!helper->next(&format, &classname))
710
                  {
711
                  helper->penalty(VTK_PYTHON_INCOMPATIBLE);
712
713
                  break;
                  }
714
                if (*format == ')')
715
716
717
718
                  {
                  break;
                  }

719
720
721
                if (j < m)
                  {
                  PyObject *sarg = PySequence_GetItem(arg, j);
722
                  helper->penalty(vtkPythonUtil::CheckArg(sarg, format, classname));
723
                  Py_DECREF(sarg);
724
                  }
725
726
727
728
729
730
                }
              }
            }
          }
        else
          {
731
          helper->penalty(VTK_PYTHON_INCOMPATIBLE);
732
733
734
735
736
          }
        }
      }

    // Loop through methods and identify the best match
737
    int minPenalty = VTK_PYTHON_INCOMPATIBLE;
738
    meth = 0;
739
    matchCount = 0;
740
741
    for (sig = 0; sig < nsig; sig++)
      {
742
      // the "helper->next" check ensures that there are no leftover args
743
      helper = &helperArray[sig];
744
      int penalty = helper->penalty();
745
      if (penalty <= minPenalty && penalty < VTK_PYTHON_INCOMPATIBLE &&
746
747
          !helper->next(&format, &classname))
        {
748
749
750
751
752
753
754
        if (penalty < minPenalty)
          {
          matchCount = 0;
          minPenalty = penalty;
          meth = &methods[sig];
          }
        matchCount++;
755
756
757
758
759
760
761
762
763
764
        }
      }

    // Free any heap space that we have used
    if (helperArray != helperStorage)
      {
      delete [] helperArray;
      }
    }

765
766
767
768
769
770
771
772
  if (meth && matchCount > 1)
    {
    PyErr_SetString(PyExc_TypeError,
      "ambiguous call, multiple overloaded methods match the arguments");

    return NULL;
    }

773
774
775
776
777
778
779
780
781
782
783
  if (meth)
    {
    return meth->ml_meth(self, args);
    }

  PyErr_SetString(PyExc_TypeError,
    "arguments do not match any overloaded methods");

  return NULL;
}

784
785
786
787
//--------------------------------------------------------------------
// Look through the a batch of constructor methods to see if any of
// them take the provided argument.

788
PyMethodDef *vtkPythonUtil::FindConversionMethod(
789
790
  PyMethodDef *methods, PyObject *arg)
{
791
  vtkPythonOverloadHelper helper;
792
793
794
  const char *format, *classname, *dummy1, *dummy2;
  int minPenalty = VTK_PYTHON_NEEDS_CONVERSION;
  PyMethodDef *method = 0;
795
  int matchCount = 0;
796
797
798
799
800
801
802
803
804
805

  for (PyMethodDef *meth = methods; meth->ml_meth != NULL; meth++)
    {
    // If meth only takes one arg
    helper.initialize(0, meth->ml_doc);
    if (helper.next(&format, &classname) &&
        !helper.next(&dummy1, &dummy2))
      {
      // If the constructor accepts the arg without
      // additional conversion, then we found a match
806
      int penalty = vtkPythonUtil::CheckArg(arg, format, classname, 1);
807
808
809

      if (penalty < minPenalty)
        {
810
        matchCount = 1;
811
812
813
        minPenalty = penalty;
        method = meth;
        }
814
815
816
817
      else if (meth && penalty == minPenalty)
        {
        matchCount++;
        }
818
819
820
      }
    }

821
822
  // if matchCount > 1, there was ambiguity

823
824
825
  return method;
}

826
//--------------------------------------------------------------------
827
828
vtkObjectBase *vtkPythonUtil::VTKParseTuple(
  PyObject *pself, PyObject *args, char *format, ...)
829
{
830
  PyVTKObject *self = (PyVTKObject *)pself;
831
  vtkObjectBase *obj = NULL;
832
833
834
835
  va_list va;
  va_start(va, format);

  /* check if this was called as an unbound method */
836
  if (PyVTKClass_Check(pself))
837
    {
David Gobbi's avatar
David Gobbi committed
838
839
840
    int n = PyTuple_Size(args);
    PyVTKClass *vtkclass = (PyVTKClass *)self;

841
    if (n == 0 || (self = (PyVTKObject *)PyTuple_GetItem(args, 0)) == NULL ||
842
843
        !PyVTKObject_Check(pself) ||
        !self->vtk_ptr->IsA(PyString_AS_STRING(vtkclass->vtk_name)))
David Gobbi's avatar
David Gobbi committed
844
845
846
      {
      char buf[256];
      sprintf(buf,"unbound method requires a %s as the first argument",
847
              PyString_AS_STRING(vtkclass->vtk_name));
David Gobbi's avatar
David Gobbi committed
848
849
850
851
852
853
854
      PyErr_SetString(PyExc_ValueError,buf);
      return NULL;
      }
    // re-slice the args to remove 'self'
    args = PyTuple_GetSlice(args,1,n);
    if (PyArg_VaParse(args,format,va))
      {
855
      obj = self->vtk_ptr;
David Gobbi's avatar
David Gobbi committed
856
857
      }
    Py_DECREF(args);
858
859
860
861
    }
  /* it was called as a bound method */
  else
    {
David Gobbi's avatar
David Gobbi committed
862
863
    if (PyArg_VaParse(args,format,va))
      {
864
      obj = self->vtk_ptr;
David Gobbi's avatar
David Gobbi committed
865
      }
866
    }
867
868
869
  return obj;
}

870
//--------------------------------------------------------------------
871
PyVTKSpecialType *vtkPythonUtil::AddSpecialTypeToMap(
872
873
874
  char *classname, char *docstring[], PyMethodDef *methods,
  PyMethodDef *constructors, PyVTKSpecialCopyFunc copy_func,
  PyVTKSpecialDeleteFunc delete_func, PyVTKSpecialPrintFunc print_func)
875
{
876
  if (vtkPythonMap == NULL)
877
    {
878
879
    vtkPythonMap = new vtkPythonUtil();
    Py_AtExit(vtkPythonUtilDelete);
880
881
882
    }

#ifdef VTKPYTHONDEBUG
883
  //  vtkGenericWarningMacro("Adding an type " << type << " to map ptr");
884
885
886
#endif

  // lets make sure it isn't already there
887
888
889
  vtkPythonSpecialTypeMap::iterator i =
    vtkPythonMap->SpecialTypeMap->find(classname);
  if(i != vtkPythonMap->SpecialTypeMap->end())
890
891
    {
#ifdef VTKPYTHONDEBUG
892
    vtkGenericWarningMacro("Attempt to add type to the map when already there!!!");
893
#endif
894
    return 0;
895
896
    }

897
898
  i = vtkPythonMap->SpecialTypeMap->insert(i,
    vtkPythonSpecialTypeMap::value_type(
899
      classname,
900
      PyVTKSpecialType(classname, docstring, methods, constructors,
901
                           copy_func, delete_func, print_func)));
902
903

#ifdef VTKPYTHONDEBUG
904
  //  vtkGenericWarningMacro("Added type to map type = " << typeObject);
905
#endif
906
907

  return &i->second;
908
909
}

910
//--------------------------------------------------------------------
911
PyVTKSpecialType *vtkPythonUtil::FindSpecialType(const char *classname)
Ken Martin's avatar
Ken Martin committed
912
{
913
  if (vtkPythonMap)
Ken Martin's avatar
Ken Martin committed
914
    {
915
916
    vtkPythonSpecialTypeMap::iterator it =
      vtkPythonMap->SpecialTypeMap->find(classname);
Ken Martin's avatar
Ken Martin committed
917

918
919
920
921
    if (it != vtkPythonMap->SpecialTypeMap->end())
      {
      return &it->second;
      }
Ken Martin's avatar
Ken Martin committed
922
923
    }

924
  return NULL;
925
}
926

927
//--------------------------------------------------------------------
928
void vtkPythonUtil::AddObjectToMap(PyObject *obj, vtkObjectBase *ptr)
929
{
930
  if (vtkPythonMap == NULL)
Ken Martin's avatar
Ken Martin committed
931
    {
932
933
    vtkPythonMap = new vtkPythonUtil();
    Py_AtExit(vtkPythonUtilDelete);
Ken Martin's avatar
Ken Martin committed
934
935
936
    }

#ifdef VTKPYTHONDEBUG
937
  vtkGenericWarningMacro("Adding an object to map ptr = " << ptr);
938
#endif
939

940
  ((PyVTKObject *)obj)->vtk_ptr = ptr;
941
  (*vtkPythonMap->ObjectMap)[ptr] = obj;
Ken Martin's avatar
Ken Martin committed
942
943

#ifdef VTKPYTHONDEBUG
944
  vtkGenericWarningMacro("Added object to map obj= " << obj << " "
945
                         << ptr);
946
947
#endif
}
Ken Martin's avatar
Ken Martin committed
948

949
//--------------------------------------------------------------------
950
void vtkPythonUtil::RemoveObjectFromMap(PyObject *obj)
Ken Martin's avatar
Ken Martin committed
951
{
952
  vtkObjectBase *ptr = ((PyVTKObject *)obj)->vtk_ptr;
953

Ken Martin's avatar
Ken Martin committed
954
#ifdef VTKPYTHONDEBUG
955
  vtkGenericWarningMacro("Deleting an object from map obj = " << obj << " "
956
                         << obj->vtk_ptr);
957
#endif
958

959
  if (vtkPythonMap)
Berk Geveci's avatar
Berk Geveci committed
960
    {
961
    vtkPythonMap->ObjectMap->erase(ptr);
Berk Geveci's avatar
Berk Geveci committed
962
    }
Ken Martin's avatar
Ken Martin committed
963
964
}

965
//--------------------------------------------------------------------
966
PyObject *vtkPythonUtil::GetObjectFromPointer(vtkObjectBase *ptr)
Ken Martin's avatar
Ken Martin committed
967
{
968
  PyObject *obj = NULL;
969

Ken Martin's avatar
Ken Martin committed
970
971
#ifdef VTKPYTHONDEBUG
  vtkGenericWarningMacro("Checking into pointer " << ptr);
972
#endif
973

974
975
  if (ptr)
    {
976
    vtkstd::map<vtkSmartPointerBase, PyObject*>::iterator i =
977
978
      vtkPythonMap->ObjectMap->find(ptr);
    if(i != vtkPythonMap->ObjectMap->end())
979
980
981
      {
      obj = i->second;
      }
982
    if (obj)
David Gobbi's avatar
David Gobbi committed
983
      {
984
      Py_INCREF(obj);
David Gobbi's avatar
David Gobbi committed
985
      }
986
987
    }
  else
988
    {
989
    Py_INCREF(Py_None);
David Gobbi's avatar
David Gobbi committed
990
    obj = Py_None;
991
    }
Ken Martin's avatar
Ken Martin committed
992
993
#ifdef VTKPYTHONDEBUG
  vtkGenericWarningMacro("Checking into pointer " << ptr << " obj = " << obj);
994
#endif
995

996
  if (obj == NULL)
997
    {
998
    PyObject *vtkclass = NULL;
999
    vtkstd::map<vtkstd::string, PyObject*>::iterator i =
1000
1001
      vtkPythonMap->ClassMap->find(ptr->GetClassName());
    if(i != vtkPythonMap->ClassMap->end())
1002
1003
1004
      {
      vtkclass = i->second;
      }
1005

1006
      // if the class was not in the map, then find the nearest base class
Jon Davis's avatar
Jon Davis committed
1007
      // that is and associate ptr->GetClassName() with that base class
David Gobbi's avatar
David Gobbi committed
1008
1009
    if (vtkclass == NULL)
      {
1010
1011
      vtkclass = vtkPythonUtil::FindNearestBaseClass(ptr);
      vtkPythonUtil::AddClassToMap(vtkclass, ptr->GetClassName());
David Gobbi's avatar
David Gobbi committed
1012
1013
      }

1014
    obj = PyVTKObject_New(vtkclass, ptr);
1015
    }
David Gobbi's avatar
David Gobbi committed
1016

Ken Martin's avatar
Ken Martin committed
1017
1018
1019
  return obj;
}

1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//--------------------------------------------------------------------
void vtkPythonUtil::AddClassToMap(PyObject *vtkclass, const char *classname)
{
  if (vtkPythonMap == NULL)
    {
    vtkPythonMap = new vtkPythonUtil();
    Py_AtExit(vtkPythonUtilDelete);
    }

#ifdef VTKPYTHONDEBUG
  //  vtkGenericWarningMacro("Adding an type " << type << " to map ptr");
#endif

  // lets make sure it isn't already there
  vtkPythonClassMap::iterator i =
    vtkPythonMap->ClassMap->find(classname);
  if(i != vtkPythonMap->ClassMap->end())
    {
#ifdef VTKPYTHONDEBUG
    vtkGenericWarningMacro("Attempt to add type to the map when already there!!!");
#endif
    return;
    }

  (*vtkPythonMap->ClassMap)[classname] = vtkclass;

#ifdef VTKPYTHONDEBUG
  //  vtkGenericWarningMacro("Added type to map type = " << typeObject);
#endif
}

//--------------------------------------------------------------------
PyObject *vtkPythonUtil::FindClass(const char *classname)
{
  if (vtkPythonMap)
    {
    vtkPythonClassMap::iterator it =
      vtkPythonMap->ClassMap->find(classname);
    if (it != vtkPythonMap->ClassMap->end())
      {
      return it->second;
      }
    }

  return NULL;
}

//--------------------------------------------------------------------
1068
1069
// this is a helper function to find the nearest base class for an
// object whose class is not in the ClassDict
1070
PyObject *vtkPythonUtil::FindNearestBaseClass(vtkObjectBase *ptr)
1071
1072
1073
{
  PyObject *nearestbase = NULL;
  int maxdepth = 0;
1074
  int depth;
1075

1076
1077
1078
  for(vtkPythonClassMap::iterator classes =
        vtkPythonMap->ClassMap->begin();
      classes != vtkPythonMap->ClassMap->end(); ++classes)
1079
    {
1080
    PyObject *pyclass = classes->second;
1081

1082
    if (ptr->IsA(PyString_AS_STRING(((PyVTKClass *)pyclass)->vtk_name)))
1083
      {
David Gobbi's avatar
David Gobbi committed
1084
1085
1086
1087
1088
1089
1090
1091
      PyObject *cls = pyclass;
      PyObject *bases = ((PyVTKClass *)pyclass)->vtk_bases;
      // count the heirarchy depth for this class
      for (depth = 0; PyTuple_Size(bases) != 0; depth++)
        {
        cls = PyTuple_GetItem(bases,0);
        bases = ((PyVTKClass *)cls)->vtk_bases;
        }
1092
      // we want the class that is furthest from vtkObjectBase
David Gobbi's avatar
David Gobbi committed
1093
1094
1095
1096
      if (depth > maxdepth)
        {
        maxdepth = depth;
        nearestbase = pyclass;
1097
        }
David Gobbi's avatar
David Gobbi committed
1098
      }
1099
    }
1100

1101
1102
1103
  return nearestbase;
}

1104
//--------------------------------------------------------------------
1105
1106
vtkObjectBase *vtkPythonUtil::GetPointerFromObject(
  PyObject *obj, const char *result_type)
1107
{
1108
  vtkObjectBase *ptr;
1109

1110
1111
1112
  // convert Py_None to NULL every time
  if (obj == Py_None)
    {
Jon Davis's avatar
Jon Davis committed
1113
      return NULL;
1114
1115
1116
    }

  // check to ensure it is a vtk object
1117
  if (!PyVTKObject_Check(obj))
Ken Martin's avatar
Ken Martin committed
1118
    {
Andy Cedilnik's avatar
Andy Cedilnik committed
1119