What is the best way for a plugin to detect whether the 2D viewport is currently open?

Godot Version

4.3.stable.official

Context

Currently I use the following check to see whether the 2D Editor viewport is being used:

@tool
extends EditorPlugin

var select_2D_viewport_button : Button

func _enter_tree() -> void:
  select_2D_viewport_button = (
      EditorInterface.get_base_control()
             .find_child("2D", true, false) 
            # (recursive=true, owned=false)
  )

func _input(_event) -> void:
  if select_2D_viewport_button.button_pressed: # (and 3 more conditions)
      # use the 2d viewport local mouse cursor position to do stuff

Edit: similar solution found here: Registering clicks in the 3D viewport

Question

  1. Iā€™m worried that the way to locate the button is not forward compatible.
  2. Can use a _gui input method here in stead of _process?

What would be the, erm, canonical way to do this properly?

Sidenote

I found the button by just dumping the GUI using this method:

func _enter_tree() -> void:
     _dump_interface(EditorInterface.get_base_control(), 4)

func _dump_interface(n : Node, max_d : int = 2, d : int = 0) -> void:
	if n.name.contains("Dialog") or n.name.contains("Popup"):
		return
	print(n.name.lpad(d + n.name.length(), "-") + " (%d)" % [n.get_child_count()])
	for c in n.get_children():
		if d < max_d:
			_dump_interface(c, max_d, d + 1)

Which outputs:

@Panel@13 (55)
-@VBoxContainer@14 (2)
--@EditorTitleBar@15 (7)
---@MenuBar@99 (5)
----Scene (2)
----Project (2)
----Debug (0)
----Editor (2)
----Help (0)
---@HBoxContainer@4025 (0)
---@HBoxContainer@4026 (4)
----2D (0)
----3D (0)
----Script (0)
----AssetLib (0)

since you have a plugin why not use the main_screen_changed signal

Whenever the 2D main screen is selected it will callback 2D

1 Like

Thanks!
I was hoping I was missing the obvious.