Skip to content

Instantly share code, notes, and snippets.

@jimfoltz
Created November 1, 2015 12:04
Show Gist options
  • Select an option

  • Save jimfoltz/c433abb743ad0dd7fd47 to your computer and use it in GitHub Desktop.

Select an option

Save jimfoltz/c433abb743ad0dd7fd47 to your computer and use it in GitHub Desktop.

Revisions

  1. jimfoltz revised this gist Nov 1, 2015. No changes.
  2. jimfoltz created this gist Nov 1, 2015.
    93 changes: 93 additions & 0 deletions parentize-dc.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,93 @@
    # Replaces references to a parent Coponent in a DC
    # with the "Parent!" reference.

    module JF

    module Parentize

    private

    DICT = "dynamic_attributes".freeze

    def self.group?(ent)
    ent.class == Sketchup::Group
    end
    def self.instance?(ent)
    ent.class == Sketchup::ComponentInstance
    end

    def self.dc_name(ent)
    name = nil
    if instance?(ent)
    name = ent.definition.attribute_dictionary(DICT)["_name"]
    elsif group?(ent)
    name = ent.attribute_dictionary(DICT)["_name"]
    end
    name
    end

    def self.replace(parent, ent)
    dict = ent.attribute_dictionary(DICT)
    dcname = dc_name(ent)
    re = Regexp.new("\\b#{dc_name(parent)}\\!\\b")
    dict.each {|k, v|
    next if v.nil?
    if k[/^_.*formula$/]
    orig = "- [#{dcname} < #{dc_name(parent)}] : #{k} = #{v.inspect}"
    ret = v.gsub!(re, 'Parent!')
    repl = "+ [#{dcname} < #{dc_name(parent)}] : #{k} = #{v.inspect}"
    if ret
    #puts orig, repl, "\n"
    dict[k] = v
    end
    end
    }
    end

    def self.main(ent)
    model = Sketchup.active_model
    model.start_operation("Parentize", true)
    work(ent)
    #$dc_observers.get_latest_class.redraw_with_undo(ent)
    rescue => exc
    p exc
    model.abort_operation
    raise
    else
    model.commit_operation
    end

    def self.work(ent, parent = nil, list = {})
    if instance?(ent)
    dict = nil
    if parent and ent.definition.attribute_dictionary(DICT)
    replace(parent, ent.definition)
    replace(parent, ent)
    end
    ent.definition.entities.each do |e|
    work(e, ent, list)
    end
    elsif group?(ent)
    if parent and ent.attribute_dictionary(DICT)
    replace(parent, ent)
    end
    ent.entities.each do |e|
    work(e, ent, list)
    end
    end
    end

    UI.add_context_menu_handler do |menu|
    model = Sketchup.active_model
    sel = model.selection
    ent = sel[0]
    if sel.size == 1 and ent.class == Sketchup::ComponentInstance
    if ent.definition.attribute_dictionary("dynamic_attributes")
    menu.add_item("Parentize") { main(ent) }
    end
    end
    end

    end # Parentize

    end # JF