All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
pyEnum.h
Go to the documentation of this file.
1 //
2 // Copyright 2016 Pixar
3 //
4 // Licensed under the Apache License, Version 2.0 (the "Apache License")
5 // with the following modification; you may not use this file except in
6 // compliance with the Apache License and the following modification to it:
7 // Section 6. Trademarks. is deleted and replaced with:
8 //
9 // 6. Trademarks. This License does not grant permission to use the trade
10 // names, trademarks, service marks, or product names of the Licensor
11 // and its affiliates, except as required to comply with Section 4(c) of
12 // the License and to reproduce the content of the NOTICE file.
13 //
14 // You may obtain a copy of the Apache License at
15 //
16 // http://www.apache.org/licenses/LICENSE-2.0
17 //
18 // Unless required by applicable law or agreed to in writing, software
19 // distributed under the Apache License with the above modification is
20 // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
21 // KIND, either express or implied. See the Apache License for the specific
22 // language governing permissions and limitations under the Apache License.
23 //
24 #ifndef PXR_BASE_TF_PY_ENUM_H
25 #define PXR_BASE_TF_PY_ENUM_H
26 
29 
30 #include "pxr/pxr.h"
31 
32 #include "pxr/base/tf/api.h"
33 #include "pxr/base/tf/pyObjWrapper.h"
34 #include "pxr/base/tf/pyUtils.h"
35 #include "pxr/base/tf/type.h"
36 
37 #include "pxr/base/arch/demangle.h"
38 #include "pxr/base/tf/enum.h"
39 #include "pxr/base/tf/hash.h"
40 #include "pxr/base/tf/hashmap.h"
41 #include "pxr/base/tf/iterator.h"
42 #include "pxr/base/tf/singleton.h"
43 #include "pxr/base/tf/stringUtils.h"
44 
45 #include <boost/python/class.hpp>
46 #include <boost/python/converter/from_python.hpp>
47 #include <boost/python/converter/registered.hpp>
48 #include <boost/python/converter/rvalue_from_python_data.hpp>
49 #include <boost/python/list.hpp>
50 #include <boost/python/object.hpp>
51 #include <boost/python/operators.hpp>
52 #include <boost/python/refcount.hpp>
53 #include <boost/python/scope.hpp>
54 #include <boost/python/to_python_converter.hpp>
55 #include <boost/python/tuple.hpp>
56 
57 #include <string>
58 
59 PXR_NAMESPACE_OPEN_SCOPE
60 
64 class Tf_PyEnum { };
65 
70 class Tf_PyEnumRegistry {
71 
72  public:
73  typedef Tf_PyEnumRegistry This;
74 
75  private:
76  Tf_PyEnumRegistry();
77  virtual ~Tf_PyEnumRegistry();
78  friend class TfSingleton<This>;
79 
80  public:
81 
82  TF_API static This &GetInstance() {
84  }
85 
86  TF_API
87  void RegisterValue(TfEnum const &e, boost::python::object const &obj);
88 
89  template <typename T>
90  void RegisterEnumConversions() {
91  // Register conversions to and from python.
92  boost::python::to_python_converter<T, _EnumToPython<T> >();
93  _EnumFromPython<T>();
94  }
95 
96  private:
97 
98  template <typename T>
99  struct _EnumFromPython {
100  _EnumFromPython() {
101  boost::python::converter::registry::insert
102  (&convertible, &construct, boost::python::type_id<T>());
103  }
104  static void *convertible(PyObject *obj) {
105  TfHashMap<PyObject *, TfEnum, _ObjectHash> const &o2e =
106  Tf_PyEnumRegistry::GetInstance()._objectsToEnums;
107  TfHashMap<PyObject *, TfEnum, _ObjectHash>::const_iterator
108  i = o2e.find(obj);
109  // In the case of producing a TfEnum or an integer, any
110  // registered enum type is fine. In all other cases, the
111  // enum types must match.
112  if (boost::is_same<T, TfEnum>::value ||
113  (boost::is_integral<T>::value && !boost::is_enum<T>::value))
114  return i != o2e.end() ? obj : 0;
115  else
116  return (i != o2e.end() && i->second.IsA<T>()) ? obj : 0;
117  }
118  static void construct(PyObject *src, boost::python::converter::
119  rvalue_from_python_stage1_data *data) {
120  void *storage =
121  ((boost::python::converter::
122  rvalue_from_python_storage<T> *)data)->storage.bytes;
123  new (storage) T(_GetEnumValue(src, (T *)0));
124  data->convertible = storage;
125  }
126  private:
127  // Overloads to explicitly allow conversion of the TfEnum integer
128  // value to other enum/integral types.
129  template <typename U>
130  static U _GetEnumValue(PyObject *src, U *) {
131  return U(Tf_PyEnumRegistry::GetInstance()._objectsToEnums[src].
132  GetValueAsInt());
133  }
134  static TfEnum _GetEnumValue(PyObject *src, TfEnum *) {
135  return Tf_PyEnumRegistry::GetInstance()._objectsToEnums[src];
136  }
137  };
138 
139  template <typename T>
140  struct _EnumToPython {
141  static PyObject *convert(T const &t);
142  };
143 
144  // Since our enum objects live as long as the registry does, we can use the
145  // pointer values for a hash.
146  struct _ObjectHash {
147  size_t operator()(PyObject *o) const {
148  return reinterpret_cast<size_t>(o);
149  }
150  };
151 
152  TfHashMap<TfEnum, PyObject *, TfHash> _enumsToObjects;
153  TfHashMap<PyObject *, TfEnum, _ObjectHash> _objectsToEnums;
154 
155 };
156 
157 TF_API_TEMPLATE_CLASS(TfSingleton<Tf_PyEnumRegistry>);
158 
159 // Private function used for __repr__ of wrapped enum types.
160 TF_API
161 std::string Tf_PyEnumRepr(boost::python::object const &self);
162 
163 // Private base class for types which are instantiated and exposed to python
164 // for each registered enum type.
165 struct Tf_PyEnumWrapper
166  : public Tf_PyEnum, boost::totally_ordered<Tf_PyEnumWrapper>
167 {
168  typedef Tf_PyEnumWrapper This;
169 
170  Tf_PyEnumWrapper(std::string const &n, TfEnum const &val) :
171  name(n), value(val) {}
172  long GetValue() const {
173  return value.GetValueAsInt();
174  }
175  std::string GetName() const{
176  return name;
177  }
178  std::string GetDisplayName() const {
179  return TfEnum::GetDisplayName(value);
180  }
181  std::string GetFullName() const {
182  return TfEnum::GetFullName(value);
183  }
184  friend bool operator ==(Tf_PyEnumWrapper const &self,
185  long other) {
186  return self.value.GetValueAsInt() == other;
187  }
188 
189  friend bool operator ==(Tf_PyEnumWrapper const &lhs,
190  Tf_PyEnumWrapper const &rhs) {
191  return lhs.value == rhs.value;
192  }
193 
194  friend bool operator <(Tf_PyEnumWrapper const &lhs,
195  Tf_PyEnumWrapper const &rhs)
196  {
197  // If same, not less.
198  if (lhs == rhs)
199  return false;
200  // If types don't match, string compare names.
201  if (!lhs.value.IsA(rhs.value.GetType()))
202  return TfEnum::GetFullName(lhs.value) <
203  TfEnum::GetFullName(rhs.value);
204  // If types do match, numerically compare values.
205  return lhs.GetValue() < rhs.GetValue();
206  }
207 
208  //
209  // XXX Bitwise operators for Enums are a temporary measure to support the
210  // use of Enums as Bitmasks in libSd. It should be noted that Enums are
211  // NOT closed under these operators. The proper place for such operators
212  // is in a yet-nonexistent Bitmask type.
213  //
214 
215  friend TfEnum operator |(Tf_PyEnumWrapper const &lhs,
216  Tf_PyEnumWrapper const &rhs) {
217  if (lhs.value.IsA(rhs.value.GetType())) {
218  return TfEnum(lhs.value.GetType(),
219  lhs.value.GetValueAsInt() |
220  rhs.value.GetValueAsInt());
221  }
222  TfPyThrowTypeError("Enum type mismatch");
223  return TfEnum();
224  }
225  friend TfEnum operator |(Tf_PyEnumWrapper const &lhs, long rhs) {
226  return TfEnum(lhs.value.GetType(), lhs.value.GetValueAsInt() | rhs);
227  }
228  friend TfEnum operator |(long lhs, Tf_PyEnumWrapper const &rhs) {
229  return TfEnum(rhs.value.GetType(), lhs | rhs.value.GetValueAsInt());
230  }
231 
232  friend TfEnum operator &(Tf_PyEnumWrapper const &lhs,
233  Tf_PyEnumWrapper const &rhs) {
234  if (lhs.value.IsA(rhs.value.GetType())) {
235  return TfEnum(lhs.value.GetType(),
236  lhs.value.GetValueAsInt() &
237  rhs.value.GetValueAsInt());
238  }
239  TfPyThrowTypeError("Enum type mismatch");
240  return TfEnum();
241  }
242  friend TfEnum operator &(Tf_PyEnumWrapper const &lhs, long rhs) {
243  return TfEnum(lhs.value.GetType(), lhs.value.GetValueAsInt() & rhs);
244  }
245  friend TfEnum operator &(long lhs, Tf_PyEnumWrapper const &rhs) {
246  return TfEnum(rhs.value.GetType(), lhs & rhs.value.GetValueAsInt());
247  }
248 
249  friend TfEnum operator ^(Tf_PyEnumWrapper const &lhs,
250  Tf_PyEnumWrapper const &rhs) {
251  if (lhs.value.IsA(rhs.value.GetType())) {
252  return TfEnum(lhs.value.GetType(),
253  lhs.value.GetValueAsInt() ^
254  rhs.value.GetValueAsInt());
255  }
256  TfPyThrowTypeError("Enum type mismatch");
257  return TfEnum();
258  }
259  friend TfEnum operator ^(Tf_PyEnumWrapper const &lhs, long rhs) {
260  return TfEnum(lhs.value.GetType(), lhs.value.GetValueAsInt() ^ rhs);
261  }
262  friend TfEnum operator ^(long lhs, Tf_PyEnumWrapper const &rhs) {
263  return TfEnum(rhs.value.GetType(), lhs ^ rhs.value.GetValueAsInt());
264  }
265 
266  friend TfEnum operator ~(Tf_PyEnumWrapper const &rhs) {
267  return TfEnum(rhs.value.GetType(), ~rhs.value.GetValueAsInt());
268  }
269  std::string name;
270  TfEnum value;
271 };
272 
273 template <typename T>
274 PyObject *
275 Tf_PyEnumRegistry::_EnumToPython<T>::convert(T const &t)
276 {
277  TfEnum e(t);
278 
279  // If there is no registered enum object, create a new one of
280  // the appropriate type.
281  if (!Tf_PyEnumRegistry::GetInstance()._enumsToObjects.count(e)) {
282  std::string name = ArchGetDemangled(e.GetType());
283  name = TfStringReplace(name, " ", "_");
284  name = TfStringReplace(name, "::", "_");
285  name = TfStringReplace(name, "<", "_");
286  name = TfStringReplace(name, ">", "_");
287  name = "AutoGenerated_" + name + "_" +
288  TfStringify(e.GetValueAsInt());
289 
290  boost::python::object wrappedVal =
291  boost::python::object(Tf_PyEnumWrapper(name, e));
292 
293  wrappedVal.attr("_baseName") = std::string();
294 
295  Tf_PyEnumRegistry::GetInstance().RegisterValue(e, wrappedVal);
296  }
297 
298  return boost::python::
299  incref(Tf_PyEnumRegistry::GetInstance()._enumsToObjects[e]);
300 }
301 
302 // Private template class which is instantiated and exposed to python for each
303 // registered enum type.
304 template <typename T>
305 struct Tf_TypedPyEnumWrapper : Tf_PyEnumWrapper
306 {
307  Tf_TypedPyEnumWrapper(std::string const &n, TfEnum const &val) :
308  Tf_PyEnumWrapper(n, val) {}
309 };
310 
311 // Removes the MFB package prefix from name if it starts with it, and replaces
312 // spaces with underscores.
313 TF_API
314 std::string Tf_PyCleanEnumName(std::string name);
315 
316 // Adds attribute of given name with given value to given scope.
317 // Issues a coding error if attribute by that name already existed.
318 TF_API
319 void Tf_PyEnumAddAttribute(boost::python::scope &s,
320  const std::string &name,
321  const boost::python::object &value);
322 
364 
365 // Detect scoped enums by using that the C++ standard does not allow them to
366 // be converted to int implicitly.
367 template <typename T, bool IsScopedEnum = !std::is_convertible<T, int>::value>
368 struct TfPyWrapEnum {
369 
370 private:
371  typedef boost::python::class_<
372  Tf_TypedPyEnumWrapper<T>, boost::python::bases<Tf_PyEnumWrapper> >
373  _EnumPyClassType;
374 
375 public:
376 
381  explicit TfPyWrapEnum( std::string const &name = std::string())
382  {
383  using namespace boost::python;
384 
385  const bool explicitName = !name.empty();
386 
387  // First, take either the given name, or the demangled type name.
388  std::string enumName = explicitName ? name :
389  TfStringReplace(ArchGetDemangled(typeid(T)), "::", ".");
390 
391  // If the name is dotted, take everything before the dot as the base
392  // name. This is used in repr.
393  std::string baseName = TfStringGetBeforeSuffix(enumName);
394  if (baseName == enumName)
395  baseName = std::string();
396 
397  // If the name is dotted, take the last element as the enum name.
398  if (!TfStringGetSuffix(enumName).empty())
399  enumName = TfStringGetSuffix(enumName);
400 
401  // If the name was not explicitly given, then clean it up by removing
402  // the mfb package name prefix if it exists.
403  if (!explicitName) {
404  if (!baseName.empty())
405  baseName = Tf_PyCleanEnumName(baseName);
406  else
407  enumName = Tf_PyCleanEnumName(enumName);
408  }
409 
410  if (IsScopedEnum) {
411  // Make the enumName appear in python representation
412  // for scoped enums.
413  if (!baseName.empty()) {
414  baseName += ".";
415  }
416  baseName += enumName;
417  }
418 
419  // Make a python type for T.
420  _EnumPyClassType enumClass(enumName.c_str(), no_init);
421  enumClass.setattr("_baseName", baseName);
422 
423  // Register conversions for it.
424  Tf_PyEnumRegistry::GetInstance().RegisterEnumConversions<T>();
425 
426  // Export values. Only clean names if basename is empty (i.e. the enum
427  // is top-level).
428  _ExportValues(baseName.empty(), enumClass);
429 
430  // Register with Tf so that python clients of a TfType
431  // that represents an enum are able to get to the equivalent
432  // python class with .pythonclass
433  const TfType &type = TfType::Find<T>();
434  if (!type.IsUnknown())
435  type.DefinePythonClass(enumClass);
436  }
437 
438  private:
439 
443  void _ExportValues(bool cleanNames, _EnumPyClassType &enumClass) {
444  boost::python::list valueList;
445 
446  std::vector<std::string> names = TfEnum::GetAllNames<T>();
447  TF_FOR_ALL(name, names) {
448  bool success = false;
449  TfEnum enumValue = TfEnum::GetValueFromName<T>(*name, &success);
450  if (!success) {
451  continue;
452  }
453 
454  std::string cleanedName = cleanNames ?
455  Tf_PyCleanEnumName(*name) : *name;
456 
457  // convert value to python.
458  Tf_TypedPyEnumWrapper<T> wrappedValue(cleanedName, enumValue);
459  boost::python::object pyValue(wrappedValue);
460 
461  // register it as the python object for this value.
462  Tf_PyEnumRegistry::GetInstance().RegisterValue(enumValue, pyValue);
463 
464  // Take all the values and export them into the current scope.
465  std::string valueName = wrappedValue.GetName();
466  if (IsScopedEnum) {
467  // If scoped enum, enum values appear on the enumClass ...
468  boost::python::scope s(enumClass);
469  Tf_PyEnumAddAttribute(s, valueName, pyValue);
470  } else {
471  // ... otherwise, enum values appear on the enclosing scope.
472  boost::python::scope s;
473  Tf_PyEnumAddAttribute(s, valueName, pyValue);
474  }
475 
476  valueList.append(pyValue);
477  }
478 
479  // Add a tuple of all the values to the enum class.
480  enumClass.setattr("allValues", boost::python::tuple(valueList));
481  }
482 
483 };
484 
485 PXR_NAMESPACE_CLOSE_SCOPE
486 
487 #endif // PXR_BASE_TF_PY_ENUM_H
Manage a single instance of an object (see.
Definition: singleton.h:122
GfVec3d operator^(GfVec3d const &v1, GfVec3d const &v2)
Returns the cross product of v1 and v2.
Definition: vec3d.h:457
TF_API std::string TfStringGetSuffix(const std::string &name, char delimiter= '.')
Returns the suffix of a string.
ARCH_API std::string ArchGetDemangled(const std::string &typeName)
Return demangled RTTI-generated type name.
An enum class that records both enum type and enum value.
Definition: enum.h:140
static TF_API std::string GetDisplayName(TfEnum val)
Returns the display name for an enumerated value.
#define TF_FOR_ALL(iter, c)
Macro for iterating over a container.
Definition: iterator.h:390
TF_API void TfPyThrowTypeError(std::string const &msg)
Raises a python TypeError and throws a C++ exception.
static T & GetInstance()
Return a reference to an object of type T, creating it if necessary.
Definition: singleton.h:137
static TF_API std::string GetFullName(TfEnum val)
Returns the fully-qualified name for an enumerated value.
TfPyWrapEnum(std::string const &name=std::string())
Construct an enum wrapper object.
Definition: pyEnum.h:381
TfType represents a dynamic runtime type.
Definition: type.h:64
VT_API bool operator==(VtDictionary const &, VtDictionary const &)
Equality comparison.
TF_API std::string TfStringGetBeforeSuffix(const std::string &name, char delimiter= '.')
Returns everything up to the suffix of a string.
std::enable_if<!std::is_enum< T >::value, std::string >::type TfStringify(const T &v)
Convert an arbitrary type into a string.
Definition: stringUtils.h:523
Used to wrap enum types for script.
Definition: pyEnum.h:368
TF_API std::string TfStringReplace(const std::string &source, const std::string &from, const std::string &to)
Replaces all occurrences of string from with to in source.