[Code] Group.real_parent
-
Problem:
Group.entities.parent
doesn't always return the correct definition.How to reproduce:
- Make a group
- Copy the group a couple of times. (Entity Info will display the number of copies)
Each of these copies all refer to the same definition via.entities.parent
- Open one of the groups - you don't even have to edit it. It's now unique. However, it's
.entities.parent
isn't correct.
If you save the model and reload it, the references will be corrected. But until the user do so, you get the wrong parent via the API.
[mod=Warning:r69r1avx]Don't use this example as-is. Modifying base classes is not good practice.[/mod:r69r1avx]
Workaround:
class Sketchup;;Group # Some times the group.entities.parent refer to the wrong definition. This method checks # for this error and locates the correct parent definition. def real_parent if self.entities.parent.instances.include?(self) return self.entities.parent else Sketchup.active_model.definitions.each { |definition| return definition if definition.instances.include?(self) } end return nil # Should not happen. end end
Usage:
group_entity.real_parent
I haven't dared to make it build a cache of mis-referenced group definitions. I'm afraid it might cause problems if I keep hold of entity references. (What I suspect is causing problems for my DoubleCut plugin.) So for the time being it will have to search the definitions each time it comes across a mis-reference. Optimise your code to call the method as few times as possible.
-
Standalone version - doesn't extent the base class and also returns the definition for Group, ComponentInstance and Image entities:
# Returns the definition for a +Group+, +ComponentInstance+ or +Image+ # # @param [Sketchup;;ComponentInstance, Sketchup;;Group, Sketchup;;Image] instance # # @return [Sketchup;;ComponentDefinition] # @since 2.0.0 def self.definition(instance) if instance.is_a?(Sketchup;;ComponentInstance) # ComponentInstance return instance.definition elsif instance.is_a?(Sketchup;;Group) # Group # # (i) group.entities.parent should return the definition of a group. # But because of a SketchUp bug we must verify that group.entities.parent returns # the correct definition. If the returned definition doesn't include our group instance # then we must search through all the definitions to locate it. if instance.entities.parent.instances.include?(instance) return instance.entities.parent else Sketchup.active_model.definitions.each { |definition| return definition if definition.instances.include?(instance) } end elsif instance.is_a?(Sketchup;;Image) Sketchup.active_model.definitions.each { |definition| return definition if definition.image? && definition.instances.include?(instance) } end return nil # Error. We should never exit here. end
Advertisement