Tool Observer method onToolStateChanged invoke twice

I am using a simple observer for tools. Code below.

I noticed that when I move object method invoked 3 times.
1 time when I grab the object
2 times when I leave an object.

Unfortunately, the 2 times when I leave the object I have tool_state == 0 so I have no idea how I can recognize that 'one time

My task is to run a function of everything when the user ‘leaves’ the grabbed object. Would be nice to avoid static/classes/global variables to do this. Any thoughts?

At first, I thought that I added observer twice, but the grabbing object invoke only once (tool_state == 1)


class MyToolsObserver < Sketchup::ToolsObserver

  def onActiveToolChanged(tools, tool_name, tool_id)
    puts "onActiveToolChanged: #{tool_name}"
  end

  def onToolStateChanged(tools, tool_name, tool_id, tool_state)
    puts "onToolStateChanged: #{tool_id} - #{tool_name}:#{tool_state}"
 end

end

I think I found a way by using the previous state tool:
Used a object variable
Maybe somebody will search that in future

Here is updated code:

class MyToolsObserver < Sketchup::ToolsObserver

  attr_accessor :last_state

  def onActiveToolChanged(tools, tool_name, tool_id)
    puts "onActiveToolChanged: #{tool_name}"
  end

  def onToolStateChanged(tools, tool_name, tool_id, tool_state)
    puts "onToolStateChanged: #{tool_id} - #{tool_name}:#{tool_state}"

    if tool_id == 21048 && tool_state == 0 && @last_state == 1
      logic_code()
      puts "INVOKE MOVE TOOL"
    end

    @last_state = tool_state
 end

end

Needing to keep track of state is quite common with the SketchUp API.

It is actually an instance variable.

Please read the open issue in the API Issue tracker:

Also read about the v2016 Observer overhaul:

1 Like

thanks for all the extra info!

Please read the open issue in the API Issue tracker:

oh yea, new methods for observers would be nice!

So, how do I detect when a user has triggered a tool? I have a similar problem. I need to detect whether a user has triggered a move or zoom function. I have read the previous content. Can I refresh the queue status immediately by ending the previous function? Please help me.:(

Your only option is to use the onActiveToolChanged callback and test for the tool IDs when they equal that for the Move tool (21048) and the Zoom tool (10509).

I do not know what a “queue status” is. This is not documented for the API.

What do you mean by “ending the previous function” ?