Apply changes when click on the element

You want to make an interactive “tool”. That won’t work purely with preselection, because after running the plugin from the toolbar button, it won’t have access to what you select afterwards.

(You could of course just require the user to select the components in the correct order, or make two toolbar buttons, first step, second step, and make sure the user has executed the first step, then selected the target component before executing the second step.)

To make an interactive tool, you need to write a Tool class (any class that implements those methods from Sketchup::Tool that you need), and then you tell SketchUp to select this tool:

command = UI::Command.new("MyTool"){
  begin
    Sketchup.active_model.select_tool( MyTool.new )
  rescue Exception => e
    puts e.message
    puts e.backtrace
  end
}

For the tool class, take a look at the line tool example from Extension Warehouse.
You need only a basic select tool with three states. On mouse click, you pick the group/component below the cursor using a pickhelper. If it is a correct entity, you save it in an instance variable and proceed into the next state. In the last state, you process the selected components (like summing up the lengths and applying them to the third component).

class MyTool

  def activate(view)
    @pickhelper = view.pick_helper
    reset()
  end

  def reset
    @component1 = nil
    @component2 = nil
    @component3 = nil
    @state = 0
  end

  def onLButtonDown(flags, x, y, view)
    @pickhelper.do_pick(x, y)
    if @pickhelper.picked_element.is_a?(Sketchup::ComponentInstance)
      case @state
        when 0
          @component1 = @pickhelper.picked_element
          @state = 1
        when 1
          @component2 = @pickhelper.picked_element
          @state = 2
        when 2
          @component3 = @pickhelper.picked_element
          process(@component1, @component2, @component3)
          @state = 0
      end
    end
  end

  def process(component1, component2, target_component)
    # ...
  end
end
2 Likes