diff --git a/backends/events/sdl/sdl-events.cpp b/backends/events/sdl/sdl-events.cpp index 3cd124e6dfa7..469cf356bc6b 100644 --- a/backends/events/sdl/sdl-events.cpp +++ b/backends/events/sdl/sdl-events.cpp @@ -32,9 +32,13 @@ #include "engines/engine.h" #include "gui/gui-manager.h" -#if defined(USE_IMGUI) && SDL_VERSION_ATLEAST(2, 0, 0) +#if defined(USE_IMGUI) +#if SDL_VERSION_ATLEAST(3, 0, 0) +#include "backends/imgui/backends/imgui_impl_sdl3.h" +#elif SDL_VERSION_ATLEAST(2, 0, 0) #include "backends/imgui/backends/imgui_impl_sdl2.h" #endif +#endif #if SDL_VERSION_ATLEAST(2, 0, 0) #define GAMECONTROLLERDB_FILE "gamecontrollerdb.txt" @@ -46,13 +50,133 @@ static uint32 convUTF8ToUTF32(const char *src) { Common::U32String u32(src); return u32[0]; } +#endif + +#if SDL_VERSION_ATLEAST(3, 0, 0) +static bool gameControllerAddMappingsFromFile(const char *file) { + return SDL_AddGamepadMappingsFromFile(file); +} +#elif SDL_VERSION_ATLEAST(2, 0, 0) +static bool gameControllerAddMappingsFromFile(const char *file) { + return SDL_GameControllerAddMappingsFromFile(file) >= 0; +} +#endif + +#if SDL_VERSION_ATLEAST(3, 0, 0) +static bool initSubSystem(SDL_InitFlags flags) { + return SDL_InitSubSystem(flags); +#else +static bool initSubSystem(Uint32 flags) { + return SDL_InitSubSystem(flags) >= 0; +#endif +} + +#if SDL_VERSION_ATLEAST(3, 0, 0) +static bool isGamepad(SDL_JoystickID instance_id) { + return SDL_IsGamepad(instance_id); +} +#elif SDL_VERSION_ATLEAST(2, 0, 0) +static bool isGamepad(SDL_JoystickID instance_id) { + return SDL_IsGameController(instance_id); +} +#endif + +static int numJoysticks() { +#if SDL_VERSION_ATLEAST(3, 0, 0) + int numJoysticks = 0; + SDL_GetJoysticks(&numJoysticks); + return numJoysticks; +#else + return SDL_NumJoysticks(); +#endif +} + +#if SDL_VERSION_ATLEAST(3, 0, 0) +static SDL_Joystick *openJoystick(SDL_JoystickID instance_id) { + return SDL_OpenJoystick(instance_id); +} +#else +static SDL_Joystick *openJoystick(int device_index) { + return SDL_JoystickOpen(device_index); +} +#endif + +static void closeJoystick(SDL_Joystick *joystick) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_CloseJoystick(joystick); +#else + SDL_JoystickClose(joystick); +#endif +} + + +#if SDL_VERSION_ATLEAST(3, 0, 0) +static SDL_Gamepad *openGamepad(SDL_JoystickID instance_id) { + return SDL_OpenGamepad(instance_id); +} +#elif SDL_VERSION_ATLEAST(2, 0, 0) +static SDL_GameController *openGamepad(int joystick_index) { + return SDL_GameControllerOpen(joystick_index); +} +#endif + +#if SDL_VERSION_ATLEAST(3, 0, 0) +static void closeGamepad(SDL_Gamepad *gamepad) { + SDL_CloseGamepad(gamepad); +} +#elif SDL_VERSION_ATLEAST(2, 0, 0) +static void closeGamepad(SDL_GameController *gamecontroller) { + SDL_GameControllerClose(gamecontroller); +} +#endif + +#if SDL_VERSION_ATLEAST(3, 0, 0) +static const char *getGamepadName(SDL_Gamepad *gamepad) { + return SDL_GetGamepadName(gamepad); +} +#elif SDL_VERSION_ATLEAST(2, 0, 0) +static const char *getGamepadName(SDL_GameController *gamecontroller) { + return SDL_GameControllerName(gamecontroller); +} +#endif + +#if SDL_VERSION_ATLEAST(3, 0, 0) +static const char *getJoystickName(SDL_Joystick *joystick) { + return SDL_GetJoystickName(joystick); +} +#elif SDL_VERSION_ATLEAST(2, 0, 0) +static const char *getJoystickName(SDL_Joystick *joystick) { + return SDL_JoystickName(joystick); +} +#endif + +#if SDL_VERSION_ATLEAST(3, 0, 0) +SDL_Joystick * getGamepadJoystick(SDL_Gamepad *gamepad) { + return SDL_GetGamepadJoystick(gamepad); +} +#elif SDL_VERSION_ATLEAST(2, 0, 0) +SDL_Joystick* getGamepadJoystick(SDL_GameController *gamecontroller) { + return SDL_GameControllerGetJoystick(gamecontroller); +} +#endif + +#if SDL_VERSION_ATLEAST(3, 0, 0) +SDL_JoystickID getJoystickID(SDL_Joystick *joystick) { + return SDL_GetJoystickID(joystick); +} +#elif SDL_VERSION_ATLEAST(2, 0, 0) +SDL_JoystickID getJoystickID(SDL_Joystick *joystick) { + return SDL_JoystickInstanceID(joystick); +} +#endif +#if SDL_VERSION_ATLEAST(2, 0, 0) void SdlEventSource::loadGameControllerMappingFile() { bool loaded = false; if (ConfMan.hasKey("controller_map_db")) { Common::FSNode file = Common::FSNode(ConfMan.getPath("controller_map_db")); if (file.exists()) { - if (SDL_GameControllerAddMappingsFromFile(file.getPath().toString(Common::Path::kNativeSeparator).c_str()) < 0) + if (!gameControllerAddMappingsFromFile(file.getPath().toString(Common::Path::kNativeSeparator).c_str())) error("File %s not valid: %s", file.getPath().toString(Common::Path::kNativeSeparator).c_str(), SDL_GetError()); else { loaded = true; @@ -65,7 +189,7 @@ void SdlEventSource::loadGameControllerMappingFile() { Common::FSNode dir = Common::FSNode(ConfMan.getPath("extrapath")); Common::FSNode file = dir.getChild(GAMECONTROLLERDB_FILE); if (file.exists()) { - if (SDL_GameControllerAddMappingsFromFile(file.getPath().toString(Common::Path::kNativeSeparator).c_str()) < 0) + if (!gameControllerAddMappingsFromFile(file.getPath().toString(Common::Path::kNativeSeparator).c_str())) error("File %s not valid: %s", file.getPath().toString(Common::Path::kNativeSeparator).c_str(), SDL_GetError()); else debug("Game controller DB file loaded: %s", file.getPath().toString(Common::Path::kNativeSeparator).c_str()); @@ -84,13 +208,17 @@ SdlEventSource::SdlEventSource() int joystick_num = ConfMan.getInt("joystick_num"); if (joystick_num >= 0) { // Initialize SDL joystick subsystem - if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) { + if (!initSubSystem(SDL_INIT_JOYSTICK)) { warning("Could not initialize SDL joystick: %s", SDL_GetError()); return; } #if SDL_VERSION_ATLEAST(2, 0, 0) - if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == -1) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (!initSubSystem(SDL_INIT_GAMEPAD)) { +#else + if (!initSubSystem(SDL_INIT_GAMECONTROLLER)) { +#endif warning("Could not initialize SDL game controller: %s", SDL_GetError()); return; } @@ -126,7 +254,11 @@ int SdlEventSource::mapKey(SDL_Keycode sdlKey, SDL_Keymod mod, Uint16 unicode) { // Umlauts and others will set KEYCODE_INVALID on SDL2, so in such a case always keep unicode. if (key != Common::KEYCODE_INVALID) { // keycode is valid, check further also depending on modifiers +#if SDL_VERSION_ATLEAST(3,0,0) + if (mod & (SDL_KMOD_CTRL | SDL_KMOD_ALT)) { +#else if (mod & (KMOD_CTRL | KMOD_ALT)) { +#endif // Ctrl and/or Alt is active // // We need to restrict unicode to only up to 0x7E, because on macOS the option/alt key will switch to @@ -160,7 +292,11 @@ int SdlEventSource::mapKey(SDL_Keycode sdlKey, SDL_Keymod mod, Uint16 unicode) { if (key >= Common::KEYCODE_F1 && key <= Common::KEYCODE_F9) { return key - Common::KEYCODE_F1 + Common::ASCII_F1; } else if (key >= Common::KEYCODE_KP0 && key <= Common::KEYCODE_KP9) { +#if SDL_VERSION_ATLEAST(3,0,0) + if ((mod & SDL_KMOD_NUM) == 0) +#else if ((mod & KMOD_NUM) == 0) +#endif return 0; // In case Num-Lock is NOT enabled, return 0 for ascii, so that directional keys on numpad work return key - Common::KEYCODE_KP0 + '0'; } else if (key >= Common::KEYCODE_UP && key <= Common::KEYCODE_PAGEDOWN) { @@ -168,7 +304,11 @@ int SdlEventSource::mapKey(SDL_Keycode sdlKey, SDL_Keymod mod, Uint16 unicode) { } else if (unicode) { // Return unicode in case it's still set and wasn't filtered. return unicode; +#if SDL_VERSION_ATLEAST(3,0,0) + } else if (key >= 'a' && key <= 'z' && (mod & SDL_KMOD_SHIFT)) { +#else } else if (key >= 'a' && key <= 'z' && (mod & KMOD_SHIFT)) { +#endif return key & ~0x20; } else if (key >= Common::KEYCODE_NUMLOCK && key < Common::KEYCODE_LAST) { return 0; @@ -197,12 +337,22 @@ void SdlEventSource::SDLModToOSystemKeyFlags(SDL_Keymod mod, Common::Event &even event.kbd.flags = 0; - if (mod & KMOD_SHIFT) +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (mod & SDL_KMOD_GUI) + event.kbd.flags |= Common::KBD_META; + if (mod & SDL_KMOD_SHIFT) event.kbd.flags |= Common::KBD_SHIFT; - if (mod & KMOD_ALT) + if (mod & SDL_KMOD_ALT) event.kbd.flags |= Common::KBD_ALT; - if (mod & KMOD_CTRL) + if (mod & SDL_KMOD_CTRL) event.kbd.flags |= Common::KBD_CTRL; + + // Sticky flags + if (mod & SDL_KMOD_NUM) + event.kbd.flags |= Common::KBD_NUM; + if (mod & SDL_KMOD_CAPS) + event.kbd.flags |= Common::KBD_CAPS; +#else #if SDL_VERSION_ATLEAST(2, 0, 0) if (mod & KMOD_GUI) event.kbd.flags |= Common::KBD_META; @@ -211,11 +361,20 @@ void SdlEventSource::SDLModToOSystemKeyFlags(SDL_Keymod mod, Common::Event &even event.kbd.flags |= Common::KBD_META; #endif + if (mod & KMOD_SHIFT) + event.kbd.flags |= Common::KBD_SHIFT; + if (mod & KMOD_ALT) + event.kbd.flags |= Common::KBD_ALT; + if (mod & KMOD_CTRL) + event.kbd.flags |= Common::KBD_CTRL; + // Sticky flags if (mod & KMOD_NUM) event.kbd.flags |= Common::KBD_NUM; if (mod & KMOD_CAPS) event.kbd.flags |= Common::KBD_CAPS; +#endif + } Common::KeyCode SdlEventSource::SDLToOSystemKeycode(const SDL_Keycode key) { @@ -228,11 +387,19 @@ Common::KeyCode SdlEventSource::SDLToOSystemKeycode(const SDL_Keycode key) { case SDLK_ESCAPE: return Common::KEYCODE_ESCAPE; case SDLK_SPACE: return Common::KEYCODE_SPACE; case SDLK_EXCLAIM: return Common::KEYCODE_EXCLAIM; +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDLK_DBLAPOSTROPHE: return Common::KEYCODE_QUOTEDBL; +#else case SDLK_QUOTEDBL: return Common::KEYCODE_QUOTEDBL; +#endif case SDLK_HASH: return Common::KEYCODE_HASH; case SDLK_DOLLAR: return Common::KEYCODE_DOLLAR; case SDLK_AMPERSAND: return Common::KEYCODE_AMPERSAND; +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDLK_APOSTROPHE: return Common::KEYCODE_QUOTE; +#else case SDLK_QUOTE: return Common::KEYCODE_QUOTE; +#endif case SDLK_LEFTPAREN: return Common::KEYCODE_LEFTPAREN; case SDLK_RIGHTPAREN: return Common::KEYCODE_RIGHTPAREN; case SDLK_ASTERISK: return Common::KEYCODE_ASTERISK; @@ -263,6 +430,35 @@ Common::KeyCode SdlEventSource::SDLToOSystemKeycode(const SDL_Keycode key) { case SDLK_RIGHTBRACKET: return Common::KEYCODE_RIGHTBRACKET; case SDLK_CARET: return Common::KEYCODE_CARET; case SDLK_UNDERSCORE: return Common::KEYCODE_UNDERSCORE; +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDLK_GRAVE: return Common::KEYCODE_BACKQUOTE; + case SDLK_A: return Common::KEYCODE_a; + case SDLK_B: return Common::KEYCODE_b; + case SDLK_C: return Common::KEYCODE_c; + case SDLK_D: return Common::KEYCODE_d; + case SDLK_E: return Common::KEYCODE_e; + case SDLK_F: return Common::KEYCODE_f; + case SDLK_G: return Common::KEYCODE_g; + case SDLK_H: return Common::KEYCODE_h; + case SDLK_I: return Common::KEYCODE_i; + case SDLK_J: return Common::KEYCODE_j; + case SDLK_K: return Common::KEYCODE_k; + case SDLK_L: return Common::KEYCODE_l; + case SDLK_M: return Common::KEYCODE_m; + case SDLK_N: return Common::KEYCODE_n; + case SDLK_O: return Common::KEYCODE_o; + case SDLK_P: return Common::KEYCODE_p; + case SDLK_Q: return Common::KEYCODE_q; + case SDLK_R: return Common::KEYCODE_r; + case SDLK_S: return Common::KEYCODE_s; + case SDLK_T: return Common::KEYCODE_t; + case SDLK_U: return Common::KEYCODE_u; + case SDLK_V: return Common::KEYCODE_v; + case SDLK_W: return Common::KEYCODE_w; + case SDLK_X: return Common::KEYCODE_x; + case SDLK_Y: return Common::KEYCODE_y; + case SDLK_Z: return Common::KEYCODE_z; +#else case SDLK_BACKQUOTE: return Common::KEYCODE_BACKQUOTE; case SDLK_a: return Common::KEYCODE_a; case SDLK_b: return Common::KEYCODE_b; @@ -290,6 +486,7 @@ Common::KeyCode SdlEventSource::SDLToOSystemKeycode(const SDL_Keycode key) { case SDLK_x: return Common::KEYCODE_x; case SDLK_y: return Common::KEYCODE_y; case SDLK_z: return Common::KEYCODE_z; +#endif case SDLK_DELETE: return Common::KEYCODE_DELETE; case SDLK_KP_PERIOD: return Common::KEYCODE_KP_PERIOD; case SDLK_KP_DIVIDE: return Common::KEYCODE_KP_DIVIDE; @@ -360,13 +557,26 @@ Common::KeyCode SdlEventSource::SDLToOSystemKeycode(const SDL_Keycode key) { case SDLK_F17: return Common::KEYCODE_F17; case SDLK_F18: return Common::KEYCODE_F18; case SDLK_SLEEP: return Common::KEYCODE_SLEEP; - case SDLK_MUTE: return Common::KEYCODE_MUTE; case SDLK_VOLUMEUP: return Common::KEYCODE_VOLUMEUP; case SDLK_VOLUMEDOWN: return Common::KEYCODE_VOLUMEDOWN; +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDLK_MEDIA_EJECT: return Common::KEYCODE_EJECT; + case SDLK_MEDIA_NEXT_TRACK: return Common::KEYCODE_AUDIONEXT; + case SDLK_MEDIA_PREVIOUS_TRACK: return Common::KEYCODE_AUDIOPREV; + case SDLK_MEDIA_STOP: return Common::KEYCODE_AUDIOSTOP; + case SDLK_MEDIA_PLAY: return Common::KEYCODE_AUDIOPLAYPAUSE; + case SDLK_MUTE: return Common::KEYCODE_AUDIOMUTE; +#else case SDLK_EJECT: return Common::KEYCODE_EJECT; - case SDLK_WWW: return Common::KEYCODE_WWW; case SDLK_MAIL: return Common::KEYCODE_MAIL; + case SDLK_WWW: return Common::KEYCODE_WWW; case SDLK_CALCULATOR: return Common::KEYCODE_CALCULATOR; + case SDLK_AUDIONEXT: return Common::KEYCODE_AUDIONEXT; + case SDLK_AUDIOPREV: return Common::KEYCODE_AUDIOPREV; + case SDLK_AUDIOSTOP: return Common::KEYCODE_AUDIOSTOP; + case SDLK_AUDIOPLAY: return Common::KEYCODE_AUDIOPLAYPAUSE; + case SDLK_AUDIOMUTE: return Common::KEYCODE_AUDIOMUTE; +#endif case SDLK_CUT: return Common::KEYCODE_CUT; case SDLK_COPY: return Common::KEYCODE_COPY; case SDLK_PASTE: return Common::KEYCODE_PASTE; @@ -379,12 +589,10 @@ Common::KeyCode SdlEventSource::SDLToOSystemKeycode(const SDL_Keycode key) { case SDLK_AC_STOP: return Common::KEYCODE_AC_STOP; case SDLK_AC_REFRESH: return Common::KEYCODE_AC_REFRESH; case SDLK_AC_BOOKMARKS: return Common::KEYCODE_AC_BOOKMARKS; - case SDLK_AUDIONEXT: return Common::KEYCODE_AUDIONEXT; - case SDLK_AUDIOPREV: return Common::KEYCODE_AUDIOPREV; - case SDLK_AUDIOSTOP: return Common::KEYCODE_AUDIOSTOP; - case SDLK_AUDIOPLAY: return Common::KEYCODE_AUDIOPLAYPAUSE; - case SDLK_AUDIOMUTE: return Common::KEYCODE_AUDIOMUTE; -#if SDL_VERSION_ATLEAST(2, 0, 6) +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDLK_MEDIA_REWIND: return Common::KEYCODE_AUDIOREWIND; + case SDLK_MEDIA_FAST_FORWARD: return Common::KEYCODE_AUDIOFASTFORWARD; +#elif SDL_VERSION_ATLEAST(2, 0, 6) case SDLK_AUDIOREWIND: return Common::KEYCODE_AUDIOREWIND; case SDLK_AUDIOFASTFORWARD: return Common::KEYCODE_AUDIOFASTFORWARD; #endif @@ -417,10 +625,17 @@ Common::KeyCode SdlEventSource::SDLToOSystemKeycode(const SDL_Keycode key) { #if SDL_VERSION_ATLEAST(2, 0, 0) void SdlEventSource::preprocessFingerDown(SDL_Event *event) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + // front (1) or back (2) panel + SDL_TouchID port = event->tfinger.touchID; + // id (for multitouch) + SDL_FingerID id = event->tfinger.fingerID; +#else // front (1) or back (2) panel SDL_TouchID port = event->tfinger.touchId; // id (for multitouch) SDL_FingerID id = event->tfinger.fingerId; +#endif int x = _mouseX; int y = _mouseY; @@ -487,7 +702,11 @@ void SdlEventSource::finishSimulatedMouseClicks() { simulatedButton = SDL_BUTTON_RIGHT; } SDL_Event ev; +#if SDL_VERSION_ATLEAST(3, 0, 0) + ev.type = SDL_EVENT_MOUSE_BUTTON_UP; +#else ev.type = SDL_MOUSEBUTTONUP; +#endif ev.button.button = simulatedButton; ev.button.x = _mouseX; ev.button.y = _mouseY; @@ -501,10 +720,17 @@ void SdlEventSource::finishSimulatedMouseClicks() { } bool SdlEventSource::preprocessFingerUp(SDL_Event *event, Common::Event *ev) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + // front (1) or back (2) panel + SDL_TouchID port = event->tfinger.touchID; + // id (for multitouch) + SDL_FingerID id = event->tfinger.fingerID; +#else // front (1) or back (2) panel SDL_TouchID port = event->tfinger.touchId; // id (for multitouch) SDL_FingerID id = event->tfinger.fingerId; +#endif // find out how many fingers were down before this event int numFingersDown = 0; @@ -549,7 +775,11 @@ bool SdlEventSource::preprocessFingerUp(SDL_Event *event, Common::Event *ev) { } } +#if SDL_VERSION_ATLEAST(3, 0, 0) + event->type = SDL_EVENT_MOUSE_BUTTON_DOWN; +#else event->type = SDL_MOUSEBUTTONDOWN; +#endif event->button.button = simulatedButton; event->button.x = x; event->button.y = y; @@ -567,7 +797,11 @@ bool SdlEventSource::preprocessFingerUp(SDL_Event *event, Common::Event *ev) { else { simulatedButton = SDL_BUTTON_LEFT; } +#if SDL_VERSION_ATLEAST(3, 0, 0) + event->type = SDL_EVENT_MOUSE_BUTTON_UP; +#else event->type = SDL_MOUSEBUTTONUP; +#endif event->button.button = simulatedButton; event->button.x = x; event->button.y = y; @@ -584,10 +818,17 @@ bool SdlEventSource::preprocessFingerUp(SDL_Event *event, Common::Event *ev) { } void SdlEventSource::preprocessFingerMotion(SDL_Event *event) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + // front (1) or back (2) panel + SDL_TouchID port = event->tfinger.touchID; + // id (for multitouch) + SDL_FingerID id = event->tfinger.fingerID; +#else // front (1) or back (2) panel SDL_TouchID port = event->tfinger.touchId; // id (for multitouch) SDL_FingerID id = event->tfinger.fingerId; +#endif // find out how many fingers were down before this event int numFingersDown = 0; @@ -676,7 +917,11 @@ void SdlEventSource::preprocessFingerMotion(SDL_Event *event) { _touchPanels[port]._multiFingerDragging = DRAG_THREE_FINGER; } SDL_Event ev; +#if SDL_VERSION_ATLEAST(3, 0, 0) + ev.type = SDL_EVENT_MOUSE_BUTTON_DOWN; +#else ev.type = SDL_MOUSEBUTTONDOWN; +#endif ev.button.button = simulatedButton; ev.button.x = mouseDownX; ev.button.y = mouseDownY; @@ -701,7 +946,11 @@ void SdlEventSource::preprocessFingerMotion(SDL_Event *event) { } } if (updatePointer) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + event->type = SDL_EVENT_MOUSE_MOTION; +#else event->type = SDL_MOUSEMOTION; +#endif event->motion.x = x; event->motion.y = y; } @@ -740,7 +989,33 @@ bool SdlEventSource::pollEvent(Common::Event &event) { while (SDL_PollEvent(&ev)) { preprocessEvents(&ev); -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + // Supported touch gestures: + // left mouse click: single finger short tap + // right mouse click: second finger short tap while first finger is still down + // pointer motion: single finger drag + if (ev.type == SDL_EVENT_FINGER_DOWN || ev.type == SDL_EVENT_FINGER_UP || ev.type == SDL_EVENT_FINGER_MOTION) { + // front (0) or back (1) panel + SDL_TouchID port = ev.tfinger.touchID; + // touchpad_mouse_mode off: use only front panel for direct touch control of pointer + // touchpad_mouse_mode on: also enable rear touch with indirect touch control + // where the finger can be somewhere else than the pointer and still move it + if (isTouchPortActive(port)) { + switch (ev.type) { + case SDL_EVENT_FINGER_DOWN: + preprocessFingerDown(&ev); + break; + case SDL_EVENT_FINGER_UP: + if (preprocessFingerUp(&ev, &event)) + return true; + break; + case SDL_EVENT_FINGER_MOTION: + preprocessFingerMotion(&ev); + break; + } + } + } +#elif SDL_VERSION_ATLEAST(2, 0, 0) // Supported touch gestures: // left mouse click: single finger short tap // right mouse click: second finger short tap while first finger is still down @@ -768,13 +1043,20 @@ bool SdlEventSource::pollEvent(Common::Event &event) { } #endif -#if defined(USE_IMGUI) && SDL_VERSION_ATLEAST(2, 0, 0) +#if defined(USE_IMGUI) +#if SDL_VERSION_ATLEAST(3, 0, 0) + ImGui_ImplSDL3_ProcessEvent(&ev); + ImGuiIO &io = ImGui::GetIO(); + if (io.WantTextInput || io.WantCaptureMouse) + continue; +#elif SDL_VERSION_ATLEAST(2, 0, 0) if (ImGui_ImplSDL2_Ready()) { ImGui_ImplSDL2_ProcessEvent(&ev); ImGuiIO &io = ImGui::GetIO(); if (io.WantTextInput || io.WantCaptureMouse) continue; } +#endif #endif if (dispatchSDLEvent(ev, event)) return true; @@ -784,6 +1066,19 @@ bool SdlEventSource::pollEvent(Common::Event &event) { } bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + switch (ev.type) { + case SDL_EVENT_KEY_DOWN: + return handleKeyDown(ev, event); + case SDL_EVENT_KEY_UP: + return handleKeyUp(ev, event); + case SDL_EVENT_MOUSE_MOTION: + return handleMouseMotion(ev, event); + case SDL_EVENT_MOUSE_BUTTON_DOWN: + return handleMouseButtonDown(ev, event); + case SDL_EVENT_MOUSE_BUTTON_UP: + return handleMouseButtonUp(ev, event); +#else switch (ev.type) { case SDL_KEYDOWN: return handleKeyDown(ev, event); @@ -797,9 +1092,14 @@ bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { return handleMouseButtonUp(ev, event); case SDL_SYSWMEVENT: return handleSysWMEvent(ev, event); +#endif #if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_MOUSE_WHEEL: { +#else case SDL_MOUSEWHEEL: { +#endif Sint32 yDir = ev.wheel.y; // We want the mouse coordinates supplied with a mouse wheel event. // However, SDL2 does not supply these, thus we use whatever we got @@ -818,7 +1118,11 @@ bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { } } +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_TEXT_INPUT: { +#else case SDL_TEXTINPUT: { +#endif // When we get a TEXTINPUT event it means we got some user input for // which no KEYDOWN exists. SDL 1.2 introduces a "fake" key down+up // in such cases. We will do the same to mimic it's behavior. @@ -839,6 +1143,7 @@ bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { return _queuedFakeKeyUp; } +#if !SDL_VERSION_ATLEAST(3, 0, 0) case SDL_WINDOWEVENT: // We're only interested in events from the current display window if (_graphicsManager) { @@ -849,7 +1154,13 @@ bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { } switch (ev.window.event) { +#endif + +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_WINDOW_EXPOSED: +#else case SDL_WINDOWEVENT_EXPOSED: +#endif if (_graphicsManager) { _graphicsManager->notifyVideoExpose(); } @@ -865,11 +1176,19 @@ bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { // where we need to call SDL_SetWindowSize and we need the resulting event to be processed. // However if the documentation is correct we can ignore SDL_WINDOWEVENT_RESIZED since when we // get one we should always get a SDL_WINDOWEVENT_SIZE_CHANGED as well. +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED: +#else case SDL_WINDOWEVENT_SIZE_CHANGED: +#endif //case SDL_WINDOWEVENT_RESIZED: return handleResizeEvent(event, ev.window.data1, ev.window.data2); +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_WINDOW_FOCUS_GAINED: { +#else case SDL_WINDOWEVENT_FOCUS_GAINED: { +#endif // When we gain focus, we to update whether the display can turn off // dependingif a game isn't running or not event.type = Common::EVENT_FOCUS_GAINED; @@ -881,30 +1200,55 @@ bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { return true; } +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_WINDOW_FOCUS_LOST: { +#else case SDL_WINDOWEVENT_FOCUS_LOST: { +#endif // Always allow the display to turn off if ScummVM is out of focus event.type = Common::EVENT_FOCUS_LOST; SDL_EnableScreenSaver(); return true; } +#if !SDL_VERSION_ATLEAST(3, 0, 0) default: return false; } +#endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_JOYSTICK_ADDED: +#else case SDL_JOYDEVICEADDED: +#endif return handleJoystickAdded(ev.jdevice, event); +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_JOYSTICK_REMOVED: +#else case SDL_JOYDEVICEREMOVED: +#endif return handleJoystickRemoved(ev.jdevice, event); +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_DROP_FILE: + event.type = Common::EVENT_DROP_FILE; + event.path = Common::Path(ev.drop.data, Common::Path::kNativeSeparator); + return true; +#else case SDL_DROPFILE: event.type = Common::EVENT_DROP_FILE; event.path = Common::Path(ev.drop.file, Common::Path::kNativeSeparator); SDL_free(ev.drop.file); return true; +#endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_CLIPBOARD_UPDATE: +#else case SDL_CLIPBOARDUPDATE: +#endif event.type = Common::EVENT_CLIPBOARD_UPDATE; return true; #else @@ -918,7 +1262,11 @@ bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { return handleResizeEvent(event, ev.resize.w, ev.resize.h); #endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + case SDL_EVENT_QUIT: +#else case SDL_QUIT: +#endif event.type = Common::EVENT_QUIT; return true; @@ -926,6 +1274,22 @@ bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { break; } +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (_joystick) { + switch (ev.type) { + case SDL_EVENT_JOYSTICK_BUTTON_DOWN: + return handleJoyButtonDown(ev, event); + case SDL_EVENT_JOYSTICK_BUTTON_UP: + return handleJoyButtonUp(ev, event); + case SDL_EVENT_JOYSTICK_AXIS_MOTION: + return handleJoyAxisMotion(ev, event); + case SDL_EVENT_JOYSTICK_HAT_MOTION: + return handleJoyHatMotion(ev, event); + default: + break; + } + } +#else if (_joystick) { switch (ev.type) { case SDL_JOYBUTTONDOWN: @@ -940,8 +1304,22 @@ bool SdlEventSource::dispatchSDLEvent(SDL_Event &ev, Common::Event &event) { break; } } +#endif -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (_controller) { + switch (ev.type) { + case SDL_EVENT_GAMEPAD_BUTTON_DOWN: + return handleControllerButton(ev, event, false); + case SDL_EVENT_GAMEPAD_BUTTON_UP: + return handleControllerButton(ev, event, true); + case SDL_EVENT_GAMEPAD_AXIS_MOTION: + return handleControllerAxisMotion(ev, event); + default: + break; + } + } +#elif SDL_VERSION_ATLEAST(2, 0, 0) if (_controller) { switch (ev.type) { case SDL_CONTROLLERBUTTONDOWN: @@ -964,7 +1342,11 @@ bool SdlEventSource::handleKeyDown(SDL_Event &ev, Common::Event &event) { SDLModToOSystemKeyFlags(SDL_GetModState(), event); +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Keycode sdlKeycode = ev.key.key; +#else SDL_Keycode sdlKeycode = obtainKeycode(ev.key.keysym); +#endif Common::KeyCode key = SDLToOSystemKeycode(sdlKeycode); // Handle scroll lock as a key modifier @@ -980,7 +1362,11 @@ bool SdlEventSource::handleKeyDown(SDL_Event &ev, Common::Event &event) { event.type = Common::EVENT_KEYDOWN; event.kbd.keycode = key; +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Keymod mod = ev.key.mod; +#else SDL_Keymod mod = (SDL_Keymod)ev.key.keysym.mod; +#endif #if defined(__amigaos4__) // On AmigaOS, SDL always reports numlock as off. However, we get KEYCODE_KP# only when // it is on, and get different keycodes (for example KEYCODE_PAGEDOWN) when it is off. @@ -989,7 +1375,7 @@ bool SdlEventSource::handleKeyDown(SDL_Event &ev, Common::Event &event) { mod = SDL_Keymod(mod | KMOD_NUM); } #endif - event.kbd.ascii = mapKey(sdlKeycode, mod, obtainUnicode(ev.key.keysym)); + event.kbd.ascii = mapKey(sdlKeycode, mod, obtainUnicode(ev.key)); #if SDL_VERSION_ATLEAST(2, 0, 0) event.kbdRepeat = ev.key.repeat; @@ -1004,7 +1390,11 @@ bool SdlEventSource::handleKeyUp(SDL_Event &ev, Common::Event &event) { SDLModToOSystemKeyFlags(SDL_GetModState(), event); +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Keycode sdlKeycode = ev.key.key; +#else SDL_Keycode sdlKeycode = obtainKeycode(ev.key.keysym); +#endif // Set the scroll lock sticky flag if (_scrollLock) @@ -1013,7 +1403,12 @@ bool SdlEventSource::handleKeyUp(SDL_Event &ev, Common::Event &event) { event.type = Common::EVENT_KEYUP; event.kbd.keycode = SDLToOSystemKeycode(sdlKeycode); +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Keymod mod = ev.key.mod; +#else SDL_Keymod mod = (SDL_Keymod)ev.key.keysym.mod; +#endif + #if defined(__amigaos4__) // On AmigaOS, SDL always reports numlock as off. However, we get KEYCODE_KP# only when // it is on, and get different keycodes (for example KEYCODE_PAGEDOWN) when it is off. @@ -1090,18 +1485,18 @@ bool SdlEventSource::handleSysWMEvent(SDL_Event &ev, Common::Event &event) { } void SdlEventSource::openJoystick(int joystickIndex) { - if (SDL_NumJoysticks() > joystickIndex) { + if (numJoysticks() > joystickIndex) { #if SDL_VERSION_ATLEAST(2, 0, 0) - if (SDL_IsGameController(joystickIndex)) { - _controller = SDL_GameControllerOpen(joystickIndex); - debug("Using game controller: %s", SDL_GameControllerName(_controller)); + if (isGamepad(joystickIndex)) { + _controller = openGamepad(joystickIndex); + debug("Using game controller: %s", getGamepadName(_controller)); } else #endif { - _joystick = SDL_JoystickOpen(joystickIndex); + _joystick = ::openJoystick(joystickIndex); debug("Using joystick: %s", #if SDL_VERSION_ATLEAST(2, 0, 0) - SDL_JoystickName(_joystick) + getJoystickName(_joystick) #else SDL_JoystickName(joystickIndex) #endif @@ -1115,12 +1510,12 @@ void SdlEventSource::openJoystick(int joystickIndex) { void SdlEventSource::closeJoystick() { #if SDL_VERSION_ATLEAST(2, 0, 0) if (_controller) { - SDL_GameControllerClose(_controller); + closeGamepad(_controller); _controller = nullptr; } #endif if (_joystick) { - SDL_JoystickClose(_joystick); + ::closeJoystick(_joystick); _joystick = nullptr; } } @@ -1231,7 +1626,7 @@ bool SdlEventSource::handleJoystickRemoved(const SDL_JoyDeviceEvent &device, Com SDL_Joystick *joystick; if (_controller) { - joystick = SDL_GameControllerGetJoystick(_controller); + joystick = getGamepadJoystick(_controller); } else { joystick = _joystick; } @@ -1240,7 +1635,7 @@ bool SdlEventSource::handleJoystickRemoved(const SDL_JoyDeviceEvent &device, Com return false; } - if (SDL_JoystickInstanceID(joystick) != device.which) { + if (getJoystickID(joystick) != device.which) { return false; } @@ -1279,7 +1674,11 @@ int SdlEventSource::mapSDLControllerButtonToOSystem(Uint8 sdlButton) { } bool SdlEventSource::handleControllerButton(const SDL_Event &ev, Common::Event &event, bool buttonUp) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + int button = mapSDLControllerButtonToOSystem(ev.gbutton.button); +#else int button = mapSDLControllerButtonToOSystem(ev.cbutton.button); +#endif if (button < 0) return false; @@ -1291,9 +1690,14 @@ bool SdlEventSource::handleControllerButton(const SDL_Event &ev, Common::Event & } bool SdlEventSource::handleControllerAxisMotion(const SDL_Event &ev, Common::Event &event) { - event.type = Common::EVENT_JOYAXIS_MOTION; +#if SDL_VERSION_ATLEAST(3, 0, 0) + event.joystick.axis = ev.gaxis.axis; + event.joystick.position = ev.gaxis.value; +#else event.joystick.axis = ev.caxis.axis; event.joystick.position = ev.caxis.value; +#endif + event.type = Common::EVENT_JOYAXIS_MOTION; return true; } @@ -1337,6 +1741,7 @@ bool SdlEventSource::handleResizeEvent(Common::Event &event, int w, int h) { return false; } +#if !SDL_VERSION_ATLEAST(3, 0, 0) SDL_Keycode SdlEventSource::obtainKeycode(const SDL_Keysym keySym) { #if !SDL_VERSION_ATLEAST(2, 0, 0) && defined(WIN32) // WORKAROUND: SDL 1.2 on Windows does not use the user configured keyboard layout, @@ -1374,8 +1779,9 @@ SDL_Keycode SdlEventSource::obtainKeycode(const SDL_Keysym keySym) { return keySym.sym; } +#endif -uint32 SdlEventSource::obtainUnicode(const SDL_Keysym keySym) { +uint32 SdlEventSource::obtainUnicode(const SDL_KeyboardEvent &key) { #if SDL_VERSION_ATLEAST(2, 0, 0) SDL_Event events[2]; @@ -1398,15 +1804,27 @@ uint32 SdlEventSource::obtainUnicode(const SDL_Keysym keySym) { // Instead a SDL_TEXTINPUT event is generated on key combinations that // generates unicode. // Here we peek into the event queue for the event to see if it exists. +#if SDL_VERSION_ATLEAST(3, 0, 0) + int n = SDL_PeepEvents(events, 2, SDL_PEEKEVENT, SDL_EVENT_KEY_DOWN, SDL_EVENT_TEXT_INPUT); + // Make sure that the TEXTINPUT event belongs to this KEYDOWN + // event and not another pending one. + if ((n > 0 && events[0].type == SDL_EVENT_TEXT_INPUT) + || (n > 1 && events[0].type != SDL_EVENT_KEY_DOWN && events[1].type == SDL_EVENT_TEXT_INPUT)) { +#else int n = SDL_PeepEvents(events, 2, SDL_PEEKEVENT, SDL_KEYDOWN, SDL_TEXTINPUT); // Make sure that the TEXTINPUT event belongs to this KEYDOWN // event and not another pending one. if ((n > 0 && events[0].type == SDL_TEXTINPUT) || (n > 1 && events[0].type != SDL_KEYDOWN && events[1].type == SDL_TEXTINPUT)) { +#endif // Remove the text input event we associate with the key press. This // makes sure we never get any SDL_TEXTINPUT events which do "belong" // to SDL_KEYDOWN events. +#if SDL_VERSION_ATLEAST(3, 0, 0) + n = SDL_PeepEvents(events, 1, SDL_GETEVENT, SDL_EVENT_TEXT_INPUT, SDL_EVENT_TEXT_INPUT); +#else n = SDL_PeepEvents(events, 1, SDL_GETEVENT, SDL_TEXTINPUT, SDL_TEXTINPUT); +#endif // This is basically a paranoia safety check because we know there // must be a text input event in the queue. if (n > 0) { @@ -1418,7 +1836,7 @@ uint32 SdlEventSource::obtainUnicode(const SDL_Keysym keySym) { return 0; } #else - return keySym.unicode; + return key.keysym.unicode; #endif } diff --git a/backends/events/sdl/sdl-events.h b/backends/events/sdl/sdl-events.h index 2fcf289e7bc7..02b548ee9de5 100644 --- a/backends/events/sdl/sdl-events.h +++ b/backends/events/sdl/sdl-events.h @@ -73,7 +73,10 @@ class SdlEventSource : public Common::EventSource { /** Joystick */ SDL_Joystick *_joystick; -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + /** Game controller */ + SDL_Gamepad *_controller; +#elif SDL_VERSION_ATLEAST(2, 0, 0) /** Game controller */ SDL_GameController *_controller; #endif @@ -186,15 +189,17 @@ class SdlEventSource : public Common::EventSource { bool handleResizeEvent(Common::Event &event, int w, int h); /** - * Extracts unicode information for the specific key sym. + * Extracts unicode information for the specific key. * May only be used for key down events. */ - uint32 obtainUnicode(const SDL_Keysym keySym); + uint32 obtainUnicode(const SDL_KeyboardEvent &key); +#if !SDL_VERSION_ATLEAST(3, 0, 0) /** * Extracts the keycode for the specified key sym. */ SDL_Keycode obtainKeycode(const SDL_Keysym keySym); +#endif /** * Whether _fakeMouseMove contains an event we need to send. diff --git a/backends/graphics/openglsdl/openglsdl-graphics.cpp b/backends/graphics/openglsdl/openglsdl-graphics.cpp index 35dd7e3101da..0f3fb789a8ce 100644 --- a/backends/graphics/openglsdl/openglsdl-graphics.cpp +++ b/backends/graphics/openglsdl/openglsdl-graphics.cpp @@ -34,6 +34,16 @@ #include "common/translation.h" #endif +#if SDL_VERSION_ATLEAST(3, 0, 0) +void sdlGLDestroyContext(SDL_GLContext context) { + SDL_GL_DestroyContext(context); +} +#elif SDL_VERSION_ATLEAST(2, 0, 0) +void sdlGLDestroyContext(SDL_GLContext context) { + SDL_GL_DeleteContext(context); +} +#endif + OpenGLSdlGraphicsManager::OpenGLSdlGraphicsManager(SdlEventSource *eventSource, SdlWindow *window) : SdlGraphicsManager(eventSource, window), _lastRequestedHeight(0), #if SDL_VERSION_ATLEAST(2, 0, 0) @@ -201,7 +211,7 @@ OpenGLSdlGraphicsManager::~OpenGLSdlGraphicsManager() { #endif notifyContextDestroy(); - SDL_GL_DeleteContext(_glContext); + sdlGLDestroyContext(_glContext); #else if (_hwScreen) { notifyContextDestroy(); @@ -255,7 +265,14 @@ void OpenGLSdlGraphicsManager::setFeatureState(OSystem::Feature f, bool enable) bool OpenGLSdlGraphicsManager::getFeatureState(OSystem::Feature f) const { switch (f) { case OSystem::kFeatureFullscreenMode: -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (_window && _window->getSDLWindow()) { + // SDL_GetWindowFullscreenMode returns a pointer to the exclusive fullscreen mode to use or NULL for borderless + return ((SDL_GetWindowFlags(_window->getSDLWindow()) & SDL_WINDOW_FULLSCREEN) != 0) && (SDL_GetWindowFullscreenMode(_window->getSDLWindow()) == NULL); + } else { + return _wantsFullScreen; + } +#elif SDL_VERSION_ATLEAST(2, 0, 0) if (_window && _window->getSDLWindow()) { return (SDL_GetWindowFlags(_window->getSDLWindow()) & SDL_WINDOW_FULLSCREEN_DESKTOP) != 0; } else { @@ -574,11 +591,15 @@ bool OpenGLSdlGraphicsManager::setupMode(uint width, uint height) { destroyImGui(); #endif - SDL_GL_DeleteContext(_glContext); + sdlGLDestroyContext(_glContext); _glContext = nullptr; } +#if SDL_VERSION_ATLEAST(3, 0, 0) + uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY; +#else uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI; +#endif if (_wantsFullScreen) { // On Linux/X11, when toggling to fullscreen, the window manager saves @@ -596,7 +617,13 @@ bool OpenGLSdlGraphicsManager::setupMode(uint width, uint height) { width = _desiredFullscreenWidth; height = _desiredFullscreenHeight; +#if SDL_VERSION_ATLEAST(3, 0, 0) + flags |= SDL_WINDOW_FULLSCREEN; + SDL_SetWindowFullscreenMode(_window->getSDLWindow(), NULL); + SDL_SyncWindow(_window->getSDLWindow()); +#else flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; +#endif } if (!_wantsFullScreen && ConfMan.getBool("window_maximized", Common::ConfigManager::kApplicationDomain)) { @@ -608,7 +635,7 @@ bool OpenGLSdlGraphicsManager::setupMode(uint width, uint height) { SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, _glContextMajor); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, _glContextMinor); -#ifdef NINTENDO_SWITCH +#if defined(NINTENDO_SWITCH) && !SDL_VERSION_ATLEAST(3, 0, 0) // Switch quirk: Switch seems to need this flag, otherwise the screen // is zoomed when switching from Normal graphics mode to OpenGL flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; @@ -627,7 +654,7 @@ bool OpenGLSdlGraphicsManager::setupMode(uint width, uint height) { initImGui(nullptr, _glContext); #endif - if (SDL_GL_SetSwapInterval(_vsync ? 1 : 0)) { + if (!SDL_GL_SetSwapInterval(_vsync ? 1 : 0)) { warning("Unable to %s VSync: %s", _vsync ? "enable" : "disable", SDL_GetError()); } diff --git a/backends/graphics/sdl/sdl-graphics.cpp b/backends/graphics/sdl/sdl-graphics.cpp index e2fd1e9342a7..5326a13a2735 100644 --- a/backends/graphics/sdl/sdl-graphics.cpp +++ b/backends/graphics/sdl/sdl-graphics.cpp @@ -38,7 +38,15 @@ #include "backends/platform/sdl/emscripten/emscripten.h" #endif -#if defined(USE_IMGUI) && SDL_VERSION_ATLEAST(2, 0, 0) +#if defined(USE_IMGUI) && SDL_VERSION_ATLEAST(3, 0, 0) +#include "backends/imgui/backends/imgui_impl_sdl3.h" +#ifdef USE_OPENGL +#include "backends/imgui/backends/imgui_impl_opengl3.h" +#endif +#ifdef USE_IMGUI_SDLRENDERER3 +#include "backends/imgui/backends/imgui_impl_sdlrenderer3.h" +#endif +#elif defined(USE_IMGUI) && SDL_VERSION_ATLEAST(2, 0, 0) #include "backends/imgui/backends/imgui_impl_sdl2.h" #ifdef USE_OPENGL #include "backends/imgui/backends/imgui_impl_opengl3.h" @@ -48,6 +56,18 @@ #endif #endif + +void getMouseState(int *x, int *y) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + float fx, fy; + SDL_GetMouseState(&fx, &fy); + *x = static_cast(fx); + *y = static_cast(fy); +#else + SDL_GetMouseState(x, y); +#endif +} + SdlGraphicsManager::SdlGraphicsManager(SdlEventSource *source, SdlWindow *window) : _eventSource(source), _window(window), _hwScreen(nullptr) #if SDL_VERSION_ATLEAST(2, 0, 0) @@ -56,7 +76,7 @@ SdlGraphicsManager::SdlGraphicsManager(SdlEventSource *source, SdlWindow *window { ConfMan.registerDefault("fullscreen_res", "desktop"); - SDL_GetMouseState(&_cursorX, &_cursorY); + getMouseState(&_cursorX, &_cursorY); } void SdlGraphicsManager::activateManager() { @@ -220,7 +240,7 @@ bool SdlGraphicsManager::showMouse(bool visible) { // area, so we need to ask SDL where the system's mouse cursor is // instead int x, y; - SDL_GetMouseState(&x, &y); + getMouseState(&x, &y); if (!_activeArea.drawRect.contains(Common::Point(x, y))) { showCursor = true; } @@ -312,7 +332,15 @@ bool SdlGraphicsManager::notifyMousePosition(Common::Point &mouse) { } void SdlGraphicsManager::showSystemMouseCursor(bool visible) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + if(visible) { + SDL_ShowCursor(); + } else { + SDL_HideCursor(); + } +#else SDL_ShowCursor(visible ? SDL_ENABLE : SDL_DISABLE); +#endif } void SdlGraphicsManager::setSystemMousePosition(const int x, const int y) { @@ -354,7 +382,11 @@ bool SdlGraphicsManager::createOrUpdateWindow(int width, int height, const Uint3 // resized the game window), or when the launcher is visible (since a user // may change the scaler, which should reset the window size) if (!_window->getSDLWindow() || _lastFlags != flags || _overlayVisible || _allowWindowSizeReset) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + const bool fullscreen = (flags & (SDL_WINDOW_FULLSCREEN)) != 0; +#else const bool fullscreen = (flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_FULLSCREEN_DESKTOP)) != 0; +#endif const bool maximized = (flags & SDL_WINDOW_MAXIMIZED); if (!fullscreen && !maximized) { if (_hintedWidth > width) { @@ -368,6 +400,14 @@ bool SdlGraphicsManager::createOrUpdateWindow(int width, int height, const Uint3 if (!_window->createOrUpdateWindow(width, height, flags)) { return false; } +#if SDL_VERSION_ATLEAST(3, 0, 0) + if(fullscreen) { + if(!SDL_SetWindowFullscreenMode(_window->getSDLWindow(), NULL)) + return false; + if(!SDL_SyncWindow(_window->getSDLWindow())) + return false; + } +#endif _lastFlags = flags; _allowWindowSizeReset = false; @@ -594,13 +634,21 @@ void SdlGraphicsManager::initImGui(SDL_Renderer *renderer, void *glContext) { if (!_imGuiReady && glContext) { io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (!ImGui_ImplSDL3_InitForOpenGL(_window->getSDLWindow(), glContext)) { +#else if (!ImGui_ImplSDL2_InitForOpenGL(_window->getSDLWindow(), glContext)) { +#endif ImGui::DestroyContext(); return; } if (!ImGui_ImplOpenGL3_Init("#version 110")) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + ImGui_ImplSDL3_Shutdown(); +#else ImGui_ImplSDL2_Shutdown(); +#endif ImGui::DestroyContext(); return; } @@ -608,7 +656,23 @@ void SdlGraphicsManager::initImGui(SDL_Renderer *renderer, void *glContext) { _imGuiReady = true; } #endif -#ifdef USE_IMGUI_SDLRENDERER2 +#ifdef USE_IMGUI_SDLRENDERER3 + if (!_imGuiReady && renderer) { + if (!ImGui_ImplSDL3_InitForSDLRenderer(_window->getSDLWindow(), renderer)) { + ImGui::DestroyContext(); + return; + } + + if (!ImGui_ImplSDLRenderer3_Init(renderer)) { + ImGui_ImplSDL3_Shutdown(); + ImGui::DestroyContext(); + return; + } + + _imGuiReady = true; + _imGuiSDLRenderer = renderer; + } +#elif defined(USE_IMGUI_SDLRENDERER2) if (!_imGuiReady && renderer) { if (!ImGui_ImplSDL2_InitForSDLRenderer(_window->getSDLWindow(), renderer)) { ImGui::DestroyContext(); @@ -649,7 +713,11 @@ void SdlGraphicsManager::renderImGui() { _imGuiInited = true; } -#ifdef USE_IMGUI_SDLRENDERER2 +#ifdef USE_IMGUI_SDLRENDERER3 + if (_imGuiSDLRenderer) { + ImGui_ImplSDLRenderer3_NewFrame(); + } else { +#elif defined(USE_IMGUI_SDLRENDERER2) if (_imGuiSDLRenderer) { ImGui_ImplSDLRenderer2_NewFrame(); } else { @@ -657,15 +725,23 @@ void SdlGraphicsManager::renderImGui() { #ifdef USE_OPENGL ImGui_ImplOpenGL3_NewFrame(); #endif -#ifdef USE_IMGUI_SDLRENDERER2 +#if defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3) } #endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + ImGui_ImplSDL3_NewFrame(); +#else ImGui_ImplSDL2_NewFrame(); +#endif ImGui::NewFrame(); _imGuiCallbacks.render(); ImGui::Render(); -#ifdef USE_IMGUI_SDLRENDERER2 +#ifdef USE_IMGUI_SDLRENDERER3 + if (_imGuiSDLRenderer) { + ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData(), _imGuiSDLRenderer); + } else { +#elif defined(USE_IMGUI_SDLRENDERER2) if (_imGuiSDLRenderer) { ImGui_ImplSDLRenderer2_RenderDrawData(ImGui::GetDrawData(), _imGuiSDLRenderer); } else { @@ -679,7 +755,7 @@ void SdlGraphicsManager::renderImGui() { ImGui::RenderPlatformWindowsDefault(); SDL_GL_MakeCurrent(backup_current_window, backup_current_context); #endif -#ifdef USE_IMGUI_SDLRENDERER2 +#if defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3) } #endif } @@ -696,7 +772,11 @@ void SdlGraphicsManager::destroyImGui() { _imGuiInited = false; _imGuiReady = false; -#ifdef USE_IMGUI_SDLRENDERER2 +#ifdef USE_IMGUI_SDLRENDERER3 + if (_imGuiSDLRenderer) { + ImGui_ImplSDLRenderer3_Shutdown(); + } else { +#elif defined(USE_IMGUI_SDLRENDERER2) if (_imGuiSDLRenderer) { ImGui_ImplSDLRenderer2_Shutdown(); } else { @@ -704,10 +784,14 @@ void SdlGraphicsManager::destroyImGui() { #ifdef USE_OPENGL ImGui_ImplOpenGL3_Shutdown(); #endif -#ifdef USE_IMGUI_SDLRENDERER2 +#if defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3) } #endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + ImGui_ImplSDL3_Shutdown(); +#else ImGui_ImplSDL2_Shutdown(); +#endif ImGui::DestroyContext(); } #endif diff --git a/backends/graphics/sdl/sdl-graphics.h b/backends/graphics/sdl/sdl-graphics.h index af5d76514f68..8225b2d4046e 100644 --- a/backends/graphics/sdl/sdl-graphics.h +++ b/backends/graphics/sdl/sdl-graphics.h @@ -161,7 +161,10 @@ class SdlGraphicsManager : virtual public WindowedGraphicsManager, public Common * values stored by the graphics manager. */ void getWindowSizeFromSdl(int *width, int *height) const { -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + assert(_window); + SDL_GetWindowSizeInPixels(_window->getSDLWindow(), width, height); +#elif SDL_VERSION_ATLEAST(2, 0, 0) assert(_window); SDL_GL_GetDrawableSize(_window->getSDLWindow(), width, height); #else diff --git a/backends/graphics/surfacesdl/surfacesdl-graphics.cpp b/backends/graphics/surfacesdl/surfacesdl-graphics.cpp index 9a63088c7009..89512b9d364a 100644 --- a/backends/graphics/surfacesdl/surfacesdl-graphics.cpp +++ b/backends/graphics/surfacesdl/surfacesdl-graphics.cpp @@ -62,6 +62,14 @@ #define SDL_FULLSCREEN 0x40000000 #endif +void destroySurface(SDL_Surface *surface) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_DestroySurface(surface); +#else + SDL_FreeSurface(surface); +#endif +} + static const OSystem::GraphicsMode s_supportedGraphicsModes[] = { {"surfacesdl", _s("SDL Surface"), GFX_SURFACESDL}, {nullptr, nullptr, 0} @@ -189,13 +197,13 @@ SurfaceSdlGraphicsManager::~SurfaceSdlGraphicsManager() { delete _scaler; delete _mouseScaler; if (_mouseOrigSurface) { - SDL_FreeSurface(_mouseOrigSurface); + destroySurface(_mouseOrigSurface); if (_mouseOrigSurface == _mouseSurface) { _mouseSurface = nullptr; } } if (_mouseSurface) { - SDL_FreeSurface(_mouseSurface); + destroySurface(_mouseOrigSurface); } free(_currentPalette); free(_overlayPalette); @@ -484,6 +492,28 @@ OSystem::TransactionError SurfaceSdlGraphicsManager::endGFXTransaction() { return (OSystem::TransactionError)errors; } +#if SDL_VERSION_ATLEAST(3, 0, 0) +Graphics::PixelFormat SurfaceSdlGraphicsManager::convertSDLPixelFormat(SDL_PixelFormat format) const { + const SDL_PixelFormatDetails *in = SDL_GetPixelFormatDetails(format); + assert(in); + if (in->bytes_per_pixel == 1 && ( + (in->Rmask == 0xff && in->Gmask == 0xff && in->Bmask == 0xff) || + (in->Rmask == 0 && in->Gmask == 0 && in->Bmask == 0) + )) + return Graphics::PixelFormat::createFormatCLUT8(); + Graphics::PixelFormat out(in->bytes_per_pixel, + in->Rbits, in->Gbits, + in->Bbits, in->Abits, + in->Rshift, in->Gshift, + in->Bshift, in->Ashift); + + // Workaround to SDL not providing an accurate Aloss value on some platforms. + if (in->Amask == 0) + out.aLoss = 8; + + return out; +} +#else Graphics::PixelFormat SurfaceSdlGraphicsManager::convertSDLPixelFormat(SDL_PixelFormat *in) const { if (in->BytesPerPixel == 1 && ( (in->Rmask == 0xff && in->Gmask == 0xff && in->Bmask == 0xff) || @@ -502,6 +532,7 @@ Graphics::PixelFormat SurfaceSdlGraphicsManager::convertSDLPixelFormat(SDL_Pixel return out; } +#endif #ifdef USE_RGB_COLOR Common::List SurfaceSdlGraphicsManager::getSupportedFormats() const { @@ -533,6 +564,20 @@ void SurfaceSdlGraphicsManager::detectSupportedFormats() { #if SDL_VERSION_ATLEAST(2, 0, 0) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_DisplayMode* pDefaultMode = SDL_GetDesktopDisplayMode(_window->getDisplayIndex()); + if (!pDefaultMode) { + error("Could not get default system display mode"); + } + + int bpp; + Uint32 rMask, gMask, bMask, aMask; + if (!SDL_GetMasksForPixelFormat(pDefaultMode->format, &bpp, &rMask, &gMask, &bMask, &aMask)) { + error("Could not convert system pixel format %s to masks", SDL_GetPixelFormatName(pDefaultMode->format)); + } + + const uint8 bytesPerPixel = SDL_BYTESPERPIXEL(pDefaultMode->format); +#else SDL_DisplayMode defaultMode; if (SDL_GetDesktopDisplayMode(_window->getDisplayIndex(), &defaultMode) != 0) { error("Could not get default system display mode"); @@ -545,6 +590,8 @@ void SurfaceSdlGraphicsManager::detectSupportedFormats() { } const uint8 bytesPerPixel = SDL_BYTESPERPIXEL(defaultMode.format); +#endif + uint8 rBits, rShift, gBits, gShift, bBits, bShift, aBits, aShift; maskToBitCount(rMask, rBits, rShift); maskToBitCount(gMask, gBits, gShift); @@ -853,7 +900,13 @@ void SurfaceSdlGraphicsManager::fixupResolutionForAspectRatio(AspectRatio desire int bestW = 0, bestH = 0; uint bestMetric = (uint)-1; // Metric is wasted space -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + int numModes; + const int display = _window->getDisplayIndex(); + SDL_DisplayMode** modes = SDL_GetFullscreenDisplayModes(display, &numModes); + for (int i = 0; i < numModes; ++i) { + SDL_DisplayMode* mode = modes[i]; +#elif SDL_VERSION_ATLEAST(2, 0, 0) const int display = _window->getDisplayIndex(); const int numModes = SDL_GetNumDisplayModes(display); SDL_DisplayMode modeData, *mode = &modeData; @@ -884,7 +937,10 @@ void SurfaceSdlGraphicsManager::fixupResolutionForAspectRatio(AspectRatio desire // Make editors a bit more happy by having the same amount of closing as // opening curley braces. -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + } + SDL_free(modes); +#elif SDL_VERSION_ATLEAST(2, 0, 0) } #else } @@ -915,7 +971,11 @@ void SurfaceSdlGraphicsManager::setupHardwareSize() { } void SurfaceSdlGraphicsManager::initGraphicsSurface() { +#if SDL_VERSION_ATLEAST(3, 0, 0) + Uint32 flags = 0; +#else Uint32 flags = SDL_SWSURFACE; +#endif if (_videoMode.fullscreen) flags |= SDL_FULLSCREEN; @@ -943,8 +1003,13 @@ bool SurfaceSdlGraphicsManager::loadGFXMode() { const Uint32 gMask = ((0xFF >> format.gLoss) << format.gShift); const Uint32 bMask = ((0xFF >> format.bLoss) << format.bShift); const Uint32 aMask = ((0xFF >> format.aLoss) << format.aShift); +#if SDL_VERSION_ATLEAST(3, 0, 0) + _screen = SDL_CreateSurface(_videoMode.screenWidth, _videoMode.screenHeight, + SDL_GetPixelFormatForMasks(_screenFormat.bytesPerPixel * 8, rMask, gMask, bMask, aMask)); +#else _screen = SDL_CreateRGBSurface(SDL_SWSURFACE, _videoMode.screenWidth, _videoMode.screenHeight, _screenFormat.bytesPerPixel * 8, rMask, gMask, bMask, aMask); +#endif if (_screen == nullptr) error("allocating _screen failed"); @@ -1013,6 +1078,19 @@ bool SurfaceSdlGraphicsManager::loadGFXMode() { // // Need some extra bytes around when using 2xSaI +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_PixelFormatDetails *pixelFormatDetails = SDL_GetPixelFormatDetails(_hwScreen->format); + if (pixelFormatDetails == nullptr) + error("getting pixel format details failed"); + _tmpscreen = SDL_CreateSurface(_videoMode.screenWidth + _maxExtraPixels * 2, + _videoMode.screenHeight + _maxExtraPixels * 2, + SDL_GetPixelFormatForMasks( + pixelFormatDetails->bits_per_pixel, + pixelFormatDetails->Rmask, + pixelFormatDetails->Gmask, + pixelFormatDetails->Bmask, + pixelFormatDetails->Amask)); +#else _tmpscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, _videoMode.screenWidth + _maxExtraPixels * 2, _videoMode.screenHeight + _maxExtraPixels * 2, _hwScreen->format->BitsPerPixel, @@ -1020,6 +1098,7 @@ bool SurfaceSdlGraphicsManager::loadGFXMode() { _hwScreen->format->Gmask, _hwScreen->format->Bmask, _hwScreen->format->Amask); +#endif if (_tmpscreen == nullptr) error("allocating _tmpscreen failed"); @@ -1030,12 +1109,22 @@ bool SurfaceSdlGraphicsManager::loadGFXMode() { _videoMode.screenWidth, _videoMode.screenHeight, _maxExtraPixels); } +#if SDL_VERSION_ATLEAST(3, 0, 0) + _overlayscreen = SDL_CreateSurface(_videoMode.overlayWidth, _videoMode.overlayHeight, + SDL_GetPixelFormatForMasks( + pixelFormatDetails->bits_per_pixel, + pixelFormatDetails->Rmask, + pixelFormatDetails->Gmask, + pixelFormatDetails->Bmask, + pixelFormatDetails->Amask)); +#else _overlayscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, _videoMode.overlayWidth, _videoMode.overlayHeight, _hwScreen->format->BitsPerPixel, _hwScreen->format->Rmask, _hwScreen->format->Gmask, _hwScreen->format->Bmask, _hwScreen->format->Amask); +#endif if (_overlayscreen == nullptr) error("allocating _overlayscreen failed"); @@ -1045,6 +1134,16 @@ bool SurfaceSdlGraphicsManager::loadGFXMode() { if (_overlayFormat.bytesPerPixel == 1 && _overlayFormat.rBits() == 0) _overlayFormat = Graphics::PixelFormat(1, 3, 3, 2, 0, 5, 2, 0, 0); +#if SDL_VERSION_ATLEAST(3, 0, 0) + _tmpscreen2 = SDL_CreateSurface(_videoMode.overlayWidth + _maxExtraPixels * 2, + _videoMode.overlayHeight + _maxExtraPixels * 2, + SDL_GetPixelFormatForMasks( + pixelFormatDetails->bits_per_pixel, + pixelFormatDetails->Rmask, + pixelFormatDetails->Gmask, + pixelFormatDetails->Bmask, + pixelFormatDetails->Amask)); +#else _tmpscreen2 = SDL_CreateRGBSurface(SDL_SWSURFACE, _videoMode.overlayWidth + _maxExtraPixels * 2, _videoMode.overlayHeight + _maxExtraPixels * 2, _hwScreen->format->BitsPerPixel, @@ -1052,6 +1151,7 @@ bool SurfaceSdlGraphicsManager::loadGFXMode() { _hwScreen->format->Gmask, _hwScreen->format->Bmask, _hwScreen->format->Amask); +#endif if (_tmpscreen2 == nullptr) error("allocating _tmpscreen2 failed"); @@ -1066,7 +1166,7 @@ bool SurfaceSdlGraphicsManager::loadGFXMode() { void SurfaceSdlGraphicsManager::unloadGFXMode() { if (_screen) { - SDL_FreeSurface(_screen); + destroySurface(_screen); _screen = nullptr; } @@ -1075,33 +1175,33 @@ void SurfaceSdlGraphicsManager::unloadGFXMode() { #endif if (_hwScreen) { - SDL_FreeSurface(_hwScreen); + destroySurface(_hwScreen); _hwScreen = nullptr; } if (_tmpscreen) { - SDL_FreeSurface(_tmpscreen); + destroySurface(_tmpscreen); _tmpscreen = nullptr; } if (_tmpscreen2) { - SDL_FreeSurface(_tmpscreen2); + destroySurface(_tmpscreen2); _tmpscreen2 = nullptr; } if (_overlayscreen) { - SDL_FreeSurface(_overlayscreen); + destroySurface(_overlayscreen); _overlayscreen = nullptr; } #ifdef USE_OSD if (_osdMessageSurface) { - SDL_FreeSurface(_osdMessageSurface); + destroySurface(_osdMessageSurface); _osdMessageSurface = nullptr; } if (_osdIconSurface) { - SDL_FreeSurface(_osdIconSurface); + destroySurface(_osdIconSurface); _osdIconSurface = nullptr; } #endif @@ -1128,15 +1228,15 @@ bool SurfaceSdlGraphicsManager::hotswapGFXMode() { // Release the HW screen surface if (_hwScreen) { - SDL_FreeSurface(_hwScreen); + destroySurface(_osdIconSurface); _hwScreen = nullptr; } if (_tmpscreen) { - SDL_FreeSurface(_tmpscreen); + destroySurface(_tmpscreen); _tmpscreen = nullptr; } if (_tmpscreen2) { - SDL_FreeSurface(_tmpscreen2); + destroySurface(_tmpscreen2); _tmpscreen2 = nullptr; } @@ -1158,8 +1258,8 @@ bool SurfaceSdlGraphicsManager::hotswapGFXMode() { SDL_BlitSurface(old_overlayscreen, nullptr, _overlayscreen, nullptr); // Free the old surfaces - SDL_FreeSurface(old_screen); - SDL_FreeSurface(old_overlayscreen); + destroySurface(old_screen); + destroySurface(old_overlayscreen); // Update cursor to new scale blitCursor(); @@ -1318,7 +1418,7 @@ void SurfaceSdlGraphicsManager::internUpdateScreen() { if (_isDoubleBuf && _numDirtyRects) _forceRedraw = true; -#if defined(USE_IMGUI) && defined(USE_IMGUI_SDLRENDERER2) +#if defined(USE_IMGUI) && (defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3)) if (_imGuiCallbacks.render) { _forceRedraw = true; } @@ -1367,7 +1467,14 @@ void SurfaceSdlGraphicsManager::internUpdateScreen() { SDL_LockSurface(srcSurf); SDL_LockSurface(_hwScreen); +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_PixelFormatDetails *pixelFormatDetails = SDL_GetPixelFormatDetails(_hwScreen->format); + if (!pixelFormatDetails) + error("SDL_GetPixelFormatDetails failed: %s", SDL_GetError()); + bpp = pixelFormatDetails->bytes_per_pixel; +#else bpp = _hwScreen->format->BytesPerPixel; +#endif srcPitch = srcSurf->pitch; dstPitch = _hwScreen->pitch; @@ -1476,11 +1583,19 @@ void SurfaceSdlGraphicsManager::internUpdateScreen() { SDL_LockSurface(_hwScreen); // Use white as color for now. +#if SDL_VERSION_ATLEAST(3, 0, 0) + Uint32 rectColor = SDL_MapSurfaceRGB(_hwScreen, 0xFF, 0xFF, 0xFF); +#else Uint32 rectColor = SDL_MapRGB(_hwScreen->format, 0xFF, 0xFF, 0xFF); +#endif // First draw the top and bottom lines // then draw the left and right lines +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (pixelFormatDetails->bytes_per_pixel == 2) { +#else if (_hwScreen->format->BytesPerPixel == 2) { +#endif uint16 *top = (uint16 *)((byte *)_hwScreen->pixels + y * _hwScreen->pitch + x * 2); uint16 *bottom = (uint16 *)((byte *)_hwScreen->pixels + (y + h) * _hwScreen->pitch + x * 2); byte *left = ((byte *)_hwScreen->pixels + y * _hwScreen->pitch + x * 2); @@ -1498,7 +1613,11 @@ void SurfaceSdlGraphicsManager::internUpdateScreen() { left += _hwScreen->pitch; right += _hwScreen->pitch; } +#if SDL_VERSION_ATLEAST(3, 0, 0) + } else if (pixelFormatDetails->bytes_per_pixel == 4) { +#else } else if (_hwScreen->format->BytesPerPixel == 4) { +#endif uint32 *top = (uint32 *)((byte *)_hwScreen->pixels + y * _hwScreen->pitch + x * 4); uint32 *bottom = (uint32 *)((byte *)_hwScreen->pixels + (y + h) * _hwScreen->pitch + x * 4); byte *left = ((byte *)_hwScreen->pixels + y * _hwScreen->pitch + x * 4); @@ -1541,7 +1660,7 @@ void SurfaceSdlGraphicsManager::internUpdateScreen() { #if SDL_VERSION_ATLEAST(2, 0, 0) -#if defined(USE_IMGUI) && defined(USE_IMGUI_SDLRENDERER2) +#if defined(USE_IMGUI) && (defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3)) renderImGui(); #endif @@ -1576,7 +1695,11 @@ bool SurfaceSdlGraphicsManager::saveScreenshot(const Common::Path &filename) con bool success; +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Palette *sdlPalette = SDL_CreateSurfacePalette(_hwScreen); +#else SDL_Palette *sdlPalette = _hwScreen->format->palette; +#endif if (sdlPalette) { byte palette[256 * 3]; for (int i = 0; i < sdlPalette->ncolors; i++) { @@ -1678,7 +1801,11 @@ void SurfaceSdlGraphicsManager::copyRectToScreen(const void *buf, int pitch, int addDirtyRect(x, y, w, h, false); // Try to lock the screen surface +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (!SDL_LockSurface(_screen)) +#else if (SDL_LockSurface(_screen) == -1) +#endif error("SDL_LockSurface failed: %s", SDL_GetError()); byte *dst = (byte *)_screen->pixels + y * _screen->pitch + x * _screenFormat.bytesPerPixel; @@ -1708,7 +1835,11 @@ Graphics::Surface *SurfaceSdlGraphicsManager::lockScreen() { _screenIsLocked = true; // Try to lock the screen surface +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (!SDL_LockSurface(_screen)) +#else if (SDL_LockSurface(_screen) == -1) +#endif error("SDL_LockSurface failed: %s", SDL_GetError()); _framebuffer.init(_screen->w, _screen->h, _screen->pitch, _screen->pixels, _screenFormat); @@ -1944,12 +2075,22 @@ void SurfaceSdlGraphicsManager::clearOverlay() { if (SDL_BlitSurface(_screen, &src, _tmpscreen, &dst) != 0) error("SDL_BlitSurface failed: %s", SDL_GetError()); +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_PixelFormatDetails *pixelFormatDetails = SDL_GetPixelFormatDetails(_tmpscreen->format); + if (!pixelFormatDetails) + error("SDL_GetPixelFormatDetails failed: %s", SDL_GetError()); +#endif + SDL_LockSurface(_tmpscreen); SDL_LockSurface(_overlayscreen); // Transpose from game palette to RGB332 (overlay palette) if (_isHwPalette) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + byte *p = (byte *)(_tmpscreen->pixels) + _maxExtraPixels * _tmpscreen->pitch + _maxExtraPixels * pixelFormatDetails->bytes_per_pixel; +#else byte *p = (byte *)(_tmpscreen->pixels) + _maxExtraPixels * _tmpscreen->pitch + _maxExtraPixels * _tmpscreen->format->BytesPerPixel; +#endif int pitchSkip = _tmpscreen->pitch - _videoMode.screenWidth; for (int y = 0; y < _videoMode.screenHeight; y++) { for (int x = 0; x < _videoMode.screenWidth; x++, p++) { @@ -1960,7 +2101,11 @@ void SurfaceSdlGraphicsManager::clearOverlay() { } } +#if SDL_VERSION_ATLEAST(3, 0, 0) + _scaler->scale((byte *)(_tmpscreen->pixels) + _maxExtraPixels * _tmpscreen->pitch + _maxExtraPixels * pixelFormatDetails->bytes_per_pixel, _tmpscreen->pitch, +#else _scaler->scale((byte *)(_tmpscreen->pixels) + _maxExtraPixels * _tmpscreen->pitch + _maxExtraPixels * _tmpscreen->format->BytesPerPixel, _tmpscreen->pitch, +#endif (byte *)_overlayscreen->pixels, _overlayscreen->pitch, _videoMode.screenWidth, _videoMode.screenHeight, 0, 0); #ifdef USE_ASPECT @@ -1981,7 +2126,11 @@ void SurfaceSdlGraphicsManager::grabOverlay(Graphics::Surface &surface) const { if (_overlayscreen == nullptr) return; +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (!SDL_LockSurface(_overlayscreen)) +#else if (SDL_LockSurface(_overlayscreen) == -1) +#endif error("SDL_LockSurface failed: %s", SDL_GetError()); assert(surface.w >= _videoMode.overlayWidth); @@ -2003,7 +2152,14 @@ void SurfaceSdlGraphicsManager::copyRectToOverlay(const void *buf, int pitch, in return; const byte *src = (const byte *)buf; +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_PixelFormatDetails *pixelFormatDetails = SDL_GetPixelFormatDetails(_overlayscreen->format); + if (!pixelFormatDetails) + error("SDL_GetPixelFormatDetails failed: %s", SDL_GetError()); + uint bpp = pixelFormatDetails->bytes_per_pixel; +#else uint bpp = _overlayscreen->format->BytesPerPixel; +#endif // Clip the coordinates if (x < 0) { @@ -2032,7 +2188,11 @@ void SurfaceSdlGraphicsManager::copyRectToOverlay(const void *buf, int pitch, in // Mark the modified region as dirty addDirtyRect(x, y, w, h, true); +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (!SDL_LockSurface(_overlayscreen)) +#else if (SDL_LockSurface(_overlayscreen) == -1) +#endif error("SDL_LockSurface failed: %s", SDL_GetError()); byte *dst = (byte *)_overlayscreen->pixels + y * _overlayscreen->pitch + x * bpp; @@ -2185,7 +2345,11 @@ void SurfaceSdlGraphicsManager::setMouseCursor(const void *buf, uint w, uint h, _mouseCurState.h = h; if (_mouseOrigSurface) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_DestroySurface(_mouseOrigSurface); +#else SDL_FreeSurface(_mouseOrigSurface); +#endif if (_mouseSurface == _mouseOrigSurface) { _mouseSurface = nullptr; @@ -2195,7 +2359,11 @@ void SurfaceSdlGraphicsManager::setMouseCursor(const void *buf, uint w, uint h, } if (formatChanged && _mouseSurface) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_DestroySurface(_mouseSurface); +#else SDL_FreeSurface(_mouseSurface); +#endif _mouseSurface = nullptr; } @@ -2206,6 +2374,17 @@ void SurfaceSdlGraphicsManager::setMouseCursor(const void *buf, uint w, uint h, assert(!_mouseOrigSurface); // Allocate bigger surface because scalers will read past the boudaries. +#if SDL_VERSION_ATLEAST(3, 0, 0) + _mouseOrigSurface = SDL_CreateSurface( + _mouseCurState.w + _maxExtraPixels * 2, + _mouseCurState.h + _maxExtraPixels * 2, + SDL_GetPixelFormatForMasks( + _cursorFormat.bytesPerPixel * 8, + ((0xFF >> _cursorFormat.rLoss) << _cursorFormat.rShift), + ((0xFF >> _cursorFormat.gLoss) << _cursorFormat.gShift), + ((0xFF >> _cursorFormat.bLoss) << _cursorFormat.bShift), + ((0xFF >> _cursorFormat.aLoss) << _cursorFormat.aShift))); +#else _mouseOrigSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, _mouseCurState.w + _maxExtraPixels * 2, _mouseCurState.h + _maxExtraPixels * 2, @@ -2214,6 +2393,7 @@ void SurfaceSdlGraphicsManager::setMouseCursor(const void *buf, uint w, uint h, ((0xFF >> _cursorFormat.gLoss) << _cursorFormat.gShift), ((0xFF >> _cursorFormat.bLoss) << _cursorFormat.bShift), ((0xFF >> _cursorFormat.aLoss) << _cursorFormat.aShift)); +#endif if (_mouseOrigSurface == nullptr) { error("Allocating _mouseOrigSurface failed"); @@ -2234,8 +2414,14 @@ void SurfaceSdlGraphicsManager::setMouseCursor(const void *buf, uint w, uint h, } if (keycolorChanged) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + uint32 flags = _disableMouseKeyColor ? 0 : SDL_SRCCOLORKEY | SDL_SRCALPHA; + SDL_SetSurfaceColorKey(_mouseOrigSurface, flags, _mouseKeyColor); + SDL_SetSurfaceRLE(_mouseOrigSurface, !_disableMouseKeyColor); +#else uint32 flags = _disableMouseKeyColor ? 0 : SDL_RLEACCEL | SDL_SRCCOLORKEY | SDL_SRCALPHA; SDL_SetColorKey(_mouseOrigSurface, flags, _mouseKeyColor); +#endif } SDL_LockSurface(_mouseOrigSurface); @@ -2253,9 +2439,13 @@ void SurfaceSdlGraphicsManager::setMouseCursor(const void *buf, uint w, uint h, } // Draw from [_maxExtraPixels,_maxExtraPixels] since scalers will read past boudaries +#if SDL_VERSION_ATLEAST(3, 0, 0) + Graphics::copyBlit((byte *)_mouseOrigSurface->pixels + _mouseOrigSurface->pitch * _maxExtraPixels + _maxExtraPixels * _cursorFormat.bytesPerPixel, + (const byte *)buf, _mouseOrigSurface->pitch, w * _cursorFormat.bytesPerPixel, w, h, _cursorFormat.bytesPerPixel); +#else Graphics::copyBlit((byte *)_mouseOrigSurface->pixels + _mouseOrigSurface->pitch * _maxExtraPixels + _maxExtraPixels * _mouseOrigSurface->format->BytesPerPixel, (const byte *)buf, _mouseOrigSurface->pitch, w * _cursorFormat.bytesPerPixel, w, h, _cursorFormat.bytesPerPixel); - +#endif SDL_UnlockSurface(_mouseOrigSurface); blitCursor(); @@ -2316,8 +2506,26 @@ void SurfaceSdlGraphicsManager::blitCursor() { if (sizeChanged || !_mouseSurface) { if (_mouseSurface) +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_DestroySurface(_mouseSurface); +#else SDL_FreeSurface(_mouseSurface); +#endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_PixelFormatDetails *pixelFormatDetails = SDL_GetPixelFormatDetails(_mouseOrigSurface->format); + if (pixelFormatDetails == nullptr) + error("getting pixel format details failed"); + _mouseSurface = SDL_CreateSurface( + _mouseCurState.rW, + _mouseCurState.rH, + SDL_GetPixelFormatForMasks( + pixelFormatDetails->bits_per_pixel, + pixelFormatDetails->Rmask, + pixelFormatDetails->Gmask, + pixelFormatDetails->Bmask, + pixelFormatDetails->Amask)); +#else _mouseSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, _mouseCurState.rW, _mouseCurState.rH, @@ -2326,14 +2534,21 @@ void SurfaceSdlGraphicsManager::blitCursor() { _mouseOrigSurface->format->Gmask, _mouseOrigSurface->format->Bmask, _mouseOrigSurface->format->Amask); +#endif if (_mouseSurface == nullptr) error("Allocating _mouseSurface failed"); } SDL_SetColors(_mouseSurface, _cursorPaletteDisabled ? _currentPalette : _cursorPalette, 0, 256); +#if SDL_VERSION_ATLEAST(3, 0, 0) + uint32 flags = _disableMouseKeyColor ? 0 : SDL_SRCCOLORKEY | SDL_SRCALPHA; + SDL_SetSurfaceColorKey(_mouseSurface, flags, _mouseKeyColor); + SDL_SetSurfaceRLE(_mouseSurface, !_disableMouseKeyColor); +#else uint32 flags = _disableMouseKeyColor ? 0 : SDL_RLEACCEL | SDL_SRCCOLORKEY | SDL_SRCALPHA; SDL_SetColorKey(_mouseSurface, flags, _mouseKeyColor); +#endif SDL_LockSurface(_mouseOrigSurface); SDL_LockSurface(_mouseSurface); @@ -2347,23 +2562,55 @@ void SurfaceSdlGraphicsManager::blitCursor() { // fall back on the Normal scaler when a smaller cursor is supplied. if (_mouseScaler && _scalerPlugin->canDrawCursor() && (uint)_mouseCurState.h >= _extraPixels) { _mouseScaler->setFactor(_videoMode.scaleFactor); +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_PixelFormatDetails *pixelFormatDetails = SDL_GetPixelFormatDetails(_mouseOrigSurface->format); + if (pixelFormatDetails == nullptr) + error("getting pixel format details failed"); + _mouseScaler->scale( + (byte *)_mouseOrigSurface->pixels + _mouseOrigSurface->pitch * _maxExtraPixels + _maxExtraPixels * pixelFormatDetails->bytes_per_pixel, + _mouseOrigSurface->pitch, (byte *)_mouseSurface->pixels, _mouseSurface->pitch, + _mouseCurState.w, _mouseCurState.h, 0, 0); +#else _mouseScaler->scale( (byte *)_mouseOrigSurface->pixels + _mouseOrigSurface->pitch * _maxExtraPixels + _maxExtraPixels * _mouseOrigSurface->format->BytesPerPixel, _mouseOrigSurface->pitch, (byte *)_mouseSurface->pixels, _mouseSurface->pitch, _mouseCurState.w, _mouseCurState.h, 0, 0); +#endif } else #endif { +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_PixelFormatDetails *pixelFormatDetails = SDL_GetPixelFormatDetails(_mouseOrigSurface->format); + if (pixelFormatDetails == nullptr) + error("getting pixel format details failed"); + Graphics::scaleBlit((byte *)_mouseSurface->pixels, (const byte *)_mouseOrigSurface->pixels + _mouseOrigSurface->pitch * _maxExtraPixels + _maxExtraPixels * pixelFormatDetails->bytes_per_pixel, + _mouseSurface->pitch, _mouseOrigSurface->pitch, + _mouseCurState.w * _videoMode.scaleFactor, _mouseCurState.h * _videoMode.scaleFactor, + _mouseCurState.w, _mouseCurState.h, convertSDLPixelFormat(_mouseSurface->format)); +#else Graphics::scaleBlit((byte *)_mouseSurface->pixels, (const byte *)_mouseOrigSurface->pixels + _mouseOrigSurface->pitch * _maxExtraPixels + _maxExtraPixels * _mouseOrigSurface->format->BytesPerPixel, _mouseSurface->pitch, _mouseOrigSurface->pitch, _mouseCurState.w * _videoMode.scaleFactor, _mouseCurState.h * _videoMode.scaleFactor, _mouseCurState.w, _mouseCurState.h, convertSDLPixelFormat(_mouseSurface->format)); +#endif } } else { +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_PixelFormatDetails *srcPixelFormatDetails = SDL_GetPixelFormatDetails(_mouseOrigSurface->format); + if (srcPixelFormatDetails == nullptr) + error("getting pixel format details failed"); + const SDL_PixelFormatDetails *dstPixelFormatDetails = SDL_GetPixelFormatDetails(_mouseSurface->format); + if (dstPixelFormatDetails == nullptr) + error("getting pixel format details failed"); + Graphics::copyBlit((byte *)_mouseSurface->pixels, (const byte *)_mouseOrigSurface->pixels + _mouseOrigSurface->pitch * _maxExtraPixels + _maxExtraPixels * srcPixelFormatDetails->bytes_per_pixel, + _mouseSurface->pitch, _mouseOrigSurface->pitch, + _mouseCurState.w, _mouseCurState.h, dstPixelFormatDetails->bytes_per_pixel); +#else Graphics::copyBlit((byte *)_mouseSurface->pixels, (const byte *)_mouseOrigSurface->pixels + _mouseOrigSurface->pitch * _maxExtraPixels + _maxExtraPixels * _mouseOrigSurface->format->BytesPerPixel, _mouseSurface->pitch, _mouseOrigSurface->pitch, _mouseCurState.w, _mouseCurState.h, _mouseSurface->format->BytesPerPixel); +#endif } #ifdef USE_ASPECT @@ -2497,10 +2744,19 @@ void SurfaceSdlGraphicsManager::displayMessageOnOSD(const Common::U32String &msg if (height > _hwScreen->h) height = _hwScreen->h; +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_PixelFormatDetails *pixelFormatDetails = SDL_GetPixelFormatDetails(_hwScreen->format); + if (pixelFormatDetails == nullptr) + error("getting pixel format details failed"); + _osdMessageSurface = SDL_CreateSurface( + width, height, + SDL_GetPixelFormatForMasks(pixelFormatDetails->bits_per_pixel, pixelFormatDetails->Rmask, pixelFormatDetails->Gmask, pixelFormatDetails->Bmask, pixelFormatDetails->Amask)); +#else _osdMessageSurface = SDL_CreateRGBSurface( SDL_SWSURFACE, width, height, _hwScreen->format->BitsPerPixel, _hwScreen->format->Rmask, _hwScreen->format->Gmask, _hwScreen->format->Bmask, _hwScreen->format->Amask ); +#endif // Lock the surface if (SDL_LockSurface(_osdMessageSurface)) @@ -2508,7 +2764,11 @@ void SurfaceSdlGraphicsManager::displayMessageOnOSD(const Common::U32String &msg // Draw a dark gray rect // TODO: Rounded corners ? Border? +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_FillSurfaceRect(_osdMessageSurface, nullptr, SDL_MapSurfaceRGB(_osdMessageSurface, 64, 64, 64)); +#else SDL_FillRect(_osdMessageSurface, nullptr, SDL_MapRGB(_osdMessageSurface->format, 64, 64, 64)); +#endif Graphics::Surface dst; dst.init(_osdMessageSurface->w, _osdMessageSurface->h, _osdMessageSurface->pitch, _osdMessageSurface->pixels, @@ -2518,7 +2778,11 @@ void SurfaceSdlGraphicsManager::displayMessageOnOSD(const Common::U32String &msg for (i = 0; i < lines.size(); i++) { font->drawString(&dst, lines[i], 0, 0 + i * lineHeight + vOffset + lineSpacing, width, +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_MapSurfaceRGB(_osdMessageSurface, 255, 255, 255), +#else SDL_MapRGB(_osdMessageSurface->format, 255, 255, 255), +#endif Graphics::kTextAlignCenter, 0, true); } @@ -2529,7 +2793,12 @@ void SurfaceSdlGraphicsManager::displayMessageOnOSD(const Common::U32String &msg _osdMessageAlpha = SDL_ALPHA_TRANSPARENT + kOSDInitialAlpha * (SDL_ALPHA_OPAQUE - SDL_ALPHA_TRANSPARENT) / 100; _osdMessageFadeStartTime = SDL_GetTicks() + kOSDFadeOutDelay; // Enable alpha blending +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_SetAlpha(_osdMessageSurface, SDL_SRCALPHA, _osdMessageAlpha); + SDL_SetSurfaceRLE(_osdMessageSurface, true); +#else SDL_SetAlpha(_osdMessageSurface, SDL_RLEACCEL | SDL_SRCALPHA, _osdMessageAlpha); +#endif #if defined(MACOSX) macOSTouchbarUpdate(msg.encode().c_str()); @@ -2564,13 +2833,28 @@ void SurfaceSdlGraphicsManager::displayActivityIconOnOSD(const Graphics::Surface } if (_osdIconSurface) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_DestroySurface(_osdIconSurface); +#else SDL_FreeSurface(_osdIconSurface); +#endif _osdIconSurface = nullptr; } if (icon) { const Graphics::PixelFormat &iconFormat = icon->format; +#if SDL_VERSION_ATLEAST(3, 0, 0) + _osdIconSurface = SDL_CreateSurface( + icon->w, icon->h, + SDL_GetPixelFormatForMasks( + iconFormat.bytesPerPixel * 8, + ((0xFF >> iconFormat.rLoss) << iconFormat.rShift), + ((0xFF >> iconFormat.gLoss) << iconFormat.gShift), + ((0xFF >> iconFormat.bLoss) << iconFormat.bShift), + ((0xFF >> iconFormat.aLoss) << iconFormat.aShift)) + ); +#else _osdIconSurface = SDL_CreateRGBSurface( SDL_SWSURFACE, icon->w, icon->h, iconFormat.bytesPerPixel * 8, @@ -2579,6 +2863,7 @@ void SurfaceSdlGraphicsManager::displayActivityIconOnOSD(const Graphics::Surface ((0xFF >> iconFormat.bLoss) << iconFormat.bShift), ((0xFF >> iconFormat.aLoss) << iconFormat.aShift) ); +#endif // Lock the surface if (SDL_LockSurface(_osdIconSurface)) @@ -2609,7 +2894,11 @@ SDL_Rect SurfaceSdlGraphicsManager::getOSDIconRect() const { void SurfaceSdlGraphicsManager::removeOSDMessage() { // Remove the previous message if (_osdMessageSurface) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_DestroySurface(_osdMessageSurface); +#else SDL_FreeSurface(_osdMessageSurface); +#endif _forceRedraw = true; } @@ -2635,7 +2924,12 @@ void SurfaceSdlGraphicsManager::updateOSD() { const int startAlpha = SDL_ALPHA_TRANSPARENT + kOSDInitialAlpha * (SDL_ALPHA_OPAQUE - SDL_ALPHA_TRANSPARENT) / 100; _osdMessageAlpha = startAlpha + diff * (SDL_ALPHA_TRANSPARENT - startAlpha) / kOSDFadeOutDuration; } +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_SetAlpha(_osdMessageSurface, SDL_SRCALPHA, _osdMessageAlpha); + SDL_SetSurfaceRLE(_osdMessageSurface, true); +#else SDL_SetAlpha(_osdMessageSurface, SDL_RLEACCEL | SDL_SRCALPHA, _osdMessageAlpha); +#endif } if (_osdMessageAlpha == SDL_ALPHA_TRANSPARENT) { @@ -2823,7 +3117,7 @@ void SurfaceSdlGraphicsManager::notifyResize(const int width, const int height) #if SDL_VERSION_ATLEAST(2, 0, 0) void SurfaceSdlGraphicsManager::deinitializeRenderer() { -#if defined(USE_IMGUI) && defined(USE_IMGUI_SDLRENDERER2) +#if defined(USE_IMGUI) && (defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3)) destroyImGui(); #endif @@ -2840,12 +3134,18 @@ void SurfaceSdlGraphicsManager::recreateScreenTexture() { if (!_renderer) return; +#if !SDL_VERSION_ATLEAST(3, 0, 0) SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, _videoMode.filtering ? "linear" : "nearest"); +#endif SDL_Texture *oldTexture = _screenTexture; _screenTexture = SDL_CreateTexture(_renderer, SDL_PIXELFORMAT_RGB565, SDL_TEXTUREACCESS_STREAMING, _videoMode.hardwareWidth, _videoMode.hardwareHeight); - if (_screenTexture) + if (_screenTexture) { SDL_DestroyTexture(oldTexture); +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_SetTextureScaleMode(_screenTexture, _videoMode.filtering ? SDL_SCALEMODE_LINEAR : SDL_SCALEMODE_NEAREST); +#endif + } else _screenTexture = oldTexture; } @@ -2854,15 +3154,27 @@ SDL_Surface *SurfaceSdlGraphicsManager::SDL_SetVideoMode(int width, int height, deinitializeRenderer(); uint32 createWindowFlags = SDL_WINDOW_RESIZABLE; - uint32 rendererFlags = 0; if ((flags & SDL_FULLSCREEN) != 0) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + createWindowFlags |= SDL_WINDOW_FULLSCREEN; +#else createWindowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; +#endif } if (!createOrUpdateWindow(width, height, createWindowFlags)) { return nullptr; } +#if SDL_VERSION_ATLEAST(3, 0, 0) + if ((flags & SDL_FULLSCREEN) != 0) { + if (!SDL_SetWindowFullscreenMode(_window->getSDLWindow(), NULL)) + warning("SDL_SetWindowFullscreenMode failed (%s)", SDL_GetError()); + if(!SDL_SyncWindow(_window->getSDLWindow())) + warning("SDL_SyncWindow failed (%s)", SDL_GetError()); + } +#endif + #if defined(MACOSX) && SDL_VERSION_ATLEAST(2, 0, 10) // WORKAROUND: Bug #11430: "macOS: blurry content on Retina displays" // Since SDL 2.0.10, Metal takes priority over OpenGL rendering on macOS, @@ -2871,18 +3183,34 @@ SDL_Surface *SurfaceSdlGraphicsManager::SDL_SetVideoMode(int width, int height, SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl"); #endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_PropertiesID props = SDL_CreateProperties(); + SDL_SetPointerProperty(props, SDL_PROP_RENDERER_CREATE_WINDOW_POINTER, _window->getSDLWindow()); + SDL_SetNumberProperty(props, SDL_PROP_RENDERER_CREATE_PRESENT_VSYNC_NUMBER, _videoMode.vsync ? 1 : 0); + _renderer = SDL_CreateRendererWithProperties(props); + SDL_DestroyProperties(props); +#else + uint32 rendererFlags = 0; if (_videoMode.vsync) { rendererFlags |= SDL_RENDERER_PRESENTVSYNC; } - _renderer = SDL_CreateRenderer(_window->getSDLWindow(), -1, rendererFlags); +#endif if (!_renderer) { if (_videoMode.vsync) { // VSYNC might not be available, so retry without VSYNC warning("SDL_SetVideoMode: SDL_CreateRenderer() failed with VSYNC option, retrying without it..."); _videoMode.vsync = false; +#if SDL_VERSION_ATLEAST(3, 0, 0) + props = SDL_CreateProperties(); + SDL_SetPointerProperty(props, SDL_PROP_RENDERER_CREATE_WINDOW_POINTER, _window->getSDLWindow()); + SDL_SetNumberProperty(props, SDL_PROP_RENDERER_CREATE_PRESENT_VSYNC_NUMBER, 0); + _renderer = SDL_CreateRendererWithProperties(props); + SDL_DestroyProperties(props); +#else rendererFlags &= ~SDL_RENDERER_PRESENTVSYNC; _renderer = SDL_CreateRenderer(_window->getSDLWindow(), -1, rendererFlags); +#endif } if (!_renderer) { deinitializeRenderer(); @@ -2893,23 +3221,36 @@ SDL_Surface *SurfaceSdlGraphicsManager::SDL_SetVideoMode(int width, int height, getWindowSizeFromSdl(&_windowWidth, &_windowHeight); handleResize(_windowWidth, _windowHeight); +#if !SDL_VERSION_ATLEAST(3, 0, 0) SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, _videoMode.filtering ? "linear" : "nearest"); +#endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_PixelFormat format = SDL_PIXELFORMAT_RGB565; +#else Uint32 format = SDL_PIXELFORMAT_RGB565; +#endif _screenTexture = SDL_CreateTexture(_renderer, format, SDL_TEXTUREACCESS_STREAMING, width, height); if (!_screenTexture) { deinitializeRenderer(); return nullptr; } +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_SetTextureScaleMode(_screenTexture, _videoMode.filtering ? SDL_SCALEMODE_LINEAR : SDL_SCALEMODE_NEAREST); +#endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Surface *screen = SDL_CreateSurface(width, height, format); +#else SDL_Surface *screen = SDL_CreateRGBSurfaceWithFormat(0, width, height, SDL_BITSPERPIXEL(format), format); +#endif if (!screen) { deinitializeRenderer(); return nullptr; } -#if defined(USE_IMGUI) && defined(USE_IMGUI_SDLRENDERER2) +#if defined(USE_IMGUI) && (defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3)) // Setup Dear ImGui initImGui(_renderer, nullptr); #endif @@ -2940,18 +3281,38 @@ void SurfaceSdlGraphicsManager::SDL_UpdateRects(SDL_Surface *screen, int numrect SDL_RenderClear(_renderer); - if (rotangle != 0) + if (rotangle != 0) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_FRect fViewport; + SDL_RectToFRect(&viewport, &fViewport); + SDL_RenderTextureRotated(_renderer, _screenTexture, nullptr, &fViewport, rotangle, nullptr, SDL_FLIP_NONE); +#else SDL_RenderCopyEx(_renderer, _screenTexture, nullptr, &viewport, rotangle, nullptr, SDL_FLIP_NONE); - else +#endif + } + else { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_FRect fViewport; + SDL_RectToFRect(&viewport, &fViewport); + SDL_RenderTexture(_renderer, _screenTexture, nullptr, &fViewport); +#else SDL_RenderCopy(_renderer, _screenTexture, nullptr, &viewport); +#endif + } } int SurfaceSdlGraphicsManager::SDL_SetColors(SDL_Surface *surface, SDL_Color *colors, int firstcolor, int ncolors) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Palette *palette = SDL_CreateSurfacePalette(surface); + if (palette) { + return !SDL_SetPaletteColors(palette, colors, firstcolor, ncolors) ? 1 : 0; + } +#else if (surface->format->palette) { return !SDL_SetPaletteColors(surface->format->palette, colors, firstcolor, ncolors) ? 1 : 0; - } else { - return 0; } +#endif + return 0; } int SurfaceSdlGraphicsManager::SDL_SetAlpha(SDL_Surface *surface, Uint32 flag, Uint8 alpha) { @@ -2973,10 +3334,14 @@ int SurfaceSdlGraphicsManager::SDL_SetAlpha(SDL_Surface *surface, Uint32 flag, U } int SurfaceSdlGraphicsManager::SDL_SetColorKey(SDL_Surface *surface, Uint32 flag, Uint32 key) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + return SDL_SetSurfaceColorKey(surface, flag, key) ? -1 : 0; +#else return ::SDL_SetColorKey(surface, flag ? SDL_TRUE : SDL_FALSE, key) ? -1 : 0; +#endif } -#if defined(USE_IMGUI) && defined(USE_IMGUI_SDLRENDERER2) +#if defined(USE_IMGUI) && (defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3)) void *SurfaceSdlGraphicsManager::getImGuiTexture(const Graphics::Surface &image, const byte *palette, int palCount) { // Upload pixels into texture @@ -2989,7 +3354,11 @@ void *SurfaceSdlGraphicsManager::getImGuiTexture(const Graphics::Surface &image, Graphics::Surface *s = image.convertTo(Graphics::PixelFormat(4, 8, 8, 8, 8, 0, 8, 16, 24), palette, palCount); SDL_UpdateTexture(texture, nullptr, s->getPixels(), s->pitch); SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); +#ifdef USE_IMGUI_SDLRENDERER3 + SDL_SetTextureScaleMode(texture, SDL_SCALEMODE_LINEAR); +#elif defined(USE_IMGUI_SDLRENDERER2) SDL_SetTextureScaleMode(texture, SDL_ScaleModeLinear); +#endif s->free(); delete s; @@ -3000,7 +3369,7 @@ void *SurfaceSdlGraphicsManager::getImGuiTexture(const Graphics::Surface &image, void SurfaceSdlGraphicsManager::freeImGuiTexture(void *texture) { SDL_DestroyTexture((SDL_Texture *) texture); } -#endif // defined(USE_IMGUI) && defined(USE_IMGUI_SDLRENDERER2) +#endif // defined(USE_IMGUI) && (defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3)) #endif // SDL_VERSION_ATLEAST(2, 0, 0) diff --git a/backends/graphics/surfacesdl/surfacesdl-graphics.h b/backends/graphics/surfacesdl/surfacesdl-graphics.h index 87abc4f76030..ce716bd5e192 100644 --- a/backends/graphics/surfacesdl/surfacesdl-graphics.h +++ b/backends/graphics/surfacesdl/surfacesdl-graphics.h @@ -95,7 +95,11 @@ class SurfaceSdlGraphicsManager : public SdlGraphicsManager { * @param in The SDL pixel format to convert * @param out A pixel format to be written to */ +#if SDL_VERSION_ATLEAST(3, 0, 0) + Graphics::PixelFormat convertSDLPixelFormat(SDL_PixelFormat in) const; +#else Graphics::PixelFormat convertSDLPixelFormat(SDL_PixelFormat *in) const; +#endif public: void copyRectToScreen(const void *buf, int pitch, int x, int y, int w, int h) override; Graphics::Surface *lockScreen() override; @@ -129,7 +133,7 @@ class SurfaceSdlGraphicsManager : public SdlGraphicsManager { void notifyVideoExpose() override; void notifyResize(const int width, const int height) override; -#if defined(USE_IMGUI) && defined(USE_IMGUI_SDLRENDERER2) +#if defined(USE_IMGUI) && (defined(USE_IMGUI_SDLRENDERER2) || defined(USE_IMGUI_SDLRENDERER3)) void *getImGuiTexture(const Graphics::Surface &image, const byte *palette, int palCount) override; void freeImGuiTexture(void *texture) override; #endif diff --git a/backends/graphics3d/openglsdl/openglsdl-graphics3d.cpp b/backends/graphics3d/openglsdl/openglsdl-graphics3d.cpp index f530d599be1f..9f811452ba76 100644 --- a/backends/graphics3d/openglsdl/openglsdl-graphics3d.cpp +++ b/backends/graphics3d/openglsdl/openglsdl-graphics3d.cpp @@ -385,7 +385,10 @@ void OpenGLSdlGraphics3dManager::createOrUpdateScreen() { g_system->quit(); } -#if SDL_VERSION_ATLEAST(2, 0, 1) +#if SDL_VERSION_ATLEAST(3, 0, 0) + int obtainedWidth = 0, obtainedHeight = 0; + SDL_GetWindowSizeInPixels(_window->getSDLWindow(), &obtainedWidth, &obtainedHeight); +#elif SDL_VERSION_ATLEAST(2, 0, 1) int obtainedWidth = 0, obtainedHeight = 0; SDL_GL_GetDrawableSize(_window->getSDLWindow(), &obtainedWidth, &obtainedHeight); #else @@ -410,8 +413,13 @@ void OpenGLSdlGraphics3dManager::notifyResize(const int width, const int height) #if SDL_VERSION_ATLEAST(2, 0, 0) // Get the updated size directly from SDL, in case there are multiple // resize events in the message queue. +#if SDL_VERSION_ATLEAST(3, 0, 0) + int newWidth = 0, newHeight = 0; + SDL_GetWindowSizeInPixels(_window->getSDLWindow(), &newWidth, &newHeight); +#else int newWidth = 0, newHeight = 0; SDL_GL_GetDrawableSize(_window->getSDLWindow(), &newWidth, &newHeight); +#endif if (newWidth == _overlayScreen->getWidth() && newHeight == _overlayScreen->getHeight()) { return; // nothing to do @@ -457,7 +465,7 @@ void OpenGLSdlGraphics3dManager::initializeOpenGLContext() const { OpenGLContext.initialize(_glContextType); #if SDL_VERSION_ATLEAST(2, 0, 0) - if (SDL_GL_SetSwapInterval(_vsync ? 1 : 0)) { + if (!SDL_GL_SetSwapInterval(_vsync ? 1 : 0)) { warning("Unable to %s VSync: %s", _vsync ? "enable" : "disable", SDL_GetError()); } #endif @@ -787,7 +795,15 @@ int16 OpenGLSdlGraphics3dManager::getOverlayWidth() const { } bool OpenGLSdlGraphics3dManager::showMouse(bool visible) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + if(visible) { + SDL_ShowCursor(); + } else { + SDL_HideCursor(); + } +#elif SDL_VERSION_ATLEAST(2, 0, 0) SDL_ShowCursor(visible ? SDL_ENABLE : SDL_DISABLE); +#endif return true; } @@ -803,7 +819,11 @@ void OpenGLSdlGraphics3dManager::deinitializeRenderer() { destroyImGui(); #endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_GL_DestroyContext(_glContext); +#else SDL_GL_DeleteContext(_glContext); +#endif _glContext = nullptr; } #endif // SDL_VERSION_ATLEAST(2, 0, 0) diff --git a/backends/imgui/backends/imgui_impl_sdl3.cpp b/backends/imgui/backends/imgui_impl_sdl3.cpp new file mode 100644 index 000000000000..44536554eae2 --- /dev/null +++ b/backends/imgui/backends/imgui_impl_sdl3.cpp @@ -0,0 +1,772 @@ +// dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) +// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) +// (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) + +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) + +// Implemented features: +// [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: IME support. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten. +// 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807) +// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: +// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn +// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn +// - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn +// 2024-08-19: Storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. +// 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853) +// 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807) +// 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() memory ownership change. (#7801) +// 2024-07-15: Update for SDL3 api changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) +// 2024-07-02: Update for SDL3 api changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762). +// 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea(). +// 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures. +// 2024-06-24: Update for SDL3 api changes: SDL_EVENT_KEY_DOWN/SDL_EVENT_KEY_UP contents. +// 2024-06-03; Update for SDL3 api changes: SDL_SYSTEM_CURSOR_ renames. +// 2024-05-15: Update for SDL3 api changes: SDLK_ renames. +// 2024-04-15: Inputs: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput() as SDL3 no longer enables it by default and should play nicer with IME. +// 2024-02-13: Inputs: Fixed gamepad support. Handle gamepad disconnection. Added ImGui_ImplSDL3_SetGamepadMode(). +// 2023-11-13: Updated for recent SDL3 API changes. +// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. +// 2023-05-04: Fixed build on Emscripten/iOS/Android. (#6391) +// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306) +// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702) +// 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644) +// 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog. + +#include "backends/imgui/imgui.h" +#ifndef IMGUI_DISABLE +#include "backends/platform/sdl/sdl.h" +#include "imgui_impl_sdl3.h" + +// Clang warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#endif + +// SDL +#include +#if defined(__APPLE__) +#include +#endif +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif + +#if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) +#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 +#else +#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 +#endif + +// FIXME-LEGACY: remove when SDL 3.1.3 preview is released. +#ifndef SDLK_APOSTROPHE +#define SDLK_APOSTROPHE SDLK_QUOTE +#endif +#ifndef SDLK_GRAVE +#define SDLK_GRAVE SDLK_BACKQUOTE +#endif + +// SDL Data +struct ImGui_ImplSDL3_Data +{ + SDL_Window* Window; + SDL_WindowID WindowID; + SDL_Renderer* Renderer; + Uint64 Time; + char* ClipboardTextData; + + // IME handling + SDL_Window* ImeWindow; + + // Mouse handling + Uint32 MouseWindowID; + int MouseButtonsDown; + SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT]; + SDL_Cursor* MouseLastCursor; + int MousePendingLeaveFrame; + bool MouseCanUseGlobalState; + + // Gamepad handling + ImVector Gamepads; + ImGui_ImplSDL3_GamepadMode GamepadMode; + bool WantUpdateGamepadsList; + + ImGui_ImplSDL3_Data() { memset((void*)this, 0, sizeof(*this)); } +}; + +// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +// FIXME: multi-context support is not well tested and probably dysfunctional in this backend. +// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. +static ImGui_ImplSDL3_Data* ImGui_ImplSDL3_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplSDL3_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; +} + +// Functions +static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + const char* sdl_clipboard_text = SDL_GetClipboardText(); + bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : nullptr; + return bd->ClipboardTextData; +} + +static void ImGui_ImplSDL3_SetClipboardText(ImGuiContext*, const char* text) +{ + SDL_SetClipboardText(text); +} + +static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle; + SDL_Window* window = SDL_GetWindowFromID(window_id); + if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != nullptr) + { + SDL_StopTextInput(bd->ImeWindow); + bd->ImeWindow = nullptr; + } + if (data->WantVisible) + { + SDL_Rect r; + r.x = (int)data->InputPos.x; + r.y = (int)data->InputPos.y; + r.w = 1; + r.h = (int)data->InputLineHeight; + SDL_SetTextInputArea(window, &r, 0); + SDL_StartTextInput(window); + bd->ImeWindow = window; + } +} + +// Not static to allow third-party code to use that if they want to (but undocumented) +ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode); +ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode) +{ + // Keypad doesn't have individual key values in SDL3 + switch (scancode) + { + case SDL_SCANCODE_KP_0: return ImGuiKey_Keypad0; + case SDL_SCANCODE_KP_1: return ImGuiKey_Keypad1; + case SDL_SCANCODE_KP_2: return ImGuiKey_Keypad2; + case SDL_SCANCODE_KP_3: return ImGuiKey_Keypad3; + case SDL_SCANCODE_KP_4: return ImGuiKey_Keypad4; + case SDL_SCANCODE_KP_5: return ImGuiKey_Keypad5; + case SDL_SCANCODE_KP_6: return ImGuiKey_Keypad6; + case SDL_SCANCODE_KP_7: return ImGuiKey_Keypad7; + case SDL_SCANCODE_KP_8: return ImGuiKey_Keypad8; + case SDL_SCANCODE_KP_9: return ImGuiKey_Keypad9; + case SDL_SCANCODE_KP_PERIOD: return ImGuiKey_KeypadDecimal; + case SDL_SCANCODE_KP_DIVIDE: return ImGuiKey_KeypadDivide; + case SDL_SCANCODE_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; + case SDL_SCANCODE_KP_MINUS: return ImGuiKey_KeypadSubtract; + case SDL_SCANCODE_KP_PLUS: return ImGuiKey_KeypadAdd; + case SDL_SCANCODE_KP_ENTER: return ImGuiKey_KeypadEnter; + case SDL_SCANCODE_KP_EQUALS: return ImGuiKey_KeypadEqual; + default: break; + } + switch (keycode) + { + case SDLK_TAB: return ImGuiKey_Tab; + case SDLK_LEFT: return ImGuiKey_LeftArrow; + case SDLK_RIGHT: return ImGuiKey_RightArrow; + case SDLK_UP: return ImGuiKey_UpArrow; + case SDLK_DOWN: return ImGuiKey_DownArrow; + case SDLK_PAGEUP: return ImGuiKey_PageUp; + case SDLK_PAGEDOWN: return ImGuiKey_PageDown; + case SDLK_HOME: return ImGuiKey_Home; + case SDLK_END: return ImGuiKey_End; + case SDLK_INSERT: return ImGuiKey_Insert; + case SDLK_DELETE: return ImGuiKey_Delete; + case SDLK_BACKSPACE: return ImGuiKey_Backspace; + case SDLK_SPACE: return ImGuiKey_Space; + case SDLK_RETURN: return ImGuiKey_Enter; + case SDLK_ESCAPE: return ImGuiKey_Escape; + case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe; + case SDLK_COMMA: return ImGuiKey_Comma; + case SDLK_MINUS: return ImGuiKey_Minus; + case SDLK_PERIOD: return ImGuiKey_Period; + case SDLK_SLASH: return ImGuiKey_Slash; + case SDLK_SEMICOLON: return ImGuiKey_Semicolon; + case SDLK_EQUALS: return ImGuiKey_Equal; + case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; + case SDLK_BACKSLASH: return ImGuiKey_Backslash; + case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; + case SDLK_GRAVE: return ImGuiKey_GraveAccent; + case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; + case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; + case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; + case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen; + case SDLK_PAUSE: return ImGuiKey_Pause; + case SDLK_LCTRL: return ImGuiKey_LeftCtrl; + case SDLK_LSHIFT: return ImGuiKey_LeftShift; + case SDLK_LALT: return ImGuiKey_LeftAlt; + case SDLK_LGUI: return ImGuiKey_LeftSuper; + case SDLK_RCTRL: return ImGuiKey_RightCtrl; + case SDLK_RSHIFT: return ImGuiKey_RightShift; + case SDLK_RALT: return ImGuiKey_RightAlt; + case SDLK_RGUI: return ImGuiKey_RightSuper; + case SDLK_APPLICATION: return ImGuiKey_Menu; + case SDLK_0: return ImGuiKey_0; + case SDLK_1: return ImGuiKey_1; + case SDLK_2: return ImGuiKey_2; + case SDLK_3: return ImGuiKey_3; + case SDLK_4: return ImGuiKey_4; + case SDLK_5: return ImGuiKey_5; + case SDLK_6: return ImGuiKey_6; + case SDLK_7: return ImGuiKey_7; + case SDLK_8: return ImGuiKey_8; + case SDLK_9: return ImGuiKey_9; + case SDLK_A: return ImGuiKey_A; + case SDLK_B: return ImGuiKey_B; + case SDLK_C: return ImGuiKey_C; + case SDLK_D: return ImGuiKey_D; + case SDLK_E: return ImGuiKey_E; + case SDLK_F: return ImGuiKey_F; + case SDLK_G: return ImGuiKey_G; + case SDLK_H: return ImGuiKey_H; + case SDLK_I: return ImGuiKey_I; + case SDLK_J: return ImGuiKey_J; + case SDLK_K: return ImGuiKey_K; + case SDLK_L: return ImGuiKey_L; + case SDLK_M: return ImGuiKey_M; + case SDLK_N: return ImGuiKey_N; + case SDLK_O: return ImGuiKey_O; + case SDLK_P: return ImGuiKey_P; + case SDLK_Q: return ImGuiKey_Q; + case SDLK_R: return ImGuiKey_R; + case SDLK_S: return ImGuiKey_S; + case SDLK_T: return ImGuiKey_T; + case SDLK_U: return ImGuiKey_U; + case SDLK_V: return ImGuiKey_V; + case SDLK_W: return ImGuiKey_W; + case SDLK_X: return ImGuiKey_X; + case SDLK_Y: return ImGuiKey_Y; + case SDLK_Z: return ImGuiKey_Z; + case SDLK_F1: return ImGuiKey_F1; + case SDLK_F2: return ImGuiKey_F2; + case SDLK_F3: return ImGuiKey_F3; + case SDLK_F4: return ImGuiKey_F4; + case SDLK_F5: return ImGuiKey_F5; + case SDLK_F6: return ImGuiKey_F6; + case SDLK_F7: return ImGuiKey_F7; + case SDLK_F8: return ImGuiKey_F8; + case SDLK_F9: return ImGuiKey_F9; + case SDLK_F10: return ImGuiKey_F10; + case SDLK_F11: return ImGuiKey_F11; + case SDLK_F12: return ImGuiKey_F12; + case SDLK_F13: return ImGuiKey_F13; + case SDLK_F14: return ImGuiKey_F14; + case SDLK_F15: return ImGuiKey_F15; + case SDLK_F16: return ImGuiKey_F16; + case SDLK_F17: return ImGuiKey_F17; + case SDLK_F18: return ImGuiKey_F18; + case SDLK_F19: return ImGuiKey_F19; + case SDLK_F20: return ImGuiKey_F20; + case SDLK_F21: return ImGuiKey_F21; + case SDLK_F22: return ImGuiKey_F22; + case SDLK_F23: return ImGuiKey_F23; + case SDLK_F24: return ImGuiKey_F24; + case SDLK_AC_BACK: return ImGuiKey_AppBack; + case SDLK_AC_FORWARD: return ImGuiKey_AppForward; + default: break; + } + return ImGuiKey_None; +} + +static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) +{ + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & SDL_KMOD_CTRL) != 0); + io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & SDL_KMOD_SHIFT) != 0); + io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & SDL_KMOD_ALT) != 0); + io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & SDL_KMOD_GUI) != 0); +} + + +static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : nullptr; +} + +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. +// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. +bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?"); + ImGuiIO& io = ImGui::GetIO(); + + switch (event->type) + { + case SDL_EVENT_MOUSE_MOTION: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == nullptr) + return false; + ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); + io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMousePosEvent(mouse_pos.x, mouse_pos.y); + return true; + } + case SDL_EVENT_MOUSE_WHEEL: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == nullptr) + return false; + //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); + float wheel_x = -event->wheel.x; + float wheel_y = event->wheel.y; + io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMouseWheelEvent(wheel_x, wheel_y); + return true; + } + case SDL_EVENT_MOUSE_BUTTON_DOWN: + case SDL_EVENT_MOUSE_BUTTON_UP: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == nullptr) + return false; + int mouse_button = -1; + if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } + if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; } + if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; } + if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; } + if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; } + if (mouse_button == -1) + break; + io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMouseButtonEvent(mouse_button, (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN)); + bd->MouseButtonsDown = (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button)); + return true; + } + case SDL_EVENT_TEXT_INPUT: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == nullptr) + return false; + io.AddInputCharactersUTF8(event->text.text); + return true; + } + case SDL_EVENT_KEY_DOWN: + case SDL_EVENT_KEY_UP: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == nullptr) + return false; + //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%d: key=%d, scancode=%d, mod=%X\n", (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP", event->key.key, event->key.scancode, event->key.mod); + ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod); + ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode); + io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN)); + io.SetKeyEventNativeData(key, event->key.key, event->key.scancode, event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. + return true; + } + case SDL_EVENT_WINDOW_MOUSE_ENTER: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr) + return false; + bd->MouseWindowID = event->window.windowID; + bd->MousePendingLeaveFrame = 0; + return true; + } + // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late, + // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why + // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details. + // FIXME: Unconfirmed whether this is still needed with SDL3. + case SDL_EVENT_WINDOW_MOUSE_LEAVE: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr) + return false; + bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1; + return true; + } + case SDL_EVENT_WINDOW_FOCUS_GAINED: + case SDL_EVENT_WINDOW_FOCUS_LOST: + { + if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr) + return false; + io.AddFocusEvent(event->type == SDL_EVENT_WINDOW_FOCUS_GAINED); + return true; + } + case SDL_EVENT_GAMEPAD_ADDED: + case SDL_EVENT_GAMEPAD_REMOVED: + { + bd->WantUpdateGamepadsList = true; + return true; + } + } + return false; +} + +static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window) +{ + viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(window); + viewport->PlatformHandleRaw = nullptr; +#if defined(_WIN32) && !defined(__WINRT__) + viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); +#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA) + viewport->PlatformHandleRaw = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, nullptr); +#endif +} + +static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context) +{ + ImGuiIO& io = ImGui::GetIO(); + IMGUI_CHECKVERSION(); + IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); + IM_UNUSED(sdl_gl_context); // Unused in this branch + + // Check and store if we are on a SDL backend that supports global mouse position + // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) + bool mouse_can_use_global_state = false; +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + const char* sdl_backend = SDL_GetCurrentVideoDriver(); + const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; + for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++) + if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0) + mouse_can_use_global_state = true; +#endif + + // Setup backend capabilities flags + ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)(); + io.BackendPlatformUserData = (void*)bd; + io.BackendPlatformName = "imgui_impl_sdl3"; + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + + bd->Window = window; + bd->WindowID = SDL_GetWindowID(window); + bd->Renderer = renderer; + bd->MouseCanUseGlobalState = mouse_can_use_global_state; + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; + platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; + platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData; + + // Gamepad handling + bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst; + bd->WantUpdateGamepadsList = true; + + // Load mouse cursors + bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT); + bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_TEXT); + bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_MOVE); + bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NS_RESIZE); + bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_EW_RESIZE); + bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE); + bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE); + bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER); + bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NOT_ALLOWED); + + // Set platform dependent data in viewport + // Our mouse update function expect PlatformHandle to be filled for the main viewport + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ImGui_ImplSDL3_SetupPlatformHandles(main_viewport, window); + + // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event. + // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered. + // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application. + // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click: + // you can ignore SDL_EVENT_MOUSE_BUTTON_DOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED) +#ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH + SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); +#endif + + // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710) +#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE + SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); +#endif + + return true; +} + +bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) +{ + IM_UNUSED(sdl_gl_context); // Viewport branch will need this. + return ImGui_ImplSDL3_Init(window, nullptr, sdl_gl_context); +} + +bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window) +{ +#if !defined(_WIN32) + IM_ASSERT(0 && "Unsupported"); +#endif + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer) +{ + return ImGui_ImplSDL3_Init(window, renderer, nullptr); +} + +bool ImGui_ImplSDL3_InitForOther(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +static void ImGui_ImplSDL3_CloseGamepads(); + +void ImGui_ImplSDL3_Shutdown() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) + SDL_DestroyCursor(bd->MouseCursors[cursor_n]); + ImGui_ImplSDL3_CloseGamepads(); + + io.BackendPlatformName = nullptr; + io.BackendPlatformUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); + IM_DELETE(bd); +} + +static void ImGui_ImplSDL3_UpdateMouseData() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGuiIO& io = ImGui::GetIO(); + + // We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below) +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside + SDL_CaptureMouse(bd->MouseButtonsDown != 0); + SDL_Window* focused_window = SDL_GetKeyboardFocus(); + const bool is_app_focused = (bd->Window == focused_window); +#else + SDL_Window* focused_window = bd->Window; + const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only +#endif + if (is_app_focused) + { + // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user) + if (io.WantSetMousePos) + SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y); + + // (Optional) Fallback to provide mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) + if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0) + { + // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) + float mouse_x_global, mouse_y_global; + int window_x, window_y; + SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); + SDL_GetWindowPosition(focused_window, &window_x, &window_y); + io.AddMousePosEvent(mouse_x_global - window_x, mouse_y_global - window_y); + } + } +} + +static void ImGui_ImplSDL3_UpdateMouseCursor() +{ + ImGuiIO& io = ImGui::GetIO(); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) + return; + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + + ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); + if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) + { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + SDL_HideCursor(); + } + else + { + // Show OS mouse cursor + SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]; + if (bd->MouseLastCursor != expected_cursor) + { + SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113) + bd->MouseLastCursor = expected_cursor; + } + SDL_ShowCursor(); + } +} + +static void ImGui_ImplSDL3_CloseGamepads() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + if (bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual) + for (SDL_Gamepad* gamepad : bd->Gamepads) + SDL_CloseGamepad(gamepad); + bd->Gamepads.resize(0); +} + +void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array, int manual_gamepads_count) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGui_ImplSDL3_CloseGamepads(); + if (mode == ImGui_ImplSDL3_GamepadMode_Manual) + { + IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0); + for (int n = 0; n < manual_gamepads_count; n++) + bd->Gamepads.push_back(manual_gamepads_array[n]); + } + else + { + IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0); + bd->WantUpdateGamepadsList = true; + } + bd->GamepadMode = mode; +} + +static void ImGui_ImplSDL3_UpdateGamepadButton(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadButton button_no) +{ + bool merged_value = false; + for (SDL_Gamepad* gamepad : bd->Gamepads) + merged_value |= SDL_GetGamepadButton(gamepad, button_no) != 0; + io.AddKeyEvent(key, merged_value); +} + +static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; } +static void ImGui_ImplSDL3_UpdateGamepadAnalog(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadAxis axis_no, float v0, float v1) +{ + float merged_value = 0.0f; + for (SDL_Gamepad* gamepad : bd->Gamepads) + { + float vn = Saturate((float)(SDL_GetGamepadAxis(gamepad, axis_no) - v0) / (float)(v1 - v0)); + if (merged_value < vn) + merged_value = vn; + } + io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value); +} + +static void ImGui_ImplSDL3_UpdateGamepads() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + + // Update list of gamepads to use + if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual) + { + ImGui_ImplSDL3_CloseGamepads(); + int sdl_gamepads_count = 0; + SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count); + for (int n = 0; n < sdl_gamepads_count; n++) + if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n])) + { + bd->Gamepads.push_back(gamepad); + if (bd->GamepadMode == ImGui_ImplSDL3_GamepadMode_AutoFirst) + break; + } + bd->WantUpdateGamepadsList = false; + SDL_free(sdl_gamepads); + } + + // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) + return; + io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; + if (bd->Gamepads.Size == 0) + return; + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + + // Update gamepad inputs + const int thumb_dead_zone = 8000; // SDL_gamepad.h suggests using this value. + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_GAMEPAD_BUTTON_START); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_GAMEPAD_BUTTON_BACK); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_GAMEPAD_BUTTON_WEST); // Xbox X, PS Square + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_GAMEPAD_BUTTON_EAST); // Xbox B, PS Circle + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_GAMEPAD_BUTTON_NORTH); // Xbox Y, PS Triangle + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_GAMEPAD_BUTTON_SOUTH); // Xbox A, PS Cross + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_GAMEPAD_BUTTON_DPAD_UP); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0.0f, 32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0.0f, 32767); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_GAMEPAD_BUTTON_LEFT_STICK); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_GAMEPAD_BUTTON_RIGHT_STICK); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_GAMEPAD_AXIS_LEFTX, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_GAMEPAD_AXIS_LEFTX, +thumb_dead_zone, +32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_GAMEPAD_AXIS_LEFTY, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_GAMEPAD_AXIS_LEFTY, +thumb_dead_zone, +32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_GAMEPAD_AXIS_RIGHTX, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_GAMEPAD_AXIS_RIGHTX, +thumb_dead_zone, +32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_GAMEPAD_AXIS_RIGHTY, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767); +} + +void ImGui_ImplSDL3_NewFrame() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?"); + ImGuiIO& io = ImGui::GetIO(); + + // Setup display size (every frame to accommodate for window resizing) + int w, h; + int display_w, display_h; + SDL_GetWindowSize(bd->Window, &w, &h); + if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED) + w = h = 0; + SDL_GetWindowSizeInPixels(bd->Window, &display_w, &display_h); + io.DisplaySize = ImVec2((float)w, (float)h); + if (w > 0 && h > 0) + io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); + + // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) + // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) + static Uint64 frequency = SDL_GetPerformanceFrequency(); + Uint64 current_time = SDL_GetPerformanceCounter(); + if (current_time <= bd->Time) + current_time = bd->Time + 1; + io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f); + bd->Time = current_time; + + if (bd->MousePendingLeaveFrame && bd->MousePendingLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0) + { + bd->MouseWindowID = 0; + bd->MousePendingLeaveFrame = 0; + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); + } + + ImGui_ImplSDL3_UpdateMouseData(); + ImGui_ImplSDL3_UpdateMouseCursor(); + + // Update game controllers (if enabled and available) + ImGui_ImplSDL3_UpdateGamepads(); +} + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui/backends/imgui_impl_sdl3.h b/backends/imgui/backends/imgui_impl_sdl3.h new file mode 100644 index 000000000000..6483fb5d06bd --- /dev/null +++ b/backends/imgui/backends/imgui_impl_sdl3.h @@ -0,0 +1,48 @@ +// dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) +// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) +// (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) + +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) + +// Implemented features: +// [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: IME support. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#include "backends/imgui/imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +struct SDL_Window; +struct SDL_Renderer; +struct SDL_Gamepad; +typedef union SDL_Event SDL_Event; + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOther(SDL_Window* window); +IMGUI_IMPL_API void ImGui_ImplSDL3_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDL3_NewFrame(); +IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event); + +// Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. +// When using manual mode, caller is responsible for opening/closing gamepad. +enum ImGui_ImplSDL3_GamepadMode { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual }; +IMGUI_IMPL_API void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = nullptr, int manual_gamepads_count = -1); + +#endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui/backends/imgui_impl_sdlrenderer3.cpp new file mode 100644 index 000000000000..153d4b767c5e --- /dev/null +++ b/backends/imgui/backends/imgui_impl_sdlrenderer3.cpp @@ -0,0 +1,283 @@ +// dear imgui: Renderer Backend for SDL_Renderer for SDL3 +// (Requires: SDL 3.0.0+) + +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) + +// Note how SDL_Renderer is an _optional_ component of SDL3. +// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. +// If your application will want to render any non trivial amount of graphics other than UI, +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and +// it might be difficult to step out of those boundaries. + +// Implemented features: +// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. + +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// 2024-07-01: Update for SDL3 api changes: SDL_RenderGeometryRaw() uint32 version was removed (SDL#9009). +// 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter. +// 2024-02-12: Amend to query SDL_RenderViewportSet() and restore viewport accordingly. +// 2023-05-30: Initial version. + +#include "backends/imgui/imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_sdlrenderer3.h" +#include // intptr_t + +// Clang warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#endif + +// SDL +#include +#if !SDL_VERSION_ATLEAST(3,0,0) +#error This backend requires SDL 3.0.0+ +#endif + +// SDL_Renderer data +struct ImGui_ImplSDLRenderer3_Data +{ + SDL_Renderer* Renderer; // Main viewport's renderer + SDL_Texture* FontTexture; + ImVector ColorBuffer; + + ImGui_ImplSDLRenderer3_Data() { memset((void*)this, 0, sizeof(*this)); } +}; + +// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +static ImGui_ImplSDLRenderer3_Data* ImGui_ImplSDLRenderer3_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; +} + +// Functions +bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer) +{ + ImGuiIO& io = ImGui::GetIO(); + IMGUI_CHECKVERSION(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!"); + + // Setup backend capabilities flags + ImGui_ImplSDLRenderer3_Data* bd = IM_NEW(ImGui_ImplSDLRenderer3_Data)(); + io.BackendRendererUserData = (void*)bd; + io.BackendRendererName = "imgui_impl_sdlrenderer3"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + + bd->Renderer = renderer; + + return true; +} + +void ImGui_ImplSDLRenderer3_Shutdown() +{ + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + + ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); + + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + IM_DELETE(bd); +} + +static void ImGui_ImplSDLRenderer3_SetupRenderState(SDL_Renderer* renderer) +{ + // Clear out any viewports and cliprect set by the user + // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. + SDL_SetRenderViewport(renderer, nullptr); + SDL_SetRenderClipRect(renderer, nullptr); +} + +void ImGui_ImplSDLRenderer3_NewFrame() +{ + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer3_Init()?"); + + if (!bd->FontTexture) + ImGui_ImplSDLRenderer3_CreateDeviceObjects(); +} + +// https://github.com/libsdl-org/SDL/issues/9009 +static int SDL_RenderGeometryRaw8BitColor(SDL_Renderer* renderer, ImVector& colors_out, SDL_Texture* texture, const float* xy, int xy_stride, const SDL_Color* color, int color_stride, const float* uv, int uv_stride, int num_vertices, const void* indices, int num_indices, int size_indices) +{ + const Uint8* color2 = (const Uint8*)color; + colors_out.resize(num_vertices); + SDL_FColor* color3 = colors_out.Data; + for (int i = 0; i < num_vertices; i++) + { + color3[i].r = color->r / 255.0f; + color3[i].g = color->g / 255.0f; + color3[i].b = color->b / 255.0f; + color3[i].a = color->a / 255.0f; + color2 += color_stride; + color = (const SDL_Color*)color2; + } + return SDL_RenderGeometryRaw(renderer, texture, xy, xy_stride, color3, sizeof(*color3), uv, uv_stride, num_vertices, indices, num_indices, size_indices); +} + +void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer) +{ + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + + // If there's a scale factor set by the user, use that instead + // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass + // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. + float rsx = 1.0f; + float rsy = 1.0f; + SDL_GetRenderScale(renderer, &rsx, &rsy); + ImVec2 render_scale; + render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; + render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; + + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); + int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); + if (fb_width == 0 || fb_height == 0) + return; + + // Backup SDL_Renderer state that will be modified to restore it afterwards + struct BackupSDLRendererState + { + SDL_Rect Viewport; + bool ViewportEnabled; + bool ClipEnabled; + SDL_Rect ClipRect; + }; + BackupSDLRendererState old = {}; + old.ViewportEnabled = SDL_RenderViewportSet(renderer); + old.ClipEnabled = SDL_RenderClipEnabled(renderer); + SDL_GetRenderViewport(renderer, &old.Viewport); + SDL_GetRenderClipRect(renderer, &old.ClipRect); + + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = render_scale; + + // Render command lists + ImGui_ImplSDLRenderer3_SetupRenderState(renderer); + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; + const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; + + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) + { + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplSDLRenderer3_SetupRenderState(renderer); + else + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } + if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } + if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; } + if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; } + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + + SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) }; + SDL_SetRenderClipRect(renderer, &r); + + const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos)); + const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv)); + const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+ + + // Bind texture, Draw + SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); + SDL_RenderGeometryRaw8BitColor(renderer, bd->ColorBuffer, tex, + xy, (int)sizeof(ImDrawVert), + color, (int)sizeof(ImDrawVert), + uv, (int)sizeof(ImDrawVert), + cmd_list->VtxBuffer.Size - pcmd->VtxOffset, + idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx)); + } + } + } + + // Restore modified SDL_Renderer state + SDL_SetRenderViewport(renderer, old.ViewportEnabled ? &old.Viewport : nullptr); + SDL_SetRenderClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr); +} + +// Called by Init/NewFrame/Shutdown +bool ImGui_ImplSDLRenderer3_CreateFontsTexture() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + + // Build texture atlas + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. + + // Upload texture to graphics system + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); + if (bd->FontTexture == nullptr) + { + SDL_Log("error creating texture"); + return false; + } + SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width); + SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND); + SDL_SetTextureScaleMode(bd->FontTexture, SDL_SCALEMODE_LINEAR); + + // Store our identifier + io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); + + return true; +} + +void ImGui_ImplSDLRenderer3_DestroyFontsTexture() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + if (bd->FontTexture) + { + io.Fonts->SetTexID(0); + SDL_DestroyTexture(bd->FontTexture); + bd->FontTexture = nullptr; + } +} + +bool ImGui_ImplSDLRenderer3_CreateDeviceObjects() +{ + return ImGui_ImplSDLRenderer3_CreateFontsTexture(); +} + +void ImGui_ImplSDLRenderer3_DestroyDeviceObjects() +{ + ImGui_ImplSDLRenderer3_DestroyFontsTexture(); +} + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui/backends/imgui_impl_sdlrenderer3.h b/backends/imgui/backends/imgui_impl_sdlrenderer3.h new file mode 100644 index 000000000000..6529469c0257 --- /dev/null +++ b/backends/imgui/backends/imgui_impl_sdlrenderer3.h @@ -0,0 +1,42 @@ +// dear imgui: Renderer Backend for SDL_Renderer for SDL3 +// (Requires: SDL 3.0.0+) + +// (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) + +// Note how SDL_Renderer is an _optional_ component of SDL3. +// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. +// If your application will want to render any non trivial amount of graphics other than UI, +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and +// it might be difficult to step out of those boundaries. + +// Implemented features: +// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. + +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#include "backends/imgui/imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +struct SDL_Renderer; + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! +IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer); + +// Called by Init/NewFrame/Shutdown +IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyFontsTexture(); +IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui/scummvm.patch b/backends/imgui/scummvm.patch index 937ff9e95535..d1ca70c18bbd 100644 --- a/backends/imgui/scummvm.patch +++ b/backends/imgui/scummvm.patch @@ -1,7 +1,26 @@ -diff --color -rbu ./backends/imgui_impl_opengl3.cpp ../scummvm/scummvm/backends/imgui/backends/imgui_impl_opengl3.cpp ---- ./backends/imgui_impl_opengl3.cpp 2024-10-07 18:21:01 -+++ ../scummvm/scummvm/backends/imgui/backends/imgui_impl_opengl3.cpp 2024-10-07 18:30:56 -@@ -114,7 +114,7 @@ +diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp +index 7087a7c5..b363ba07 100644 +--- a/backends/imgui_impl_opengl3.cpp ++++ b/backends/imgui_impl_opengl3.cpp +@@ -5,7 +5,8 @@ + + // Implemented features: + // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! +-// [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). ++// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). ++// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. + + // About WebGL/ES: + // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. +@@ -22,6 +23,7 @@ + + // CHANGELOG + // (minor and older changes stripped away, please see git history for details) ++// 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. + // 2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) + // 2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562) + // 2024-04-16: OpenGL: Detect ES3 contexts on desktop based on version string, to e.g. avoid calling glPolygonMode() on them. (#7447) +@@ -112,7 +114,7 @@ #define _CRT_SECURE_NO_WARNINGS #endif @@ -10,7 +29,7 @@ diff --color -rbu ./backends/imgui_impl_opengl3.cpp ../scummvm/scummvm/backends/ #ifndef IMGUI_DISABLE #include "imgui_impl_opengl3.h" #include -@@ -167,6 +167,7 @@ +@@ -165,6 +167,7 @@ // - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped // - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases // Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version. @@ -18,10 +37,98 @@ diff --color -rbu ./backends/imgui_impl_opengl3.cpp ../scummvm/scummvm/backends/ #define IMGL3W_IMPL #include "imgui_impl_opengl3_loader.h" #endif -diff --color -rbu ./backends/imgui_impl_opengl3.h ../scummvm/scummvm/backends/imgui/backends/imgui_impl_opengl3.h ---- ./backends/imgui_impl_opengl3.h 2024-10-07 18:21:01 -+++ ../scummvm/scummvm/backends/imgui/backends/imgui_impl_opengl3.h 2024-10-07 18:30:56 -@@ -27,7 +27,7 @@ +@@ -249,6 +252,10 @@ static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData() + return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; + } + ++// Forward Declarations ++static void ImGui_ImplOpenGL3_InitPlatformInterface(); ++static void ImGui_ImplOpenGL3_ShutdownPlatformInterface(); ++ + // OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only) + #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + struct ImGui_ImplOpenGL3_VtxAttribState +@@ -341,6 +348,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) + if (bd->GlVersion >= 320) + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + #endif ++ io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) + + // Store GLSL version string so we can refer to it later in case we recreate shaders. + // Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure. +@@ -381,6 +389,9 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) + } + #endif + ++ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ++ ImGui_ImplOpenGL3_InitPlatformInterface(); ++ + return true; + } + +@@ -390,10 +401,11 @@ void ImGui_ImplOpenGL3_Shutdown() + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + ++ ImGui_ImplOpenGL3_ShutdownPlatformInterface(); + ImGui_ImplOpenGL3_DestroyDeviceObjects(); + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; +- io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; ++ io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports); + IM_DELETE(bd); + } + +@@ -949,6 +961,34 @@ void ImGui_ImplOpenGL3_DestroyDeviceObjects() + ImGui_ImplOpenGL3_DestroyFontsTexture(); + } + ++//-------------------------------------------------------------------------------------------------------- ++// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT ++// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. ++// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. ++//-------------------------------------------------------------------------------------------------------- ++ ++static void ImGui_ImplOpenGL3_RenderWindow(ImGuiViewport* viewport, void*) ++{ ++ if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear)) ++ { ++ ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); ++ glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); ++ glClear(GL_COLOR_BUFFER_BIT); ++ } ++ ImGui_ImplOpenGL3_RenderDrawData(viewport->DrawData); ++} ++ ++static void ImGui_ImplOpenGL3_InitPlatformInterface() ++{ ++ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ++ platform_io.Renderer_RenderWindow = ImGui_ImplOpenGL3_RenderWindow; ++} ++ ++static void ImGui_ImplOpenGL3_ShutdownPlatformInterface() ++{ ++ ImGui::DestroyPlatformWindows(); ++} ++ + //----------------------------------------------------------------------------- + + #if defined(__GNUC__) +diff --git a/backends/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h +index 54545f95..ecb865db 100644 +--- a/backends/imgui_impl_opengl3.h ++++ b/backends/imgui_impl_opengl3.h +@@ -5,7 +5,8 @@ + + // Implemented features: + // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! +-// [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). ++// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). ++// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. + + // About WebGL/ES: + // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. +@@ -26,7 +27,7 @@ // Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp. #pragma once @@ -30,7 +137,7 @@ diff --color -rbu ./backends/imgui_impl_opengl3.h ../scummvm/scummvm/backends/im #ifndef IMGUI_DISABLE // Follow "Getting Started" link and check examples/ folder to learn about using backends! -@@ -56,7 +56,7 @@ +@@ -55,7 +56,7 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); #endif #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__)) #define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" @@ -39,9 +146,10 @@ diff --color -rbu ./backends/imgui_impl_opengl3.h ../scummvm/scummvm/backends/im #define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" #else // Otherwise imgui_impl_opengl3_loader.h will be used. -diff --color -rbu ./backends/imgui_impl_opengl3_loader.h ../scummvm/scummvm/backends/imgui/backends/imgui_impl_opengl3_loader.h ---- ./backends/imgui_impl_opengl3_loader.h 2024-05-17 22:26:35 -+++ ../scummvm/scummvm/backends/imgui/backends/imgui_impl_opengl3_loader.h 2024-10-07 18:30:56 +diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h +index 3fbc3481..2f290421 100644 +--- a/backends/imgui_impl_opengl3_loader.h ++++ b/backends/imgui_impl_opengl3_loader.h @@ -56,6 +56,11 @@ #ifndef __gl3w_h_ #define __gl3w_h_ @@ -54,7 +162,16 @@ diff --color -rbu ./backends/imgui_impl_opengl3_loader.h ../scummvm/scummvm/back // Adapted from KHR/khrplatform.h to avoid including entire file. #ifndef __khrplatform_h_ typedef float khronos_float_t; -@@ -614,7 +619,20 @@ +@@ -118,7 +123,7 @@ extern "C" { + ** included as . + ** + ** glcorearb.h includes only APIs in the latest OpenGL core profile +-** implementation together with APIs in newer ARB extensions which ++** implementation together with APIs in newer ARB extensions which + ** can be supported by the core profile. It does not, and never will + ** include functionality removed from the core profile, such as + ** fixed-function vertex and fragment processing. +@@ -614,7 +619,20 @@ extern "C" { #define GL3W_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) @@ -76,10 +193,41 @@ diff --color -rbu ./backends/imgui_impl_opengl3_loader.h ../scummvm/scummvm/back #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif -diff --color -rbu ./backends/imgui_impl_sdl2.cpp ../scummvm/scummvm/backends/imgui/backends/imgui_impl_sdl2.cpp ---- ./backends/imgui_impl_sdl2.cpp 2024-10-07 18:21:01 -+++ ../scummvm/scummvm/backends/imgui/backends/imgui_impl_sdl2.cpp 2024-10-07 18:30:56 -@@ -92,9 +92,11 @@ +diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp +index 6d98a697..c4669b07 100644 +--- a/backends/imgui_impl_sdl2.cpp ++++ b/backends/imgui_impl_sdl2.cpp +@@ -9,7 +9,11 @@ + // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] + // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. + // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +-// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. ++// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. ++// Issues: ++// [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows). ++// [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). ++// [x] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. + + // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. + // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +@@ -21,6 +25,7 @@ + + // CHANGELOG + // (minor and older changes stripped away, please see git history for details) ++// 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. + // 2024-09-09: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190) + // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: + // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn +@@ -57,7 +62,7 @@ + // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. + // 2021-08-17: Calling io.AddFocusEvent() on SDL_WINDOWEVENT_FOCUS_GAINED/SDL_WINDOWEVENT_FOCUS_LOST. + // 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using SDL_GetMouseFocus() + SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, requires SDL 2.0.5+) +-// 2021-06-29: *BREAKING CHANGE* Removed 'SDL_Window* window' parameter to ImGui_ImplSDL2_NewFrame() which was unnecessary. ++// 2021-06:29: *BREAKING CHANGE* Removed 'SDL_Window* window' parameter to ImGui_ImplSDL2_NewFrame() which was unnecessary. + // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). + // 2021-03-22: Rework global mouse pos availability check listing supported platforms explicitly, effectively fixing mouse access on Raspberry Pi. (#2837, #3950) + // 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends. +@@ -87,9 +92,11 @@ // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1). // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. @@ -92,39 +240,651 @@ diff --color -rbu ./backends/imgui_impl_sdl2.cpp ../scummvm/scummvm/backends/img // Clang warnings with -Weverything #if defined(__clang__) -@@ -128,7 +128,8 @@ - #define SDL_HAS_DISPLAY_EVENT SDL_VERSION_ATLEAST(2,0,9) - #define SDL_HAS_SHOW_WINDOW_ACTIVATION_HINT SDL_VERSION_ATLEAST(2,0,18) +@@ -98,6 +105,7 @@ + #endif + + // SDL ++// (the multi-viewports feature requires SDL features supported from SDL 2.0.4+. SDL 2.0.5+ is highly recommended) + #include + #include + #ifdef __APPLE__ +@@ -112,9 +120,18 @@ + #else + #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 + #endif ++#define SDL_HAS_WINDOW_ALPHA SDL_VERSION_ATLEAST(2,0,5) ++#define SDL_HAS_ALWAYS_ON_TOP SDL_VERSION_ATLEAST(2,0,5) ++#define SDL_HAS_USABLE_DISPLAY_BOUNDS SDL_VERSION_ATLEAST(2,0,5) ++#define SDL_HAS_PER_MONITOR_DPI SDL_VERSION_ATLEAST(2,0,4) + #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6) ++#define SDL_HAS_DISPLAY_EVENT SDL_VERSION_ATLEAST(2,0,9) ++#define SDL_HAS_SHOW_WINDOW_ACTIVATION_HINT SDL_VERSION_ATLEAST(2,0,18) #if SDL_HAS_VULKAN -extern "C" { extern DECLSPEC void SDLCALL SDL_Vulkan_GetDrawableSize(SDL_Window* window, int* w, int* h); } +//extern "C" { extern DECLSPEC void SDLCALL SDL_Vulkan_GetDrawableSize(SDL_Window* window, int* w, int* h); } +#include --#elif +#else - static const Uint32 SDL_WINDOW_VULKAN = 0x10000000; ++static const Uint32 SDL_WINDOW_VULKAN = 0x10000000; #endif -@@ -346,6 +348,11 @@ - return ImGui::FindViewportByPlatformHandle((void*)(intptr_t)window_id); + + // SDL Data +@@ -125,6 +142,8 @@ struct ImGui_ImplSDL2_Data + SDL_Renderer* Renderer; + Uint64 Time; + char* ClipboardTextData; ++ bool UseVulkan; ++ bool WantUpdateMonitors; + + // Mouse handling + Uint32 MouseWindowID; +@@ -133,6 +152,7 @@ struct ImGui_ImplSDL2_Data + SDL_Cursor* MouseLastCursor; + int MouseLastLeaveFrame; + bool MouseCanUseGlobalState; ++ bool MouseCanReportHoveredViewport; // This is hard to use/unreliable on SDL so we'll set ImGuiBackendFlags_HasMouseHoveredViewport dynamically based on state. + + // Gamepad handling + ImVector Gamepads; +@@ -151,6 +171,11 @@ static ImGui_ImplSDL2_Data* ImGui_ImplSDL2_GetBackendData() + return ImGui::GetCurrentContext() ? (ImGui_ImplSDL2_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; + } + ++// Forward Declarations ++static void ImGui_ImplSDL2_UpdateMonitors(); ++static void ImGui_ImplSDL2_InitPlatformInterface(SDL_Window* window, void* sdl_gl_context); ++static void ImGui_ImplSDL2_ShutdownPlatformInterface(); ++ + // Functions + static const char* ImGui_ImplSDL2_GetClipboardText(ImGuiContext*) + { +@@ -167,13 +192,13 @@ static void ImGui_ImplSDL2_SetClipboardText(ImGuiContext*, const char* text) } + // Note: native IME will only display if user calls SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1") _before_ SDL_CreateWindow(). +-static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData* data) ++static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) + { + if (data->WantVisible) + { + SDL_Rect r; +- r.x = (int)data->InputPos.x; +- r.y = (int)data->InputPos.y; ++ r.x = (int)(data->InputPos.x - viewport->Pos.x); ++ r.y = (int)(data->InputPos.y - viewport->Pos.y + data->InputLineHeight); + r.w = 1; + r.h = (int)data->InputLineHeight; + SDL_SetTextInputRect(&r); +@@ -321,15 +346,18 @@ static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) + + static ImGuiViewport* ImGui_ImplSDL2_GetViewportForWindowID(Uint32 window_id) + { +- ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); +- return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : NULL; ++ return ImGui::FindViewportByPlatformHandle((void*)(intptr_t)window_id); ++} ++ +bool ImGui_ImplSDL2_Ready() +{ + return ImGui_ImplSDL2_GetBackendData() != nullptr; -+} -+ + } + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. -@@ -1201,4 +1208,5 @@ + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. +-// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. + bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) + { + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); +@@ -343,6 +371,13 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) + if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == NULL) + return false; + ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); ++ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ++ { ++ int window_x, window_y; ++ SDL_GetWindowPosition(SDL_GetWindowFromID(event->motion.windowID), &window_x, &window_y); ++ mouse_pos.x += window_x; ++ mouse_pos.y += window_y; ++ } + io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMousePosEvent(mouse_pos.x, mouse_pos.y); + return true; +@@ -402,10 +437,21 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) + io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. + return true; + } ++#if SDL_HAS_DISPLAY_EVENT ++ case SDL_DISPLAYEVENT: ++ { ++ // 2.0.26 has SDL_DISPLAYEVENT_CONNECTED/SDL_DISPLAYEVENT_DISCONNECTED/SDL_DISPLAYEVENT_ORIENTATION, ++ // so change of DPI/Scaling are not reflected in this event. (SDL3 has it) ++ bd->WantUpdateMonitors = true; ++ return true; ++ } ++#endif + case SDL_WINDOWEVENT: + { +- if (ImGui_ImplSDL2_GetViewportForWindowID(event->window.windowID) == NULL) ++ ImGuiViewport* viewport = ImGui_ImplSDL2_GetViewportForWindowID(event->window.windowID); ++ if (viewport == NULL) + return false; ++ + // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right. + // - However we won't get a correct LEAVE event for a captured window. + // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late, +@@ -421,8 +467,14 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) + bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1; + if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED) + io.AddFocusEvent(true); +- else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST) ++ else if (window_event == SDL_WINDOWEVENT_FOCUS_LOST) + io.AddFocusEvent(false); ++ else if (window_event == SDL_WINDOWEVENT_CLOSE) ++ viewport->PlatformRequestClose = true; ++ else if (window_event == SDL_WINDOWEVENT_MOVED) ++ viewport->PlatformRequestMove = true; ++ else if (window_event == SDL_WINDOWEVENT_RESIZED) ++ viewport->PlatformRequestResize = true; + return true; + } + case SDL_CONTROLLERDEVICEADDED: +@@ -460,13 +512,23 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void + ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)(); + io.BackendPlatformUserData = (void*)bd; + io.BackendPlatformName = "imgui_impl_sdl2"; +- io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) +- io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) ++ io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) ++ io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) ++ if (mouse_can_use_global_state) ++ io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) + + bd->Window = window; + bd->WindowID = SDL_GetWindowID(window); + bd->Renderer = renderer; ++ ++ // SDL on Linux/OSX doesn't report events for unfocused windows (see https://github.com/ocornut/imgui/issues/4960) ++ // We will use 'MouseCanReportHoveredViewport' to set 'ImGuiBackendFlags_HasMouseHoveredViewport' dynamically each frame. + bd->MouseCanUseGlobalState = mouse_can_use_global_state; ++#ifndef __APPLE__ ++ bd->MouseCanReportHoveredViewport = bd->MouseCanUseGlobalState; ++#else ++ bd->MouseCanReportHoveredViewport = false; ++#endif + + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; +@@ -477,6 +539,9 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void + platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; }; + #endif + ++ // Update monitor a first time during init ++ ImGui_ImplSDL2_UpdateMonitors(); ++ + // Gamepad handling + bd->GamepadMode = ImGui_ImplSDL2_GamepadMode_AutoFirst; + bd->WantUpdateGamepadsList = true; +@@ -529,7 +594,11 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void + SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); + #endif + +- (void)sdl_gl_context; // Unused in 'master' branch. ++ // We need SDL_CaptureMouse(), SDL_GetGlobalMouseState() from SDL 2.0.4+ to support multiple viewports. ++ // We left the call to ImGui_ImplSDL2_InitPlatformInterface() outside of #ifdef to avoid unused-function warnings. ++ if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports)) ++ ImGui_ImplSDL2_InitPlatformInterface(window, sdl_gl_context); ++ + return true; + } + +@@ -543,7 +612,11 @@ bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window) + #if !SDL_HAS_VULKAN + IM_ASSERT(0 && "Unsupported"); + #endif +- return ImGui_ImplSDL2_Init(window, nullptr, nullptr); ++ if (!ImGui_ImplSDL2_Init(window, nullptr, nullptr)) ++ return false; ++ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ++ bd->UseVulkan = true; ++ return true; + } + + bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window) +@@ -577,6 +650,8 @@ void ImGui_ImplSDL2_Shutdown() + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + ++ ImGui_ImplSDL2_ShutdownPlatformInterface(); ++ + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) +@@ -585,10 +660,11 @@ void ImGui_ImplSDL2_Shutdown() + + io.BackendPlatformName = nullptr; + io.BackendPlatformUserData = nullptr; +- io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); ++ io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | ImGuiBackendFlags_HasMouseHoveredViewport); + IM_DELETE(bd); + } + ++// This code is incredibly messy because some of the functions we need for full viewport support are not available in SDL < 2.0.4. + static void ImGui_ImplSDL2_UpdateMouseData() + { + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); +@@ -599,25 +675,56 @@ static void ImGui_ImplSDL2_UpdateMouseData() + // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside + SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE); + SDL_Window* focused_window = SDL_GetKeyboardFocus(); +- const bool is_app_focused = (bd->Window == focused_window); ++ const bool is_app_focused = (focused_window && (bd->Window == focused_window || ImGui_ImplSDL2_GetViewportForWindowID(SDL_GetWindowID(focused_window)) != NULL)); + #else ++ SDL_Window* focused_window = bd->Window; + const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only + #endif ++ + if (is_app_focused) + { + // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) + if (io.WantSetMousePos) +- SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y); ++ { ++#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE ++ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ++ SDL_WarpMouseGlobal((int)io.MousePos.x, (int)io.MousePos.y); ++ else ++#endif ++ SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y); ++ } + + // (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured) + if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0) + { +- int window_x, window_y, mouse_x_global, mouse_y_global; +- SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); +- SDL_GetWindowPosition(bd->Window, &window_x, &window_y); +- io.AddMousePosEvent((float)(mouse_x_global - window_x), (float)(mouse_y_global - window_y)); ++ // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) ++ // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) ++ int mouse_x, mouse_y, window_x, window_y; ++ SDL_GetGlobalMouseState(&mouse_x, &mouse_y); ++ if (!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)) ++ { ++ SDL_GetWindowPosition(focused_window, &window_x, &window_y); ++ mouse_x -= window_x; ++ mouse_y -= window_y; ++ } ++ io.AddMousePosEvent((float)mouse_x, (float)mouse_y); + } + } ++ ++ // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering. ++ // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic. ++ // - [!] SDL backend does NOT correctly ignore viewports with the _NoInputs flag. ++ // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window ++ // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported ++ // by the backend, and use its flawed heuristic to guess the viewport behind. ++ // - [X] SDL backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target). ++ if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) ++ { ++ ImGuiID mouse_viewport_id = 0; ++ if (ImGuiViewport* mouse_viewport = ImGui_ImplSDL2_GetViewportForWindowID(bd->MouseWindowID)) ++ mouse_viewport_id = mouse_viewport->ID; ++ io.AddMouseViewportEvent(mouse_viewport_id); ++ } + } + + static void ImGui_ImplSDL2_UpdateMouseCursor() +@@ -751,6 +858,43 @@ static void ImGui_ImplSDL2_UpdateGamepads() + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767); + } + ++// FIXME: Note that doesn't update with DPI/Scaling change only as SDL2 doesn't have an event for it (SDL3 has). ++static void ImGui_ImplSDL2_UpdateMonitors() ++{ ++ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ++ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ++ platform_io.Monitors.resize(0); ++ bd->WantUpdateMonitors = false; ++ int display_count = SDL_GetNumVideoDisplays(); ++ for (int n = 0; n < display_count; n++) ++ { ++ // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime. ++ ImGuiPlatformMonitor monitor; ++ SDL_Rect r; ++ SDL_GetDisplayBounds(n, &r); ++ monitor.MainPos = monitor.WorkPos = ImVec2((float)r.x, (float)r.y); ++ monitor.MainSize = monitor.WorkSize = ImVec2((float)r.w, (float)r.h); ++#if SDL_HAS_USABLE_DISPLAY_BOUNDS ++ SDL_GetDisplayUsableBounds(n, &r); ++ monitor.WorkPos = ImVec2((float)r.x, (float)r.y); ++ monitor.WorkSize = ImVec2((float)r.w, (float)r.h); ++#endif ++#if SDL_HAS_PER_MONITOR_DPI ++ // FIXME-VIEWPORT: On MacOS SDL reports actual monitor DPI scale, ignoring OS configuration. We may want to set ++ // DpiScale to cocoa_window.backingScaleFactor here. ++ float dpi = 0.0f; ++ if (!SDL_GetDisplayDPI(n, &dpi, nullptr, nullptr)) ++ { ++ if (dpi <= 0.0f) ++ continue; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902. ++ monitor.DpiScale = dpi / 96.0f; ++ } ++#endif ++ monitor.PlatformHandle = (void*)(intptr_t)n; ++ platform_io.Monitors.push_back(monitor); ++ } ++} ++ + void ImGui_ImplSDL2_NewFrame() + { + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); +@@ -775,6 +919,10 @@ void ImGui_ImplSDL2_NewFrame() + if (w > 0 && h > 0) + io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); + ++ // Update monitors ++ if (bd->WantUpdateMonitors) ++ ImGui_ImplSDL2_UpdateMonitors(); ++ + // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) + // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) + static Uint64 frequency = SDL_GetPerformanceFrequency(); +@@ -791,6 +939,13 @@ void ImGui_ImplSDL2_NewFrame() + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); + } + ++ // Our io.AddMouseViewportEvent() calls will only be valid when not capturing. ++ // Technically speaking testing for 'bd->MouseButtonsDown == 0' would be more rigorous, but testing for payload reduces noise and potential side-effects. ++ if (bd->MouseCanReportHoveredViewport && ImGui::GetDragDropPayload() == nullptr) ++ io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; ++ else ++ io.BackendFlags &= ~ImGuiBackendFlags_HasMouseHoveredViewport; ++ + ImGui_ImplSDL2_UpdateMouseData(); + ImGui_ImplSDL2_UpdateMouseCursor(); + +@@ -798,10 +953,261 @@ void ImGui_ImplSDL2_NewFrame() + ImGui_ImplSDL2_UpdateGamepads(); + } + ++//-------------------------------------------------------------------------------------------------------- ++// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT ++// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. ++// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. ++//-------------------------------------------------------------------------------------------------------- ++ ++// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. ++struct ImGui_ImplSDL2_ViewportData ++{ ++ SDL_Window* Window; ++ Uint32 WindowID; ++ bool WindowOwned; ++ SDL_GLContext GLContext; ++ ++ ImGui_ImplSDL2_ViewportData() { Window = nullptr; WindowID = 0; WindowOwned = false; GLContext = nullptr; } ++ ~ImGui_ImplSDL2_ViewportData() { IM_ASSERT(Window == nullptr && GLContext == nullptr); } ++}; ++ ++static void ImGui_ImplSDL2_CreateWindow(ImGuiViewport* viewport) ++{ ++ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ++ ImGui_ImplSDL2_ViewportData* vd = IM_NEW(ImGui_ImplSDL2_ViewportData)(); ++ viewport->PlatformUserData = vd; ++ ++ ImGuiViewport* main_viewport = ImGui::GetMainViewport(); ++ ImGui_ImplSDL2_ViewportData* main_viewport_data = (ImGui_ImplSDL2_ViewportData*)main_viewport->PlatformUserData; ++ ++ // Share GL resources with main context ++ bool use_opengl = (main_viewport_data->GLContext != nullptr); ++ SDL_GLContext backup_context = nullptr; ++ if (use_opengl) ++ { ++ backup_context = SDL_GL_GetCurrentContext(); ++ SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1); ++ SDL_GL_MakeCurrent(main_viewport_data->Window, main_viewport_data->GLContext); ++ } ++ ++ Uint32 sdl_flags = 0; ++ sdl_flags |= use_opengl ? SDL_WINDOW_OPENGL : (bd->UseVulkan ? SDL_WINDOW_VULKAN : 0); ++ sdl_flags |= SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_ALLOW_HIGHDPI; ++ sdl_flags |= SDL_WINDOW_HIDDEN; ++ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? SDL_WINDOW_BORDERLESS : 0; ++ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? 0 : SDL_WINDOW_RESIZABLE; ++#if !defined(_WIN32) ++ // See SDL hack in ImGui_ImplSDL2_ShowWindow(). ++ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) ? SDL_WINDOW_SKIP_TASKBAR : 0; ++#endif ++#if SDL_HAS_ALWAYS_ON_TOP ++ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_TopMost) ? SDL_WINDOW_ALWAYS_ON_TOP : 0; ++#endif ++ vd->Window = SDL_CreateWindow("No Title Yet", (int)viewport->Pos.x, (int)viewport->Pos.y, (int)viewport->Size.x, (int)viewport->Size.y, sdl_flags); ++ vd->WindowOwned = true; ++ if (use_opengl) ++ { ++ vd->GLContext = SDL_GL_CreateContext(vd->Window); ++ SDL_GL_SetSwapInterval(0); ++ } ++ if (use_opengl && backup_context) ++ SDL_GL_MakeCurrent(vd->Window, backup_context); ++ ++ viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(vd->Window); ++ viewport->PlatformHandleRaw = nullptr; ++ SDL_SysWMinfo info; ++ SDL_VERSION(&info.version); ++ if (SDL_GetWindowWMInfo(vd->Window, &info)) ++ { ++#if defined(SDL_VIDEO_DRIVER_WINDOWS) ++ viewport->PlatformHandleRaw = info.info.win.window; ++#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA) ++ viewport->PlatformHandleRaw = (void*)info.info.cocoa.window; ++#endif ++ } ++} ++ ++static void ImGui_ImplSDL2_DestroyWindow(ImGuiViewport* viewport) ++{ ++ if (ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData) ++ { ++ if (vd->GLContext && vd->WindowOwned) ++ SDL_GL_DeleteContext(vd->GLContext); ++ if (vd->Window && vd->WindowOwned) ++ SDL_DestroyWindow(vd->Window); ++ vd->GLContext = nullptr; ++ vd->Window = nullptr; ++ IM_DELETE(vd); ++ } ++ viewport->PlatformUserData = viewport->PlatformHandle = nullptr; ++} ++ ++static void ImGui_ImplSDL2_ShowWindow(ImGuiViewport* viewport) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++#if defined(_WIN32) && !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)) ++ HWND hwnd = (HWND)viewport->PlatformHandleRaw; ++ ++ // SDL hack: Hide icon from task bar ++ // Note: SDL 2.0.6+ has a SDL_WINDOW_SKIP_TASKBAR flag which is supported under Windows but the way it create the window breaks our seamless transition. ++ if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) ++ { ++ LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ++ ex_style &= ~WS_EX_APPWINDOW; ++ ex_style |= WS_EX_TOOLWINDOW; ++ ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); ++ } ++#endif ++ ++#if SDL_HAS_SHOW_WINDOW_ACTIVATION_HINT ++ SDL_SetHint(SDL_HINT_WINDOW_NO_ACTIVATION_WHEN_SHOWN, (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) ? "1" : "0"); ++#elif defined(_WIN32) ++ // SDL hack: SDL always activate/focus windows :/ ++ if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) ++ { ++ ::ShowWindow(hwnd, SW_SHOWNA); ++ return; ++ } ++#endif ++ SDL_ShowWindow(vd->Window); ++} ++ ++static ImVec2 ImGui_ImplSDL2_GetWindowPos(ImGuiViewport* viewport) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ int x = 0, y = 0; ++ SDL_GetWindowPosition(vd->Window, &x, &y); ++ return ImVec2((float)x, (float)y); ++} ++ ++static void ImGui_ImplSDL2_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ SDL_SetWindowPosition(vd->Window, (int)pos.x, (int)pos.y); ++} ++ ++static ImVec2 ImGui_ImplSDL2_GetWindowSize(ImGuiViewport* viewport) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ int w = 0, h = 0; ++ SDL_GetWindowSize(vd->Window, &w, &h); ++ return ImVec2((float)w, (float)h); ++} ++ ++static void ImGui_ImplSDL2_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ SDL_SetWindowSize(vd->Window, (int)size.x, (int)size.y); ++} ++ ++static void ImGui_ImplSDL2_SetWindowTitle(ImGuiViewport* viewport, const char* title) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ SDL_SetWindowTitle(vd->Window, title); ++} ++ ++#if SDL_HAS_WINDOW_ALPHA ++static void ImGui_ImplSDL2_SetWindowAlpha(ImGuiViewport* viewport, float alpha) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ SDL_SetWindowOpacity(vd->Window, alpha); ++} ++#endif ++ ++static void ImGui_ImplSDL2_SetWindowFocus(ImGuiViewport* viewport) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ SDL_RaiseWindow(vd->Window); ++} ++ ++static bool ImGui_ImplSDL2_GetWindowFocus(ImGuiViewport* viewport) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; ++} ++ ++static bool ImGui_ImplSDL2_GetWindowMinimized(ImGuiViewport* viewport) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_MINIMIZED) != 0; ++} ++ ++static void ImGui_ImplSDL2_RenderWindow(ImGuiViewport* viewport, void*) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ if (vd->GLContext) ++ SDL_GL_MakeCurrent(vd->Window, vd->GLContext); ++} ++ ++static void ImGui_ImplSDL2_SwapBuffers(ImGuiViewport* viewport, void*) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ if (vd->GLContext) ++ { ++ SDL_GL_MakeCurrent(vd->Window, vd->GLContext); ++ SDL_GL_SwapWindow(vd->Window); ++ } ++} ++ ++// Vulkan support (the Vulkan renderer needs to call a platform-side support function to create the surface) ++// SDL is graceful enough to _not_ need so we can safely include this. ++#if SDL_HAS_VULKAN ++#include ++static int ImGui_ImplSDL2_CreateVkSurface(ImGuiViewport* viewport, ImU64 vk_instance, const void* vk_allocator, ImU64* out_vk_surface) ++{ ++ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData; ++ (void)vk_allocator; ++ SDL_bool ret = SDL_Vulkan_CreateSurface(vd->Window, (VkInstance)vk_instance, (VkSurfaceKHR*)out_vk_surface); ++ return ret ? 0 : 1; // ret ? VK_SUCCESS : VK_NOT_READY ++} ++#endif // SDL_HAS_VULKAN ++ ++static void ImGui_ImplSDL2_InitPlatformInterface(SDL_Window* window, void* sdl_gl_context) ++{ ++ // Register platform interface (will be coupled with a renderer interface) ++ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ++ platform_io.Platform_CreateWindow = ImGui_ImplSDL2_CreateWindow; ++ platform_io.Platform_DestroyWindow = ImGui_ImplSDL2_DestroyWindow; ++ platform_io.Platform_ShowWindow = ImGui_ImplSDL2_ShowWindow; ++ platform_io.Platform_SetWindowPos = ImGui_ImplSDL2_SetWindowPos; ++ platform_io.Platform_GetWindowPos = ImGui_ImplSDL2_GetWindowPos; ++ platform_io.Platform_SetWindowSize = ImGui_ImplSDL2_SetWindowSize; ++ platform_io.Platform_GetWindowSize = ImGui_ImplSDL2_GetWindowSize; ++ platform_io.Platform_SetWindowFocus = ImGui_ImplSDL2_SetWindowFocus; ++ platform_io.Platform_GetWindowFocus = ImGui_ImplSDL2_GetWindowFocus; ++ platform_io.Platform_GetWindowMinimized = ImGui_ImplSDL2_GetWindowMinimized; ++ platform_io.Platform_SetWindowTitle = ImGui_ImplSDL2_SetWindowTitle; ++ platform_io.Platform_RenderWindow = ImGui_ImplSDL2_RenderWindow; ++ platform_io.Platform_SwapBuffers = ImGui_ImplSDL2_SwapBuffers; ++#if SDL_HAS_WINDOW_ALPHA ++ platform_io.Platform_SetWindowAlpha = ImGui_ImplSDL2_SetWindowAlpha; ++#endif ++#if SDL_HAS_VULKAN ++ platform_io.Platform_CreateVkSurface = ImGui_ImplSDL2_CreateVkSurface; ++#endif ++ ++ // Register main window handle (which is owned by the main application, not by us) ++ // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports. ++ ImGuiViewport* main_viewport = ImGui::GetMainViewport(); ++ ImGui_ImplSDL2_ViewportData* vd = IM_NEW(ImGui_ImplSDL2_ViewportData)(); ++ vd->Window = window; ++ vd->WindowID = SDL_GetWindowID(window); ++ vd->WindowOwned = false; ++ vd->GLContext = sdl_gl_context; ++ main_viewport->PlatformUserData = vd; ++ main_viewport->PlatformHandle = (void*)(intptr_t)vd->WindowID; ++} ++ ++static void ImGui_ImplSDL2_ShutdownPlatformInterface() ++{ ++ ImGui::DestroyPlatformWindows(); ++} ++ + //----------------------------------------------------------------------------- + + #if defined(__clang__) #pragma clang diagnostic pop #endif +#endif #endif // #ifndef IMGUI_DISABLE -diff --color -rbu ./backends/imgui_impl_sdl2.h ../scummvm/scummvm/backends/imgui/backends/imgui_impl_sdl2.h ---- ./backends/imgui_impl_sdl2.h 2024-10-07 18:21:01 -+++ ../scummvm/scummvm/backends/imgui/backends/imgui_impl_sdl2.h 2024-10-07 18:30:56 -@@ -23,7 +23,7 @@ +diff --git a/backends/imgui_impl_sdl2.h b/backends/imgui_impl_sdl2.h +index e551e52a..d0313bbe 100644 +--- a/backends/imgui_impl_sdl2.h ++++ b/backends/imgui_impl_sdl2.h +@@ -8,7 +8,11 @@ + // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] + // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. + // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +-// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. ++// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. ++// Issues: ++// [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows). ++// [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). ++// [x] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. + + // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. + // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +@@ -19,7 +23,7 @@ // - Introduction, links and more at the top of imgui.cpp #pragma once @@ -133,7 +893,7 @@ diff --color -rbu ./backends/imgui_impl_sdl2.h ../scummvm/scummvm/backends/imgui #ifndef IMGUI_DISABLE struct SDL_Window; -@@ -41,6 +41,7 @@ +@@ -37,6 +41,7 @@ IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOther(SDL_Window* window); IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(); IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); @@ -141,10 +901,213 @@ diff --color -rbu ./backends/imgui_impl_sdl2.h ../scummvm/scummvm/backends/imgui // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. // When using manual mode, caller is responsible for opening/closing gamepad. -diff --color -rbu ./backends/imgui_impl_sdlrenderer2.cpp ../scummvm/scummvm/backends/imgui/backends/imgui_impl_sdlrenderer2.cpp ---- ./backends/imgui_impl_sdlrenderer2.cpp 2024-05-22 17:43:07 -+++ ../scummvm/scummvm/backends/imgui/backends/imgui_impl_sdlrenderer2.cpp 2024-10-07 18:30:56 -@@ -30,7 +30,7 @@ +diff --git a/backends/imgui_impl_sdl3.cpp b/backends/imgui_impl_sdl3.cpp +index 599d3fc4..44536554 100644 +--- a/backends/imgui_impl_sdl3.cpp ++++ b/backends/imgui_impl_sdl3.cpp +@@ -7,9 +7,10 @@ + // Implemented features: + // [X] Platform: Clipboard support. + // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +-// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] ++// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] + // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +-// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. ++// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. ++// [X] Platform: IME support. + + // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. + // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +@@ -21,6 +22,7 @@ + + // CHANGELOG + // (minor and older changes stripped away, please see git history for details) ++// 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten. + // 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807) + // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: + // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn +@@ -47,8 +49,9 @@ + // 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644) + // 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog. + +-#include "imgui.h" ++#include "backends/imgui/imgui.h" + #ifndef IMGUI_DISABLE ++#include "backends/platform/sdl/sdl.h" + #include "imgui_impl_sdl3.h" + + // Clang warnings with -Weverything +@@ -127,7 +130,7 @@ static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*) + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + const char* sdl_clipboard_text = SDL_GetClipboardText(); +- bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : NULL; ++ bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : nullptr; + return bd->ClipboardTextData; + } + +@@ -141,7 +144,7 @@ static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* view + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle; + SDL_Window* window = SDL_GetWindowFromID(window_id); +- if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != NULL) ++ if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != nullptr) + { + SDL_StopTextInput(bd->ImeWindow); + bd->ImeWindow = nullptr; +@@ -160,6 +163,7 @@ static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* view + } + + // Not static to allow third-party code to use that if they want to (but undocumented) ++ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode); + ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode) + { + // Keypad doesn't have individual key values in SDL3 +@@ -306,7 +310,7 @@ static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) + static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id) + { + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); +- return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : NULL; ++ return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : nullptr; + } + + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +@@ -324,7 +328,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) + { + case SDL_EVENT_MOUSE_MOTION: + { +- if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == NULL) ++ if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == nullptr) + return false; + ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); + io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); +@@ -333,14 +337,11 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) + } + case SDL_EVENT_MOUSE_WHEEL: + { +- if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == NULL) ++ if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == nullptr) + return false; + //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); + float wheel_x = -event->wheel.x; + float wheel_y = event->wheel.y; +- #ifdef __EMSCRIPTEN__ +- wheel_x /= 100.0f; +- #endif + io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMouseWheelEvent(wheel_x, wheel_y); + return true; +@@ -348,7 +349,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) + case SDL_EVENT_MOUSE_BUTTON_DOWN: + case SDL_EVENT_MOUSE_BUTTON_UP: + { +- if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == NULL) ++ if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == nullptr) + return false; + int mouse_button = -1; + if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } +@@ -365,7 +366,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) + } + case SDL_EVENT_TEXT_INPUT: + { +- if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == NULL) ++ if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == nullptr) + return false; + io.AddInputCharactersUTF8(event->text.text); + return true; +@@ -373,7 +374,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) + case SDL_EVENT_KEY_DOWN: + case SDL_EVENT_KEY_UP: + { +- if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == NULL) ++ if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == nullptr) + return false; + //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%d: key=%d, scancode=%d, mod=%X\n", (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP", event->key.key, event->key.scancode, event->key.mod); + ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod); +@@ -384,7 +385,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) + } + case SDL_EVENT_WINDOW_MOUSE_ENTER: + { +- if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL) ++ if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr) + return false; + bd->MouseWindowID = event->window.windowID; + bd->MousePendingLeaveFrame = 0; +@@ -396,7 +397,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) + // FIXME: Unconfirmed whether this is still needed with SDL3. + case SDL_EVENT_WINDOW_MOUSE_LEAVE: + { +- if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL) ++ if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr) + return false; + bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1; + return true; +@@ -404,7 +405,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) + case SDL_EVENT_WINDOW_FOCUS_GAINED: + case SDL_EVENT_WINDOW_FOCUS_LOST: + { +- if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL) ++ if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr) + return false; + io.AddFocusEvent(event->type == SDL_EVENT_WINDOW_FOCUS_GAINED); + return true; +@@ -573,7 +574,7 @@ static void ImGui_ImplSDL3_UpdateMouseData() + #endif + if (is_app_focused) + { +- // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) ++ // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user) + if (io.WantSetMousePos) + SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y); + +diff --git a/backends/imgui_impl_sdl3.h b/backends/imgui_impl_sdl3.h +index 880ba961..6483fb5d 100644 +--- a/backends/imgui_impl_sdl3.h ++++ b/backends/imgui_impl_sdl3.h +@@ -7,9 +7,10 @@ + // Implemented features: + // [X] Platform: Clipboard support. + // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +-// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] ++// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5] + // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +-// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. ++// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. ++// [X] Platform: IME support. + + // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. + // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +@@ -20,7 +21,7 @@ + // - Introduction, links and more at the top of imgui.cpp + + #pragma once +-#include "imgui.h" // IMGUI_IMPL_API ++#include "backends/imgui/imgui.h" // IMGUI_IMPL_API + #ifndef IMGUI_DISABLE + + struct SDL_Window; +@@ -42,6 +43,6 @@ IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event); + // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. + // When using manual mode, caller is responsible for opening/closing gamepad. + enum ImGui_ImplSDL3_GamepadMode { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual }; +-IMGUI_IMPL_API void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = NULL, int manual_gamepads_count = -1); ++IMGUI_IMPL_API void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = nullptr, int manual_gamepads_count = -1); + + #endif // #ifndef IMGUI_DISABLE +diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp +index 3d538dfe..c385a0da 100644 +--- a/backends/imgui_impl_sdlrenderer2.cpp ++++ b/backends/imgui_impl_sdlrenderer2.cpp +@@ -10,6 +10,8 @@ + // Implemented features: + // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! + // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. ++// Missing features: ++// [ ] Renderer: Multi-viewport support (multiple windows). + + // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. + // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +@@ -28,7 +30,7 @@ // 2021-10-06: Backup and restore modified ClipRect/Viewport. // 2021-09-21: Initial version. @@ -153,10 +1116,20 @@ diff --color -rbu ./backends/imgui_impl_sdlrenderer2.cpp ../scummvm/scummvm/back #ifndef IMGUI_DISABLE #include "imgui_impl_sdlrenderer2.h" #include // intptr_t -diff --color -rbu ./backends/imgui_impl_sdlrenderer2.h ../scummvm/scummvm/backends/imgui/backends/imgui_impl_sdlrenderer2.h ---- ./backends/imgui_impl_sdlrenderer2.h 2024-10-07 18:21:01 -+++ ../scummvm/scummvm/backends/imgui/backends/imgui_impl_sdlrenderer2.h 2024-10-07 18:30:56 -@@ -22,8 +22,8 @@ +diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h +index c067eaee..ce00c5c6 100644 +--- a/backends/imgui_impl_sdlrenderer2.h ++++ b/backends/imgui_impl_sdlrenderer2.h +@@ -10,6 +10,8 @@ + // Implemented features: + // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! + // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. ++// Missing features: ++// [ ] Renderer: Multi-viewport support (multiple windows). + + // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. + // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +@@ -20,8 +22,8 @@ // - Introduction, links and more at the top of imgui.cpp #pragma once @@ -166,25 +1139,9981 @@ diff --color -rbu ./backends/imgui_impl_sdlrenderer2.h ../scummvm/scummvm/backen struct SDL_Renderer; -diff --color -rbu ./imgui.h ../scummvm/scummvm/backends/imgui/imgui.h ---- ./imgui.h 2024-10-07 18:21:01 -+++ ../scummvm/scummvm/backends/imgui/imgui.h 2024-10-07 18:30:56 -@@ -105,8 +105,10 @@ - #define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) - #define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) - #elif !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__)) --#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) --#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) -+//#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) -+//#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) -+#define IM_FMTARGS(FMT) -+#define IM_FMTLIST(FMT) - #else - #define IM_FMTARGS(FMT) - #define IM_FMTLIST(FMT) -diff --color -rbu ./misc/freetype/imgui_freetype.cpp ../scummvm/scummvm/backends/imgui/misc/freetype/imgui_freetype.cpp ---- ./misc/freetype/imgui_freetype.cpp 2024-10-07 18:21:01 -+++ ../scummvm/scummvm/backends/imgui/misc/freetype/imgui_freetype.cpp 2024-10-07 18:32:37 +diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp +index 30f967bd..153d4b76 100644 +--- a/backends/imgui_impl_sdlrenderer3.cpp ++++ b/backends/imgui_impl_sdlrenderer3.cpp +@@ -27,7 +27,7 @@ + // 2024-02-12: Amend to query SDL_RenderViewportSet() and restore viewport accordingly. + // 2023-05-30: Initial version. + +-#include "imgui.h" ++#include "backends/imgui/imgui.h" + #ifndef IMGUI_DISABLE + #include "imgui_impl_sdlrenderer3.h" + #include // intptr_t +diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h +index 6c23deca..6529469c 100644 +--- a/backends/imgui_impl_sdlrenderer3.h ++++ b/backends/imgui_impl_sdlrenderer3.h +@@ -22,7 +22,7 @@ + // - Introduction, links and more at the top of imgui.cpp + + #pragma once +-#include "imgui.h" // IMGUI_IMPL_API ++#include "backends/imgui/imgui.h" // IMGUI_IMPL_API + #ifndef IMGUI_DISABLE + + struct SDL_Renderer; +diff --git a/imconfig.h b/imconfig.h +index b8d55842..d6f0587d 100644 +--- a/imconfig.h ++++ b/imconfig.h +@@ -28,8 +28,8 @@ + //#define IMGUI_API __attribute__((visibility("default"))) // GCC/Clang: override visibility when set is hidden + + //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names. +-//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS +-//#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87+ disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This is automatically done by IMGUI_DISABLE_OBSOLETE_FUNCTIONS. ++#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS ++#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87+ disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This is automatically done by IMGUI_DISABLE_OBSOLETE_FUNCTIONS. + + //---- Disable all of Dear ImGui or don't implement standard windows/tools. + // It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp. +@@ -43,7 +43,7 @@ + //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) + //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME). + //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). +-//#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")). ++#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")). + //#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) + //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. + //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) +diff --git a/imgui.cpp b/imgui.cpp +index 3bbaf018..5b139e30 100644 +--- a/imgui.cpp ++++ b/imgui.cpp +@@ -91,6 +91,7 @@ CODE + // [SECTION] SETTINGS + // [SECTION] LOCALIZATION + // [SECTION] VIEWPORTS, PLATFORM WINDOWS ++// [SECTION] DOCKING + // [SECTION] PLATFORM DEPENDENT HELPERS + // [SECTION] METRICS/DEBUGGER WINDOW + // [SECTION] DEBUG LOG WINDOW +@@ -430,6 +431,13 @@ CODE + When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. + You can read releases logs https://github.com/ocornut/imgui/releases for more details. + ++(Docking/Viewport Branch) ++ - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that: ++ - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore. ++ you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos) ++ - likewise io.MousePos and GetMousePos() will use OS coordinates. ++ If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos. ++ + - 2024/10/03 (1.91.3) - drags: treat v_min==v_max as a valid clamping range when != 0.0f. Zero is a still special value due to legacy reasons, unless using ImGuiSliderFlags_ClampZeroRange. (#7968, #3361, #76) + - drags: extended behavior of ImGuiSliderFlags_AlwaysClamp to include _ClampZeroRange. It considers v_min==v_max==0.0f as a valid clamping range (aka edits not allowed). + although unlikely, it you wish to only clamp on text input but want v_min==v_max==0.0f to mean unclamped drags, you can use _ClampOnInput instead of _AlwaysClamp. (#7968, #3361, #76) +@@ -494,6 +502,9 @@ CODE + - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0); + for various reasons those changes makes sense. They are being made because making some of those API public. + only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL. ++ - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611) ++ - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...); ++ - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...); + - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys. + - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps. + - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456) +@@ -1145,6 +1156,9 @@ static const ImVec2 TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10); // Multi + static const ImVec2 TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20); // Multiplied by g.Style.MouseCursorScale + static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multiplied by g.Style.MouseCursorScale + ++// Docking ++static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport. ++ + //------------------------------------------------------------------------- + // [SECTION] FORWARD DECLARATIONS + //------------------------------------------------------------------------- +@@ -1219,7 +1233,18 @@ static void SetLastItemDataForWindow(ImGuiWindow* window, const ImRe + + // Viewports + const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter. ++static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags); ++static void DestroyViewport(ImGuiViewportP* viewport); + static void UpdateViewportsNewFrame(); ++static void UpdateViewportsEndFrame(); ++static void WindowSelectViewport(ImGuiWindow* window); ++static void WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack); ++static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport); ++static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window); ++static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window); ++static int FindPlatformMonitorForPos(const ImVec2& pos); ++static int FindPlatformMonitorForRect(const ImRect& r); ++static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport); + + } + +@@ -1312,6 +1337,7 @@ ImGuiStyle::ImGuiStyle() + SeparatorTextPadding = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. + DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. + DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. ++ DockingSeparatorSize = 2.0f; // Thickness of resizing border between docked windows + MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. + AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). +@@ -1356,6 +1382,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) + TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX; + TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor); + SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor); ++ DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor); + DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor); + DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor); + MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor); +@@ -1387,6 +1414,18 @@ ImGuiIO::ImGuiIO() + FontAllowUserScaling = false; + DisplayFramebufferScale = ImVec2(1.0f, 1.0f); + ++ // Docking options (when ImGuiConfigFlags_DockingEnable is set) ++ ConfigDockingNoSplit = false; ++ ConfigDockingWithShift = false; ++ ConfigDockingAlwaysTabBar = false; ++ ConfigDockingTransparentPayload = false; ++ ++ // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) ++ ConfigViewportsNoAutoMerge = false; ++ ConfigViewportsNoTaskBarIcon = false; ++ ConfigViewportsNoDecoration = true; ++ ConfigViewportsNoDefaultParent = false; ++ + // Miscellaneous options + MouseDrawCursor = false; + #ifdef __APPLE__ +@@ -1773,6 +1812,27 @@ void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source) + g.InputEventsNextMouseSource = source; + } + ++void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id) ++{ ++ IM_ASSERT(Ctx != NULL); ++ ImGuiContext& g = *Ctx; ++ //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport); ++ if (!AppAcceptingEvents) ++ return; ++ ++ // Filter duplicate ++ const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport); ++ const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport; ++ if (latest_viewport_id == viewport_id) ++ return; ++ ++ ImGuiInputEvent e; ++ e.Type = ImGuiInputEventType_MouseViewport; ++ e.Source = ImGuiInputSource_Mouse; ++ e.MouseViewport.HoveredViewportID = viewport_id; ++ g.InputEventsQueue.push_back(e); ++} ++ + void ImGuiIO::AddFocusEvent(bool focused) + { + IM_ASSERT(Ctx != NULL); +@@ -3297,6 +3357,11 @@ void ImGui::PopStyleColor(int count) + } + } + ++static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] = ++{ ++ ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline, ++}; ++ + static const ImGuiDataVarInfo GStyleVarInfo[] = + { + { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha +@@ -3332,6 +3397,7 @@ static const ImGuiDataVarInfo GStyleVarInfo[] = + { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)}, // ImGuiStyleVar_SeparatorTextBorderSize + { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign + { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding ++ { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) }, // ImGuiStyleVar_DockingSeparatorSize + }; + + const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx) +@@ -3463,6 +3529,8 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) + case ImGuiCol_TabDimmed: return "TabDimmed"; + case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected"; + case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline"; ++ case ImGuiCol_DockingPreview: return "DockingPreview"; ++ case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg"; + case ImGuiCol_PlotLines: return "PlotLines"; + case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; + case ImGuiCol_PlotHistogram: return "PlotHistogram"; +@@ -3725,7 +3793,7 @@ void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCurso + if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2])) + continue; + const ImVec2 pos = base_pos - offset; +- const float scale = base_scale; ++ const float scale = base_scale * viewport->DpiScale; + if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale))) + continue; + ImDrawList* draw_list = GetForegroundDrawList(viewport); +@@ -3809,6 +3877,9 @@ static const ImGuiLocEntry GLocalizationEntriesEnUS[] = + { ImGuiLocKey_WindowingUntitled, "(Untitled)" }, + { ImGuiLocKey_OpenLink_s, "Open '%s'" }, + { ImGuiLocKey_CopyLink, "Copy Link###CopyLink" }, ++ { ImGuiLocKey_DockingHideTabBar, "Hide tab bar###HideTabBar" }, ++ { ImGuiLocKey_DockingHoldShiftToDock, "Hold SHIFT to enable Docking window." }, ++ { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node." }, + }; + + ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) +@@ -3817,13 +3888,14 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) + InputTextState.Ctx = this; + + Initialized = false; ++ ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None; + FontAtlasOwnedByContext = shared_font_atlas ? false : true; + Font = NULL; + FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f; + IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); + Time = 0.0f; + FrameCount = 0; +- FrameCountEnded = FrameCountRendered = -1; ++ FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1; + WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false; + GcCompactAll = false; + TestEngineHookItems = false; +@@ -3881,6 +3953,12 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) + CurrentItemFlags = ImGuiItemFlags_None; + DebugShowGroupRects = false; + ++ CurrentViewport = NULL; ++ MouseViewport = MouseLastHoveredViewport = NULL; ++ PlatformLastFocusedViewportId = 0; ++ ViewportCreatedCount = PlatformWindowsCreatedCount = 0; ++ ViewportFocusedStampCount = 0; ++ + NavWindow = NULL; + NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0; + NavLayer = ImGuiNavLayer_Main; +@@ -3975,6 +4053,9 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) + + PlatformImeData.InputPos = ImVec2(0.0f, 0.0f); + PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission ++ PlatformImeViewport = 0; ++ ++ DockNodeWindowMenuHandler = NULL; + + SettingsLoaded = false; + SettingsDirtyTimer = 0.0f; +@@ -4010,6 +4091,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) + DebugItemPickerBreakId = 0; + DebugFlashStyleColorTime = 0.0f; + DebugFlashStyleColorIdx = ImGuiCol_COUNT; ++ DebugHoveredDockNode = NULL; + + // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations + DebugBreakInWindow = 0; +@@ -4056,8 +4138,13 @@ void ImGui::Initialize() + // Create default viewport + ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)(); + viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID; ++ viewport->Idx = 0; ++ viewport->PlatformWindowCreated = true; ++ viewport->Flags = ImGuiViewportFlags_OwnedByApp; + g.Viewports.push_back(viewport); + g.TempBuffer.resize(1024 * 3 + 1, 0); ++ g.ViewportCreatedCount++; ++ g.PlatformIO.Viewports.push_back(g.Viewports[0]); + + // Build KeysMayBeCharInput[] lookup table (1 bool per named key) + for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) +@@ -4068,6 +4155,8 @@ void ImGui::Initialize() + g.KeysMayBeCharInput.SetBit(key); + + #ifdef IMGUI_HAS_DOCK ++ // Initialize Docking ++ DockContextInitialize(&g); + #endif + + g.Initialized = true; +@@ -4097,6 +4186,12 @@ void ImGui::Shutdown() + if (g.SettingsLoaded && g.IO.IniFilename != NULL) + SaveIniSettingsToDisk(g.IO.IniFilename); + ++ // Destroy platform windows ++ DestroyPlatformWindows(); ++ ++ // Shutdown extensions ++ DockContextShutdown(&g); ++ + CallContextHooks(&g, ImGuiContextHookType_Shutdown); + + // Clear everything else +@@ -4120,6 +4215,7 @@ void ImGui::Shutdown() + g.BeginPopupStack.clear(); + g.TreeNodeStack.clear(); + ++ g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL; + g.Viewports.clear_delete(); + + g.TabBars.Clear(); +@@ -4202,21 +4298,27 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NUL + NameBufLen = (int)strlen(name) + 1; + ID = ImHashStr(name); + IDStack.push_back(ID); ++ ViewportAllowPlatformMonitorExtend = -1; ++ ViewportPos = ImVec2(FLT_MAX, FLT_MAX); + MoveId = GetID("#MOVE"); ++ TabId = GetID("#TAB"); + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); + AutoFitFramesX = AutoFitFramesY = -1; + AutoPosLastDirection = ImGuiDir_None; +- SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = 0; ++ SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0; + SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); + LastFrameActive = -1; ++ LastFrameJustFocused = -1; + LastTimeActive = -1.0f; +- FontWindowScale = 1.0f; ++ FontWindowScale = FontDpiScale = 1.0f; + SettingsOffset = -1; ++ DockOrder = -1; + DrawList = &DrawListInst; + DrawList->_Data = &Ctx->DrawListSharedData; + DrawList->_OwnerName = Name; + NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX); ++ IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass(); + } + + ImGuiWindow::~ImGuiWindow() +@@ -4232,7 +4334,6 @@ static void SetCurrentWindow(ImGuiWindow* window) + g.CurrentWindow = window; + g.StackSizesInBeginForCurrentWindow = g.CurrentWindow ? &g.CurrentWindowStack.back().StackSizesInBegin : NULL; + g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL; +- g.CurrentDpiScale = 1.0f; // FIXME-DPI: WIP this is modified in docking + if (window) + { + g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); +@@ -4381,8 +4482,8 @@ bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flag + // FIXME-OPT: This could be cached/stored within the window. + ImGuiContext& g = *GImGui; + if (g.NavWindow) +- if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow) +- if (focused_root_window->WasActive && focused_root_window != window->RootWindow) ++ if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree) ++ if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree) + { + // For the purpose of those flags we differentiate "standard popup" from "modal popup" + // NB: The 'else' is important because Modal windows are also Popups. +@@ -4397,6 +4498,12 @@ bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flag + if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window)) + return false; + } ++ ++ // Filter by viewport ++ if (window->Viewport != g.MouseViewport) ++ if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree) ++ return false; ++ + return true; + } + +@@ -4447,7 +4554,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) + if (flags & ImGuiHoveredFlags_ForTooltip) + flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse); + +- IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy)) == 0); // Flags not supported by this function ++ IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0); // Flags not supported by this function + + // Done with rectangle culling so we can perform heavier checks now + // Test if we are hovering the right window (our window could be behind another window) +@@ -4463,7 +4570,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) + const ImGuiID id = g.LastItemData.ID; + if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0) + if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) +- if (g.ActiveId != window->MoveId) ++ if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId) + return false; + + // Test if interactions on this window are blocked by an active popup or modal. +@@ -4776,26 +4883,18 @@ static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t draw + + ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport) + { ++ if (viewport == NULL) ++ viewport = GImGui->CurrentWindow->Viewport; + return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background"); + } + +-ImDrawList* ImGui::GetBackgroundDrawList() +-{ +- ImGuiContext& g = *GImGui; +- return GetBackgroundDrawList(g.Viewports[0]); +-} +- + ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport) + { ++ if (viewport == NULL) ++ viewport = GImGui->CurrentWindow->Viewport; + return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground"); + } + +-ImDrawList* ImGui::GetForegroundDrawList() +-{ +- ImGuiContext& g = *GImGui; +- return GetForegroundDrawList(g.Viewports[0]); +-} +- + ImDrawListSharedData* ImGui::GetDrawListSharedData() + { + return &GImGui->DrawListSharedData; +@@ -4810,17 +4909,43 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) + FocusWindow(window); + SetActiveID(window->MoveId, window); + g.NavDisableHighlight = true; +- g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos; ++ g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos; + g.ActiveIdNoClearOnFocusLoss = true; + SetActiveIdUsingAllKeyboardKeys(); + + bool can_move_window = true; +- if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove)) ++ if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove)) + can_move_window = false; ++ if (ImGuiDockNode* node = window->DockNodeAsHost) ++ if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove)) ++ can_move_window = false; + if (can_move_window) + g.MovingWindow = window; + } + ++// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them. ++void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock) ++{ ++ ImGuiContext& g = *GImGui; ++ bool can_undock_node = false; ++ if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0) ++ { ++ // Can undock if: ++ // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window) ++ // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows) ++ ImGuiDockNode* root_node = DockNodeGetRootNode(node); ++ if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that. ++ can_undock_node = true; ++ } ++ ++ const bool clicked = IsMouseClicked(0); ++ const bool dragging = IsMouseDragging(0); ++ if (can_undock_node && dragging) ++ DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame ++ else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window) ++ StartMouseMovingWindow(window); ++} ++ + // Handle mouse moving window + // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing() + // FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId. +@@ -4834,16 +4959,43 @@ void ImGui::UpdateMouseMovingWindowNewFrame() + // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). + // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency. + KeepAliveID(g.ActiveId); +- IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow); +- ImGuiWindow* moving_window = g.MovingWindow->RootWindow; +- if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos)) ++ IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree); ++ ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree; ++ ++ // When a window stop being submitted while being dragged, it may will its viewport until next Begin() ++ const bool window_disappared = (!moving_window->WasActive && !moving_window->Active); ++ if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared) + { + ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset; +- SetWindowPos(moving_window, pos, ImGuiCond_Always); ++ if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y) ++ { ++ SetWindowPos(moving_window, pos, ImGuiCond_Always); ++ if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window. ++ { ++ moving_window->Viewport->Pos = pos; ++ moving_window->Viewport->UpdateWorkRect(); ++ } ++ } + FocusWindow(g.MovingWindow); + } + else + { ++ if (!window_disappared) ++ { ++ // Try to merge the window back into the main viewport. ++ // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports) ++ if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) ++ UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport); ++ ++ // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button. ++ if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted()) ++ g.MouseViewport = moving_window->Viewport; ++ ++ // Clear the NoInput window flag set by the Viewport system ++ if (moving_window->Viewport) ++ moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; ++ } ++ + g.MovingWindow = NULL; + ClearActiveID(); + } +@@ -4873,7 +5025,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() + return; + + // Click on empty space to focus window and start moving +- // (after we're done with all our widgets) ++ // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!) + if (g.IO.MouseClicked[0]) + { + // Handle the edge case of a popup being closed while clicking in its empty space. +@@ -4887,7 +5039,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() + + // Cancel moving if clicked outside of title bar + if (g.IO.ConfigWindowsMoveFromTitleBarOnly) +- if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) ++ if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive) + if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) + g.MovingWindow = NULL; + +@@ -4915,6 +5067,29 @@ void ImGui::UpdateMouseMovingWindowEndFrame() + } + } + ++// This is called during NewFrame()->UpdateViewportsNewFrame() only. ++// Need to keep in sync with SetWindowPos() ++static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta) ++{ ++ window->Pos += delta; ++ window->ClipRect.Translate(delta); ++ window->OuterRectClipped.Translate(delta); ++ window->InnerRect.Translate(delta); ++ window->DC.CursorPos += delta; ++ window->DC.CursorStartPos += delta; ++ window->DC.CursorMaxPos += delta; ++ window->DC.IdealMaxPos += delta; ++} ++ ++static void ScaleWindow(ImGuiWindow* window, float scale) ++{ ++ ImVec2 origin = window->Viewport->Pos; ++ window->Pos = ImFloor((window->Pos - origin) * scale + origin); ++ window->Size = ImTrunc(window->Size * scale); ++ window->SizeFull = ImTrunc(window->SizeFull * scale); ++ window->ContentSize = ImTrunc(window->ContentSize * scale); ++} ++ + static bool IsWindowActiveAndVisible(ImGuiWindow* window) + { + return (window->Active) && (!window->Hidden); +@@ -4936,11 +5111,12 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() + // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. + bool clear_hovered_windows = false; + FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow); ++ IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport); + g.HoveredWindowBeforeClear = g.HoveredWindow; + + // Modal windows prevents mouse from hovering behind them. + ImGuiWindow* modal_window = GetTopMostPopupModal(); +- if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) ++ if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ? + clear_hovered_windows = true; + + // Disabled mouse hovering (we don't currently clear MousePos, we could) +@@ -5035,7 +5211,9 @@ void ImGui::NewFrame() + CallContextHooks(&g, ImGuiContextHookType_NewFramePre); + + // Check and assert for various common IO and Configuration mistakes ++ g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame; + ErrorCheckNewFrameSanityChecks(); ++ g.ConfigFlagsCurrFrame = g.IO.ConfigFlags; + + // Load settings on first frame, save settings when modified (after a delay) + UpdateSettings(); +@@ -5062,6 +5240,7 @@ void ImGui::NewFrame() + UpdateViewportsNewFrame(); + + // Setup current font and draw list shared data ++ // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! + g.IO.Fonts->Locked = true; + SetupDrawListSharedData(); + SetCurrentFont(GetDefaultFont()); +@@ -5069,7 +5248,10 @@ void ImGui::NewFrame() + + // Mark rendering data as invalid to prevent user who may have a handle on it to use it. + for (ImGuiViewportP* viewport : g.Viewports) ++ { ++ viewport->DrawData = NULL; + viewport->DrawDataP.Valid = false; ++ } + + // Drag and drop keep the source ID alive so even if the source disappear our state is consistent + if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId) +@@ -5180,6 +5362,10 @@ void ImGui::NewFrame() + // Update mouse input state + UpdateMouseInputs(); + ++ // Undocking ++ // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame) ++ DockContextNewFrameUpdateUndocking(&g); ++ + // Mark all windows as not visible and compact unused memory. + IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size); + const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer; +@@ -5244,6 +5430,9 @@ void ImGui::NewFrame() + g.CurrentItemFlags = g.ItemFlagsStack.back(); + g.GroupStack.resize(0); + ++ // Docking ++ DockContextNewFrameUpdateDocking(&g); ++ + // [DEBUG] Update debug features + #ifndef IMGUI_DISABLE_DEBUG_TOOLS + UpdateDebugToolItemPicker(); +@@ -5317,7 +5506,8 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im + static void AddWindowToDrawData(ImGuiWindow* window, int layer) + { + ImGuiContext& g = *GImGui; +- ImGuiViewportP* viewport = g.Viewports[0]; ++ ImGuiViewportP* viewport = window->Viewport; ++ IM_ASSERT(viewport != NULL); + g.IO.MetricsRenderWindows++; + if (window->DrawList->_Splitter._Count > 1) + window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows. +@@ -5361,17 +5551,25 @@ static void InitViewportDrawData(ImGuiViewportP* viewport) + ImGuiIO& io = ImGui::GetIO(); + ImDrawData* draw_data = &viewport->DrawDataP; + ++ viewport->DrawData = draw_data; // Make publicly accessible + viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists; + viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1; + viewport->DrawDataBuilder.Layers[0]->resize(0); + viewport->DrawDataBuilder.Layers[1]->resize(0); + ++ // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode, ++ // and to allow applications/backends to easily skip rendering. ++ // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure. ++ // This is because the work has been done already, and its wasted! We should fix that and add optimizations for ++ // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline. ++ const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0; ++ + draw_data->Valid = true; + draw_data->CmdListsCount = 0; + draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; + draw_data->DisplayPos = viewport->Pos; +- draw_data->DisplaySize = viewport->Size; +- draw_data->FramebufferScale = io.DisplayFramebufferScale; ++ draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size; ++ draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis? + draw_data->OwnerViewport = viewport; + } + +@@ -5397,20 +5595,28 @@ void ImGui::PopClipRect() + window->ClipRect = window->DrawList->_ClipRectStack.back(); + } + ++static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window) ++{ ++ for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--) ++ if (IsWindowActiveAndVisible(window->DC.ChildWindows[n])) ++ return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]); ++ return window; ++} ++ + static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col) + { + if ((col & IM_COL32_A_MASK) == 0) + return; + +- ImGuiViewportP* viewport = (ImGuiViewportP*)GetMainViewport(); ++ ImGuiViewportP* viewport = window->Viewport; + ImRect viewport_rect = viewport->GetMainRect(); + + // Draw behind window by moving the draw command at the FRONT of the draw list + { +- // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows, +- // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing. ++ // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing. + // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order. +- ImDrawList* draw_list = window->RootWindow->DrawList; ++ ImDrawList* draw_list = window->RootWindowDockTree->DrawList; ++ draw_list->ChannelsMerge(); + if (draw_list->CmdBuffer.Size == 0) + draw_list->AddDrawCmd(); + draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that) +@@ -5422,6 +5628,18 @@ static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 + draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command. + draw_list->PopClipRect(); + } ++ ++ // Draw over sibling docking nodes in a same docking tree ++ if (window->RootWindow->DockIsActive) ++ { ++ ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList; ++ draw_list->ChannelsMerge(); ++ if (draw_list->CmdBuffer.Size == 0) ++ draw_list->AddDrawCmd(); ++ draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false); ++ RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding); ++ draw_list->PopClipRect(); ++ } + } + + ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window) +@@ -5441,6 +5659,8 @@ ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* par + return bottom_most_visible_window; + } + ++// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage. ++// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds(). + static void ImGui::RenderDimmedBackgrounds() + { + ImGuiContext& g = *GImGui; +@@ -5452,31 +5672,50 @@ static void ImGui::RenderDimmedBackgrounds() + if (!dim_bg_for_modal && !dim_bg_for_window_list) + return; + ++ ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL }; + if (dim_bg_for_modal) + { + // Draw dimming behind modal or a begin stack child, whichever comes first in draw order. + ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window); + RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio)); ++ viewports_already_dimmed[0] = modal_window->Viewport; + } + else if (dim_bg_for_window_list) + { + // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window + RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio)); ++ if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport) ++ RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio)); ++ viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport; ++ viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL; + + // Draw border around CTRL+Tab target window + ImGuiWindow* window = g.NavWindowingTargetAnim; +- ImGuiViewport* viewport = GetMainViewport(); ++ ImGuiViewport* viewport = window->Viewport; + float distance = g.FontSize; + ImRect bb = window->Rect(); + bb.Expand(distance); + if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y) + bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward ++ window->DrawList->ChannelsMerge(); + if (window->DrawList->CmdBuffer.Size == 0) + window->DrawList->AddDrawCmd(); + window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size); + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); + window->DrawList->PopClipRect(); + } ++ ++ // Draw dimming background on _other_ viewports than the ones our windows are in ++ for (ImGuiViewportP* viewport : g.Viewports) ++ { ++ if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1]) ++ continue; ++ if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window)) ++ continue; ++ ImDrawList* draw_list = GetForegroundDrawList(viewport); ++ const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio); ++ draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col); ++ } + } + + // This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. +@@ -5502,8 +5741,10 @@ void ImGui::EndFrame() + ImGuiPlatformImeData* ime_data = &g.PlatformImeData; + if (g.PlatformIO.Platform_SetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) + { ++ ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport); + IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y); +- ImGuiViewport* viewport = GetMainViewport(); ++ if (viewport == NULL) ++ viewport = GetMainViewport(); + g.PlatformIO.Platform_SetImeDataFn(&g, viewport, ime_data); + } + +@@ -5516,6 +5757,11 @@ void ImGui::EndFrame() + // Update navigation: CTRL+Tab, wrap-around requests + NavEndFrame(); + ++ // Update docking ++ DockContextEndFrame(&g); ++ ++ SetCurrentViewport(NULL, NULL); ++ + // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted) + if (g.DragDropActive) + { +@@ -5544,6 +5790,9 @@ void ImGui::EndFrame() + // Initiate moving window + handle left-click and right-click focus + UpdateMouseMovingWindowEndFrame(); + ++ // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) ++ UpdateViewportsEndFrame(); ++ + // Sort the window list so that all child windows are after their parent + // We cannot do that on FocusWindow() because children may not exist yet + g.WindowsTempSortBuffer.resize(0); +@@ -5602,7 +5851,7 @@ void ImGui::Render() + + // Add ImDrawList to render + ImGuiWindow* windows_to_render_top_most[2]; +- windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; ++ windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL; + windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL); + for (ImGuiWindow* window : g.Windows) + { +@@ -5681,8 +5930,15 @@ void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_vi + ImGuiWindow* hovered_window = NULL; + ImGuiWindow* hovered_window_under_moving_window = NULL; + +- if (find_first_and_in_any_viewport == false && g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs)) +- hovered_window = g.MovingWindow; ++ // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame) ++ ImGuiViewportP* backup_moving_window_viewport = NULL; ++ if (find_first_and_in_any_viewport == false && g.MovingWindow) ++ { ++ backup_moving_window_viewport = g.MovingWindow->Viewport; ++ g.MovingWindow->Viewport = g.MouseViewport; ++ if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs)) ++ hovered_window = g.MovingWindow; ++ } + + ImVec2 padding_regular = g.Style.TouchExtraPadding; + ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular; +@@ -5694,6 +5950,9 @@ void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_vi + continue; + if (window->Flags & ImGuiWindowFlags_NoMouseInputs) + continue; ++ IM_ASSERT(window->Viewport); ++ if (window->Viewport != g.MouseViewport) ++ continue; + + // Using the clipped AABB, a child window will typically be clipped by its parent (not always) + ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize; +@@ -5720,7 +5979,7 @@ void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_vi + if (hovered_window == NULL) + hovered_window = window; + IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer. +- if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow)) ++ if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)) + hovered_window_under_moving_window = window; + if (hovered_window && hovered_window_under_moving_window) + break; +@@ -5730,6 +5989,8 @@ void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_vi + *out_hovered_window = hovered_window; + if (out_hovered_window_under_moving_window != NULL) + *out_hovered_window_under_moving_window = hovered_window_under_moving_window; ++ if (find_first_and_in_any_viewport == false && g.MovingWindow) ++ g.MovingWindow->Viewport = backup_moving_window_viewport; + } + + bool ImGui::IsItemActive() +@@ -5769,6 +6030,13 @@ bool ImGui::IsItemFocused() + ImGuiContext& g = *GImGui; + if (g.NavId != g.LastItemData.ID || g.NavId == 0) + return false; ++ ++ // Special handling for the dummy item after Begin() which represent the title bar or tab. ++ // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. ++ ImGuiWindow* window = g.CurrentWindow; ++ if (g.LastItemData.ID == window->ID && window->WriteAccessed) ++ return false; ++ + return true; + } + +@@ -5929,7 +6197,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, I + child_flags &= ~ImGuiChildFlags_ResizeY; + + // Set window flags +- window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar; ++ window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking; + window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag + if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize)) + window_flags |= ImGuiWindowFlags_AlwaysAutoResize; +@@ -6076,6 +6344,7 @@ static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, b + window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags); + window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags); + window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags); ++ window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags); + } + + ImGuiWindow* ImGui::FindWindowByID(ImGuiID id) +@@ -6092,10 +6361,19 @@ ImGuiWindow* ImGui::FindWindowByName(const char* name) + + static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings) + { +- window->Pos = ImTrunc(ImVec2(settings->Pos.x, settings->Pos.y)); ++ const ImGuiViewport* main_viewport = ImGui::GetMainViewport(); ++ window->ViewportPos = main_viewport->Pos; ++ if (settings->ViewportId) ++ { ++ window->ViewportId = settings->ViewportId; ++ window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y); ++ } ++ window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y)); + if (settings->Size.x > 0 && settings->Size.y > 0) + window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y)); + window->Collapsed = settings->Collapsed; ++ window->DockId = settings->DockId; ++ window->DockOrder = settings->DockOrder; + } + + static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags) +@@ -6128,7 +6406,8 @@ static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* s + const ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + window->Pos = main_viewport->Pos + ImVec2(60, 60); + window->Size = window->SizeFull = ImVec2(0, 0); +- window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; ++ window->ViewportPos = main_viewport->Pos; ++ window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; + + if (settings != NULL) + { +@@ -6176,6 +6455,16 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) + return window; + } + ++static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window) ++{ ++ return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window; ++} ++ ++static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window) ++{ ++ return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window; ++} ++ + static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window) + { + // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) +@@ -6195,7 +6484,7 @@ static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window) + } + + // Reduce artifacts with very small windows +- ImGuiWindow* window_for_height = window; ++ ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window); + size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); + return size_min; + } +@@ -6266,8 +6555,19 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont + { + // Maximum window size is determined by the viewport size or monitor size + ImVec2 size_min = CalcWindowMinSize(window); +- ImVec2 size_max = ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup)) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f; +- ImVec2 size_auto_fit = ImClamp(size_desired, size_min, size_max); ++ ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX); ++ ++ // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction ++ if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0) ++ { ++ if (!window->ViewportOwned) ++ size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f; ++ const int monitor_idx = window->ViewportAllowPlatformMonitorExtend; ++ if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size) ++ size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f; ++ } ++ ++ ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max)); + + // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars, + // we may need to compute/store three variants of size_auto_fit, for x/y/xy. +@@ -6304,7 +6604,7 @@ static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window) + { + if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) + return ImGuiCol_PopupBg; +- if (window->Flags & ImGuiWindowFlags_ChildWindow) ++ if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive) + return ImGuiCol_ChildBg; + return ImGuiCol_WindowBg; + } +@@ -6370,7 +6670,7 @@ static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_ + ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n) + { + IM_ASSERT(n >= 0 && n < 4); +- ImGuiID id = window->ID; ++ ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID; + id = ImHashStr("#RESIZE", 0, id); + id = ImHashData(&n, sizeof(int), id); + return id; +@@ -6381,7 +6681,7 @@ ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir) + { + IM_ASSERT(dir >= 0 && dir < 4); + int n = (int)dir + 4; +- ImGuiID id = window->ID; ++ ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID; + id = ImHashStr("#RESIZE", 0, id); + id = ImHashData(&n, sizeof(int), id); + return id; +@@ -6412,6 +6712,16 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si + ImVec2 pos_target(FLT_MAX, FLT_MAX); + ImVec2 size_target(FLT_MAX, FLT_MAX); + ++ // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time). ++ // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits. ++ // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it. ++ // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow. ++ // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold). ++ // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. ++ const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration); ++ if (clip_with_viewport_rect) ++ window->ClipRect = window->Viewport->GetMainRect(); ++ + // Resize grips and borders are on layer 1 + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + +@@ -6497,7 +6807,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si + // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop. + // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually. + // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it! +- const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false)); ++ const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true)); + if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing) + { + g.WindowResizeBorderExpectedRect = border_rect; +@@ -6555,7 +6865,7 @@ static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& si + // Navigation resize (keyboard/gamepad) + // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user. + // Not even sure the callback works here. +- if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window) ++ if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window) + { + ImVec2 nav_resize_dir; + if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift) +@@ -6606,7 +6916,9 @@ static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_ + { + ImGuiContext& g = *GImGui; + ImVec2 size_for_clamping = window->Size; +- if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ++ if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost) ++ size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here. ++ else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) + size_for_clamping.y = window->TitleBarHeight; + window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); + } +@@ -6641,7 +6953,7 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) + const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered); + RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual + } +- if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ++ if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) + { + float y = window->Pos.y + window->TitleBarHeight - 1; + window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize); +@@ -6670,6 +6982,8 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar + const float backup_border_size = style.FrameBorderSize; + g.Style.FrameBorderSize = window->WindowBorderSize; + ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); ++ if (window->ViewportOwned) ++ title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse) + RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); + g.Style.FrameBorderSize = backup_border_size; + } +@@ -6678,23 +6992,58 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar + // Window background + if (!(flags & ImGuiWindowFlags_NoBackground)) + { ++ bool is_docking_transparent_payload = false; ++ if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload) ++ if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window) ++ is_docking_transparent_payload = true; ++ + ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window)); +- bool override_alpha = false; +- float alpha = 1.0f; +- if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha) ++ if (window->ViewportOwned) ++ { ++ bg_col |= IM_COL32_A_MASK; // No alpha ++ if (is_docking_transparent_payload) ++ window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; ++ } ++ else + { +- alpha = g.NextWindowData.BgAlphaVal; +- override_alpha = true; ++ // Adjust alpha. For docking ++ bool override_alpha = false; ++ float alpha = 1.0f; ++ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha) ++ { ++ alpha = g.NextWindowData.BgAlphaVal; ++ override_alpha = true; ++ } ++ if (is_docking_transparent_payload) ++ { ++ alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override? ++ override_alpha = true; ++ } ++ if (override_alpha) ++ bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); + } +- if (override_alpha) +- bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); +- window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom); ++ ++ // Render, for docked windows and host windows we ensure bg goes before decorations ++ if (window->DockIsActive) ++ window->DockNode->LastBgColor = bg_col; ++ ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList; ++ if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost)) ++ bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG); ++ bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom); ++ if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost)) ++ bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); + } ++ if (window->DockIsActive) ++ window->DockNode->IsBgDrawnThisFrame = true; + + // Title bar +- if (!(flags & ImGuiWindowFlags_NoTitleBar)) ++ // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag, ++ // in order for their pos/size to be matching their undocking state.) ++ if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) + { + ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); ++ if (window->ViewportOwned) ++ title_bar_col |= IM_COL32_A_MASK; // No alpha + window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop); + } + +@@ -6708,6 +7057,27 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar + window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + } + ++ // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock ++ ImGuiDockNode* node = window->DockNode; ++ if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar()) ++ { ++ float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f); ++ float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f); ++ ImVec2 p = node->Pos; ++ ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit)); ++ ImGuiID unhide_id = window->GetID("#UNHIDE"); ++ KeepAliveID(unhide_id); ++ bool hovered, held; ++ if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren)) ++ node->WantHiddenTabBarToggle = true; ++ else if (held && IsMouseDragging(0)) ++ StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button ++ ++ // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size.. ++ ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); ++ window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col); ++ } ++ + // Scrollbars + if (window->ScrollbarX) + Scrollbar(ImGuiAxis_X); +@@ -6731,12 +7101,13 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar + } + } + +- // Borders +- if (handle_borders_and_resize_grips) ++ // Borders (for dock node host they will be rendered over after the tab bar) ++ if (handle_borders_and_resize_grips && !window->DockNodeAsHost) + RenderWindowOuterBorders(window); + } + } + ++// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. + // Render title text, collapse button, close button + void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) + { +@@ -6778,7 +7149,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl + + // Collapse button (submitting first so it gets priority when choosing a navigation init fallback) + if (has_collapse_button) +- if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos)) ++ if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL)) + window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function + + // Close button +@@ -6829,12 +7200,16 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl + void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window) + { + window->ParentWindow = parent_window; +- window->RootWindow = window->RootWindowPopupTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window; ++ window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window; + if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) +- window->RootWindow = parent_window->RootWindow; ++ { ++ window->RootWindowDockTree = parent_window->RootWindowDockTree; ++ if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost)) ++ window->RootWindow = parent_window->RootWindow; ++ } + if (parent_window && (flags & ImGuiWindowFlags_Popup)) + window->RootWindowPopupTree = parent_window->RootWindowPopupTree; +- if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) ++ if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ? + window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight; + while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened) + { +@@ -6949,22 +7324,24 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); + window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow); + +- // Update the Appearing flag +- bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on ++ // Update the Appearing flag (note: the BeginDocked() path may also set this to true later) ++ bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; + window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed + window_just_activated_by_user |= (window != popup_ref.Window); + } +- window->Appearing = window_just_activated_by_user; +- if (window->Appearing) +- SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); + + // Update Flags, LastFrameActive, BeginOrderXXX fields ++ const bool window_was_appearing = window->Appearing; + if (first_begin_of_the_frame) + { + UpdateWindowInFocusOrderList(window, window_just_created, flags); ++ window->Appearing = window_just_activated_by_user; ++ if (window->Appearing) ++ SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); ++ window->FlagsPreviousFrame = window->Flags; + window->Flags = (ImGuiWindowFlags)flags; + window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0; + window->LastFrameActive = current_frame; +@@ -6977,8 +7354,42 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + flags = window->Flags; + } + ++ // Docking ++ // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1) ++ IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both ++ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock) ++ SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond); ++ if (first_begin_of_the_frame) ++ { ++ bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL); ++ bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window); ++ bool dock_node_was_visible = window->DockNodeIsVisible; ++ bool dock_tab_was_visible = window->DockTabIsVisible; ++ if (has_dock_node || new_auto_dock_node) ++ { ++ BeginDocked(window, p_open); ++ flags = window->Flags; ++ if (window->DockIsActive) ++ { ++ IM_ASSERT(window->DockNode != NULL); ++ g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints ++ } ++ ++ // Amend the Appearing flag ++ if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing) ++ { ++ window->Appearing = true; ++ SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); ++ } ++ } ++ else ++ { ++ window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false; ++ } ++ } ++ + // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack +- ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window; ++ ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window; + ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow; + IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); + +@@ -7004,9 +7415,20 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + UpdateWindowParentAndRootLinks(window, flags, parent_window); + window->ParentWindowInBeginStack = parent_window_in_stack; + ++ // Focus route + // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack, +- // e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798) +- window->ParentWindowForFocusRoute = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window_in_stack : NULL; ++ // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798) ++ window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL; ++ if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL) ++ if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute) ++ window->ParentWindowForFocusRoute = window->DockNode->HostWindow; ++ ++ // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute() ++ if (window->WindowClass.FocusRouteParentWindowId != 0) ++ { ++ window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId); ++ IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId. ++ } + } + + // Add to focus scope stack +@@ -7070,6 +7492,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal; + else if (first_begin_of_the_frame) + window->ContentSizeExplicit = ImVec2(0.0f, 0.0f); ++ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass) ++ window->WindowClass = g.NextWindowData.WindowClass; + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed) + SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus) +@@ -7099,6 +7523,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + window->IDStack.resize(1); + window->DrawList->_ResetForNewFrame(); + window->DC.CurrentTableIdx = -1; ++ if (flags & ImGuiWindowFlags_DockNodeHost) ++ { ++ window->DrawList->ChannelsSplit(2); ++ window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later ++ } + + // Restore buffer capacity when woken from a compacted state, to avoid + if (window->MemoryCompacted) +@@ -7107,7 +7536,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). + // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. + bool window_title_visible_elsewhere = false; +- if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB ++ if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive)) ++ window_title_visible_elsewhere = true; ++ else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB + window_title_visible_elsewhere = true; + if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0) + { +@@ -7120,6 +7551,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + + // Update contents size from last frame for auto-fitting (or use explicit size) + CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal); ++ ++ // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors ++ // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because ++ // it has a single usage before this code block and may be set below before it is finally checked. + if (window->HiddenFramesCanSkipItems > 0) + window->HiddenFramesCanSkipItems--; + if (window->HiddenFramesCannotSkipItems > 0) +@@ -7147,20 +7582,23 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + } + + // SELECT VIEWPORT +- // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style) ++ // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes. + +- ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport(); +- SetWindowViewport(window, viewport); ++ WindowSelectViewport(window); ++ SetCurrentViewport(window, window->Viewport); ++ window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f; + SetCurrentWindow(window); ++ flags = window->Flags; + + // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies) ++ // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style. + +- if (flags & ImGuiWindowFlags_ChildWindow) ++ if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow)) + window->WindowBorderSize = style.ChildBorderSize; + else + window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize; + window->WindowPadding = style.WindowPadding; +- if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f) ++ if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f) + window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f); + + // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size. +@@ -7180,7 +7618,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + + // Collapse window by double-clicking on title bar + // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing +- if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) ++ if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive) + { + // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), + // so verify that we don't have items over the title bar. +@@ -7281,23 +7719,66 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) + window->Pos = FindBestWindowPosForPopup(window); + ++ // Late create viewport if we don't fit within our current host viewport. ++ if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized)) ++ if (!window->Viewport->GetMainRect().Contains(window->Rect())) ++ { ++ // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport) ++ //ImGuiViewport* old_viewport = window->Viewport; ++ window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); ++ ++ // FIXME-DPI ++ //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong ++ SetCurrentViewport(window, window->Viewport); ++ window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f; ++ SetCurrentWindow(window); ++ } ++ ++ if (window->ViewportOwned) ++ WindowSyncOwnedViewport(window, parent_window_in_stack); ++ + // Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect. +- ImRect viewport_rect(viewport->GetMainRect()); +- ImRect viewport_work_rect(viewport->GetWorkRect()); ++ ImRect viewport_rect(window->Viewport->GetMainRect()); ++ ImRect viewport_work_rect(window->Viewport->GetWorkRect()); + ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding); + + // Clamp position/size so window stays visible within its viewport or monitor + // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. ++ // FIXME: Similar to code in GetWindowAllowedExtentRect() + if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow)) +- if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f) ++ { ++ if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f) ++ { ++ ClampWindowPos(window, visibility_rect); ++ } ++ else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0) ++ { ++ if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree) ++ { ++ // While moving windows we allow them to straddle monitors (#7299, #3071) ++ visibility_rect = g.PlatformMonitorsFullWorkRect; ++ } ++ else ++ { ++ // When not moving ensure visible in its monitor ++ // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport. ++ const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport); ++ visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize); ++ } ++ visibility_rect.Expand(-visibility_padding); + ClampWindowPos(window, visibility_rect); ++ } ++ } + window->Pos = ImTrunc(window->Pos); + + // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) + // Large values tend to lead to variety of artifacts and are not recommended. +- window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; ++ if (window->ViewportOwned || window->DockIsActive) ++ window->WindowRounding = 0.0f; ++ else ++ window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; + + // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts. + //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar)) +@@ -7309,7 +7790,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + { + if (flags & ImGuiWindowFlags_Popup) + want_focus = true; +- else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0) ++ else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip)) + want_focus = true; + } + +@@ -7325,12 +7806,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + } + #endif + ++ // Decide if we are going to handle borders and resize grips ++ const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive); ++ + // Handle manual resize: Resize Grips, Borders, Gamepad + int border_hovered = -1, border_held = -1; + ImU32 resize_grip_col[4] = {}; + const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. + const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); +- if (!window->Collapsed) ++ if (handle_borders_and_resize_grips && !window->Collapsed) + if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) + { + if (auto_fit_mask & (1 << ImGuiAxis_X)) +@@ -7341,6 +7825,20 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + window->ResizeBorderHovered = (signed char)border_hovered; + window->ResizeBorderHeld = (signed char)border_held; + ++ // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either) ++ if (window->ViewportOwned) ++ { ++ if (!window->Viewport->PlatformRequestMove) ++ window->Viewport->Pos = window->Pos; ++ if (!window->Viewport->PlatformRequestResize) ++ window->Viewport->Size = window->Size; ++ window->Viewport->UpdateWorkRect(); ++ viewport_rect = window->Viewport->GetMainRect(); ++ } ++ ++ // Save last known viewport position within the window itself (so it can be saved in .ini file and restored) ++ window->ViewportPos = window->Viewport->Pos; ++ + // SCROLLBAR VISIBILITY + + // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). +@@ -7379,6 +7877,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + const ImRect outer_rect = window->Rect(); + const ImRect title_bar_rect = window->TitleBarRect(); + window->OuterRectClipped = outer_rect; ++ if (window->DockIsActive) ++ window->OuterRectClipped.Min.y += window->TitleBarHeight; + window->OuterRectClipped.ClipWith(host_rect); + + // Inner rectangle +@@ -7441,6 +7941,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71) + // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order. + // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493) ++ const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible; ++ if (is_undocked_or_docked_visible) + { + bool render_decorations_in_parent = false; + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) +@@ -7458,8 +7960,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + + // Handle title bar, scrollbar, resize grips and resize borders + const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; +- const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight); +- const bool handle_borders_and_resize_grips = true; // This exists to facilitate merge with 'docking' branch. ++ const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode))); + RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size); + + if (render_decorations_in_parent) +@@ -7542,6 +8043,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + if (window->AutoFitFramesY > 0) + window->AutoFitFramesY--; + ++ // Clear SetNextWindowXXX data (can aim to move this higher in the function) ++ g.NextWindowData.ClearFlags(); ++ + // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + // We ImGuiFocusRequestFlags_UnlessBelowModal to: + // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed. +@@ -7551,8 +8055,16 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + if (want_focus && window == g.NavWindow) + NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls + ++ // Close requested by platform window (apply to all windows in this viewport) ++ if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport()) ++ { ++ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name); ++ *p_open = false; ++ g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing. ++ } ++ + // Title bar +- if (!(flags & ImGuiWindowFlags_NoTitleBar)) ++ if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) + RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open); + + // Clear hit test shape every frame +@@ -7571,6 +8083,20 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + LogToClipboard(); + */ + ++ if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) ++ { ++ // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source. ++ // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. ++ if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0) ++ BeginDockableDragDropSource(window); ++ ++ // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead. ++ if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking)) ++ if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window) ++ if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost)) ++ BeginDockableDragDropTarget(window); ++ } ++ + // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). + // This is useful to allow creating context menus on title bar only, etc. + SetLastItemDataForWindow(window, title_bar_rect); +@@ -7594,26 +8120,39 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + SetWindowActiveForSkipRefresh(window); + + // Append ++ SetCurrentViewport(window, window->Viewport); + SetCurrentWindow(window); ++ g.NextWindowData.ClearFlags(); + SetLastItemDataForWindow(window, window->TitleBarRect()); + } + +- if (!window->SkipRefresh) ++ if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh) + PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); + + // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) + window->WriteAccessed = false; + window->BeginCount++; +- g.NextWindowData.ClearFlags(); + + // Update visibility + if (first_begin_of_the_frame && !window->SkipRefresh) + { ++ // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. ++ // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. ++ // This is analogous to regular windows being hidden from one frame. ++ // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. ++ if (window->DockIsActive && !window->DockTabIsVisible) ++ { ++ if (window->LastFrameJustFocused == g.FrameCount) ++ window->HiddenFramesCannotSkipItems = 1; ++ else ++ window->HiddenFramesCanSkipItems = 1; ++ } ++ + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu)) + { + // Child window can be out of sight and have "negative" clip windows. + // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). +- IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); ++ IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive); + const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); + if (!g.LogEnabled && !nav_request) + if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) +@@ -7652,6 +8191,16 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) + skip_items = true; + window->SkipItems = skip_items; ++ ++ // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value. ++ if (window->SkipItems) ++ window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask; ++ ++ // Sanity check: there are two spots which can set Appearing = true ++ // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false ++ // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert. ++ if (window->SkipItems && !window->Appearing) ++ IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177 + } + else if (first_begin_of_the_frame) + { +@@ -7677,7 +8226,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) + static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect) + { + ImGuiContext& g = *GImGui; +- SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect); ++ if (window->DockIsActive) ++ SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect); ++ else ++ SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect); + } + + void ImGui::End() +@@ -7694,14 +8246,14 @@ void ImGui::End() + ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back(); + + // Error checking: verify that user doesn't directly call End() on a child window. +- if (window->Flags & ImGuiWindowFlags_ChildWindow) ++ if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive) + IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!"); + + // Close anything that is open + if (window->DC.CurrentColumns) + EndColumns(); +- if (!window->SkipRefresh) +- PopClipRect(); // Inner window clip rectangle ++ if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh) // Pop inner window clip rectangle ++ PopClipRect(); + PopFocusScope(); + if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window) + EndDisabledOverrideReenable(); +@@ -7719,6 +8271,11 @@ void ImGui::End() + if (window->DC.IsSetPos) + ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); + ++ // Docking: report contents sizes to parent to allow for auto-resize ++ if (window->DockNode && window->DockTabIsVisible) ++ if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK ++ host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding; ++ + // Pop from window stack + g.LastItemData = window_stack_data.ParentLastItemDataBackup; + if (window->Flags & ImGuiWindowFlags_ChildMenu) +@@ -7732,6 +8289,8 @@ void ImGui::End() + + g.CurrentWindowStack.pop_back(); + SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window); ++ if (g.CurrentWindow) ++ SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport); + } + + void ImGui::BringWindowToFocusFront(ImGuiWindow* window) +@@ -7759,7 +8318,7 @@ void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) + { + ImGuiContext& g = *GImGui; + ImGuiWindow* current_front_window = g.Windows.back(); +- if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better) ++ if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better) + return; + for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window + if (g.Windows[i] == window) +@@ -7852,31 +8411,39 @@ void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags) + } + + // Move the root window to the top of the pile +- IM_ASSERT(window == NULL || window->RootWindow != NULL); +- ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop +- ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; ++ IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL); ++ ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; ++ ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL; ++ ImGuiDockNode* dock_node = window ? window->DockNode : NULL; ++ bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow); + + // Steal active widgets. Some of the cases it triggers includes: + // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. + // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) ++ // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) +- if (!g.ActiveIdNoClearOnFocusLoss) ++ if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host) + ClearActiveID(); + + // Passing NULL allow to disable keyboard focus + if (!window) + return; ++ window->LastFrameJustFocused = g.FrameCount; ++ ++ // Select in dock node ++ // For #2304 we avoid applying focus immediately before the tabbar is visible. ++ //if (dock_node && dock_node->TabBar) ++ // dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId; + + // Bring to front + BringWindowToFocusFront(focus_front_window); +- if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) ++ if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) + BringWindowToDisplayFront(display_front_window); + } + + void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags) + { + ImGuiContext& g = *GImGui; +- IM_UNUSED(filter_viewport); // Unused in master branch. + int start_idx = g.WindowsFocusOrder.Size - 1; + if (under_this_window != NULL) + { +@@ -7895,8 +8462,15 @@ void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWind + ImGuiWindow* window = g.WindowsFocusOrder[i]; + if (window == ignore_window || !window->WasActive) + continue; ++ if (filter_viewport != NULL && window->Viewport != filter_viewport) ++ continue; + if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) + { ++ // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set... ++ // This is failing (lagging by one frame) for docked windows. ++ // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B. ++ // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update) ++ // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself? + FocusWindow(window, flags); + return; + } +@@ -8062,7 +8636,7 @@ void ImGui::PopTextWrapPos() + window->DC.TextWrapPosStack.pop_back(); + } + +-static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy) ++static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy) + { + ImGuiWindow* last_window = NULL; + while (last_window != window) +@@ -8071,13 +8645,15 @@ static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierar + window = window->RootWindow; + if (popup_hierarchy) + window = window->RootWindowPopupTree; +- } ++ if (dock_hierarchy) ++ window = window->RootWindowDockTree; ++ } + return window; + } + +-bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy) ++bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy) + { +- ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy); ++ ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy); + if (window_root == potential_parent) + return true; + while (window != NULL) +@@ -8142,12 +8718,13 @@ bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) + { + IM_ASSERT(cur_window); // Not inside a Begin()/End() + const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0; ++ const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0; + if (flags & ImGuiHoveredFlags_RootWindow) +- cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy); ++ cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy); + + bool result; + if (flags & ImGuiHoveredFlags_ChildWindows) +- result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy); ++ result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy); + else + result = (ref_window == cur_window); + if (!result) +@@ -8186,15 +8763,28 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) + + IM_ASSERT(cur_window); // Not inside a Begin()/End() + const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0; ++ const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0; + if (flags & ImGuiHoveredFlags_RootWindow) +- cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy); ++ cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy); + + if (flags & ImGuiHoveredFlags_ChildWindows) +- return IsWindowChildOf(ref_window, cur_window, popup_hierarchy); ++ return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy); + else + return (ref_window == cur_window); + } + ++ImGuiID ImGui::GetWindowDockID() ++{ ++ ImGuiContext& g = *GImGui; ++ return g.CurrentWindow->DockId; ++} ++ ++bool ImGui::IsWindowDocked() ++{ ++ ImGuiContext& g = *GImGui; ++ return g.CurrentWindow->DockIsActive; ++} ++ + // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) + // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically. + // If you want a window to never be focused, you may use the e.g. NoInputs flag. +@@ -8239,6 +8829,7 @@ void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) + if (offset.x == 0.0f && offset.y == 0.0f) + return; + MarkIniSettingsDirty(window); ++ // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here. + window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected. + window->DC.IdealMaxPos += offset; +@@ -8376,6 +8967,7 @@ void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pi + g.NextWindowData.PosVal = pos; + g.NextWindowData.PosPivotVal = pivot; + g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always; ++ g.NextWindowData.PosUndock = true; + } + + void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) +@@ -8438,6 +9030,29 @@ void ImGui::SetNextWindowBgAlpha(float alpha) + g.NextWindowData.BgAlphaVal = alpha; + } + ++void ImGui::SetNextWindowViewport(ImGuiID id) ++{ ++ ImGuiContext& g = *GImGui; ++ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport; ++ g.NextWindowData.ViewportId = id; ++} ++ ++void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond) ++{ ++ ImGuiContext& g = *GImGui; ++ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock; ++ g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always; ++ g.NextWindowData.DockId = id; ++} ++ ++void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit ++ g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass; ++ g.NextWindowData.WindowClass = *window_class; ++} ++ + // This is experimental and meant to be a toy for exploring a future/wider range of features. + void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags) + { +@@ -8452,6 +9067,19 @@ ImDrawList* ImGui::GetWindowDrawList() + return window->DrawList; + } + ++float ImGui::GetWindowDpiScale() ++{ ++ ImGuiContext& g = *GImGui; ++ return g.CurrentDpiScale; ++} ++ ++ImGuiViewport* ImGui::GetWindowViewport() ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport); ++ return g.CurrentViewport; ++} ++ + ImFont* ImGui::GetFont() + { + return GImGui->Font; +@@ -9459,6 +10087,8 @@ bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool c + // Hit testing, expanded for touch input + if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding)) + return false; ++ if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped)) ++ return false; + return true; + } + +@@ -9783,13 +10413,16 @@ static void ImGui::UpdateMouseInputs() + io.MouseClickedTime[i] = g.Time; + io.MouseClickedPos[i] = io.MousePos; + io.MouseClickedCount[i] = io.MouseClickedLastCount[i]; ++ io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f); + io.MouseDragMaxDistanceSqr[i] = 0.0f; + } + else if (io.MouseDown[i]) + { + // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold +- float delta_sqr_click_pos = IsMousePosValid(&io.MousePos) ? ImLengthSqr(io.MousePos - io.MouseClickedPos[i]) : 0.0f; +- io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], delta_sqr_click_pos); ++ ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); ++ io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos)); ++ io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x); ++ io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y); + } + + // We provide io.MouseDoubleClicked[] as a legacy service +@@ -9979,6 +10612,7 @@ static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e) + if (e->Type == ImGuiInputEventType_MousePos) { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; } + if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; } + if (e->Type == ImGuiInputEventType_MouseWheel) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; } ++ if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; } + if (e->Type == ImGuiInputEventType_Key) { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; } + if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; } + if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; } +@@ -10042,6 +10676,10 @@ void ImGui::UpdateInputEvents(bool trickle_fast_inputs) + io.MouseSource = e->MouseWheel.MouseSource; + mouse_wheeled = true; + } ++ else if (e->Type == ImGuiInputEventType_MouseViewport) ++ { ++ io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID; ++ } + else if (e->Type == ImGuiInputEventType_Key) + { + // Trickling Rule: Stop processing queued events if we got multiple action on the same button +@@ -10452,6 +11090,45 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() + if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl)) + g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); }; + #endif ++ ++ // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data. ++ if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0) ++ IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); ++ if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0) ++ IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); ++ ++ // Perform simple checks: multi-viewport and platform windows support ++ if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ++ { ++ if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports)) ++ { ++ IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference."); ++ IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?"); ++ IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?"); ++ IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?"); ++ IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?"); ++ IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?"); ++ IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?"); ++ IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?"); ++ IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport."); ++ if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) ++ IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!"); ++ } ++ else ++ { ++ // Disable feature, our backends do not support it ++ g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable; ++ } ++ ++ // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs ++ for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors) ++ { ++ IM_UNUSED(mon); ++ IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly."); ++ IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them."); ++ IM_ASSERT(mon.DpiScale != 0.0f); ++ } ++ } + } + + static void ImGui::ErrorCheckEndFrameSanityChecks() +@@ -11549,7 +12226,8 @@ bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags ext + SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow); + ImFormatString(window_name, IM_ARRAYSIZE(window_name), window_name_template, ++g.TooltipOverrideCount); + } +- ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; ++ ++ ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking; + Begin(window_name, NULL, flags | extra_window_flags); + // 2023-03-09: Added bool return value to the API, but currently always returning true. + // If this ever returns false we need to update BeginDragDropSource() accordingly. +@@ -11622,8 +12300,8 @@ bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags) + if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) + { + // Return true if the popup is open anywhere in the popup stack +- for (int n = 0; n < g.OpenPopupStack.Size; n++) +- if (g.OpenPopupStack[n].PopupId == id) ++ for (ImGuiPopupData& popup_data : g.OpenPopupStack) ++ if (popup_data.PopupId == id) + return true; + return false; + } +@@ -11762,12 +12440,13 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to + // Window -> Popup1 -> Window2(Ref) + // - Clicking/focusing Popup1 will close Popup2 and Popup3: + // Window -> Popup1(Ref) -> Popup2 -> Popup3 +- // - Each popups may contain child windows, which is why we compare ->RootWindow! ++ // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree! + // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child + // We step through every popup from bottom to top to validate their position relative to reference window. + bool ref_window_is_descendent_of_popup = false; + for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++) + if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window) ++ //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE + if (IsWindowWithinBeginStackOf(ref_window, popup_window)) + { + ref_window_is_descendent_of_popup = true; +@@ -11871,7 +12550,7 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags) + else + ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame + +- bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup); ++ bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking); + if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) + EndPopup(); + +@@ -11915,11 +12594,11 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla + // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. + if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) + { +- const ImGuiViewport* viewport = GetMainViewport(); ++ const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport? + SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); + } + +- flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse; ++ flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; + const bool is_open = Begin(name, p_open, flags); + if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + { +@@ -12106,8 +12785,19 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s + ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window) + { + ImGuiContext& g = *GImGui; +- IM_UNUSED(window); +- ImRect r_screen = ((ImGuiViewportP*)(void*)GetMainViewport())->GetMainRect(); ++ ImRect r_screen; ++ if (window->ViewportAllowPlatformMonitorExtend >= 0) ++ { ++ // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here) ++ const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend]; ++ r_screen.Min = monitor.WorkPos; ++ r_screen.Max = monitor.WorkPos + monitor.WorkSize; ++ } ++ else ++ { ++ // Use the full viewport area (not work area) for popups ++ r_screen = window->Viewport->GetMainRect(); ++ } + ImVec2 padding = g.Style.DisplaySafeAreaPadding; + r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f)); + return r_screen; +@@ -12122,8 +12812,7 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) + { + // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds. + // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. +- IM_ASSERT(g.CurrentWindow == window); +- ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2].Window; ++ ImGuiWindow* parent_window = window->ParentWindow; + float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x). + ImRect r_avoid; + if (parent_window->DC.MenuBarAppending) +@@ -12677,6 +13366,9 @@ static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window) + { + if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive) + return window->NavLastChildNavWindow; ++ if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar) ++ if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar)) ++ return tab->Window; + return window; + } + +@@ -12721,6 +13413,7 @@ static inline void ImGui::NavUpdateAnyRequestFlag() + // This needs to be called before we submit any widget (aka in or before Begin) + void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) + { ++ // FIXME: ChildWindow test here is wrong for docking + ImGuiContext& g = *GImGui; + IM_ASSERT(window == g.NavWindow); + +@@ -12781,7 +13474,7 @@ static ImVec2 ImGui::NavCalcPreferredRefPos() + ref_rect.Translate(window->Scroll - next_scroll); + } + ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect.GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect.GetHeight())); +- ImGuiViewport* viewport = GetMainViewport(); ++ ImGuiViewport* viewport = window->Viewport; + return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta. + } + } +@@ -13664,7 +14357,7 @@ static void ImGui::NavUpdateWindowing() + ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos); + if (accum_floored.x != 0.0f || accum_floored.y != 0.0f) + { +- ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow; ++ ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree; + SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always); + g.NavWindowingAccumDeltaPos -= accum_floored; + } +@@ -13674,6 +14367,9 @@ static void ImGui::NavUpdateWindowing() + // Apply final focus + if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)) + { ++ // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow() ++ // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow() ++ ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL; + ClearActiveID(); + NavRestoreHighlightAfterMove(); + ClosePopupsOverWindow(apply_focus_window, false); +@@ -13691,6 +14387,10 @@ static void ImGui::NavUpdateWindowing() + // won't be valid. + if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu)) + g.NavLayer = ImGuiNavLayer_Menu; ++ ++ // Request OS level focus ++ if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus) ++ g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport); + } + if (apply_focus_window) + g.NavWindowingTarget = NULL; +@@ -13719,7 +14419,8 @@ static void ImGui::NavUpdateWindowing() + if (new_nav_layer != g.NavLayer) + { + // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?) +- if (new_nav_layer == ImGuiNavLayer_Menu) ++ const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL); ++ if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id) + g.NavWindow->NavLastIds[new_nav_layer] = 0; + NavRestoreLayer(new_nav_layer); + NavRestoreHighlightAfterMove(); +@@ -13734,6 +14435,8 @@ static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window) + return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup); + if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0) + return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar); ++ if (window->DockNodeAsHost) ++ return "(Dock node)"; // Not normally shown to user. + return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled); + } + +@@ -13748,7 +14451,7 @@ void ImGui::NavUpdateWindowingOverlay() + + if (g.NavWindowingListWindow == NULL) + g.NavWindowingListWindow = FindWindowByName("###NavWindowingList"); +- const ImGuiViewport* viewport = GetMainViewport(); ++ const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport(); + SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); + SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); +@@ -13999,7 +14702,7 @@ bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) + + ImGuiWindow* window = g.CurrentWindow; + ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; +- if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow) ++ if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree) + return false; + IM_ASSERT(id != 0); + if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId)) +@@ -14029,7 +14732,7 @@ bool ImGui::BeginDragDropTarget() + if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect)) + return false; + ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; +- if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow || window->SkipItems) ++ if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems) + return false; + + const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect; +@@ -14531,7 +15234,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) + line_end[-1] = 0; + const char* name_end = line_end - 1; + const char* type_start = line + 1; +- char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']'); ++ char* type_end = const_cast(ImStrchrRange(type_start, name_end, ']')); + const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; + if (!type_end || !name_start) + continue; +@@ -14634,11 +15337,14 @@ ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window) + void ImGui::ClearWindowSettings(const char* name) + { + //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name); ++ ImGuiContext& g = *GImGui; + ImGuiWindow* window = FindWindowByName(name); + if (window != NULL) + { + window->Flags |= ImGuiWindowFlags_NoSavedSettings; + InitOrLoadWindowSettings(window, NULL); ++ if (window->DockId != 0) ++ DockContextProcessUndockWindow(&g, window, true); + } + if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name))) + settings->WantDelete = true; +@@ -14670,10 +15376,16 @@ static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, + ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; + int x, y; + int i; +- if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); } +- else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); } +- else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); } +- else if (sscanf(line, "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); } ++ ImU32 u1; ++ if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); } ++ else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); } ++ else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; } ++ else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); } ++ else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); } ++ else if (sscanf(line, "IsChild=%d", &i) == 1) { settings->IsChild = (i != 0); } ++ else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; } ++ else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; } ++ else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; } + } + + // Apply to existing windows (if any) +@@ -14706,10 +15418,16 @@ static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl + window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); + } + IM_ASSERT(settings->ID == window->ID); +- settings->Pos = ImVec2ih(window->Pos); ++ settings->Pos = ImVec2ih(window->Pos - window->ViewportPos); + settings->Size = ImVec2ih(window->SizeFull); +- settings->IsChild = (window->Flags & ImGuiWindowFlags_ChildWindow) != 0; ++ settings->ViewportId = window->ViewportId; ++ settings->ViewportPos = ImVec2ih(window->ViewportPos); ++ IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId); ++ settings->DockId = window->DockId; ++ settings->ClassId = window->WindowClass.ClassId; ++ settings->DockOrder = window->DockOrder; + settings->Collapsed = window->Collapsed; ++ settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set. + settings->WantDelete = false; + } + +@@ -14728,10 +15446,26 @@ static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl + } + else + { +- buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y); +- buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y); +- if (settings->Collapsed) +- buf->appendf("Collapsed=1\n"); ++ if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID) ++ { ++ buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y); ++ buf->appendf("ViewportId=0x%08X\n", settings->ViewportId); ++ } ++ if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID) ++ buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y); ++ if (settings->Size.x != 0 || settings->Size.y != 0) ++ buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y); ++ buf->appendf("Collapsed=%d\n", settings->Collapsed); ++ if (settings->DockId != 0) ++ { ++ //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier. ++ if (settings->DockOrder == -1) ++ buf->appendf("DockId=0x%08X\n", settings->DockId); ++ else ++ buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder); ++ if (settings->ClassId != 0) ++ buf->appendf("ClassId=0x%08X\n", settings->ClassId); ++ } + } + buf->append("\n"); + } +@@ -14754,9 +15488,28 @@ void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count) + // [SECTION] VIEWPORTS, PLATFORM WINDOWS + //----------------------------------------------------------------------------- + // - GetMainViewport() ++// - FindViewportByID() ++// - FindViewportByPlatformHandle() ++// - SetCurrentViewport() [Internal] + // - SetWindowViewport() [Internal] ++// - GetWindowAlwaysWantOwnViewport() [Internal] ++// - UpdateTryMergeWindowIntoHostViewport() [Internal] ++// - UpdateTryMergeWindowIntoHostViewports() [Internal] ++// - TranslateWindowsInViewport() [Internal] ++// - ScaleWindowsInViewport() [Internal] ++// - FindHoveredViewportFromPlatformWindowStack() [Internal] + // - UpdateViewportsNewFrame() [Internal] +-// (this section is more complete in the 'docking' branch) ++// - UpdateViewportsEndFrame() [Internal] ++// - AddUpdateViewport() [Internal] ++// - WindowSelectViewport() [Internal] ++// - WindowSyncOwnedViewport() [Internal] ++// - UpdatePlatformWindows() ++// - RenderPlatformWindowsDefault() ++// - FindPlatformMonitorForPos() [Internal] ++// - FindPlatformMonitorForRect() [Internal] ++// - UpdateViewportPlatformMonitor() [Internal] ++// - DestroyPlatformWindow() [Internal] ++// - DestroyPlatformWindows() + //----------------------------------------------------------------------------- + + ImGuiViewport* ImGui::GetMainViewport() +@@ -14765,40 +15518,4925 @@ ImGuiViewport* ImGui::GetMainViewport() + return g.Viewports[0]; + } + +-void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport) ++// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236) ++ImGuiViewport* ImGui::FindViewportByID(ImGuiID id) + { +- window->Viewport = viewport; ++ ImGuiContext& g = *GImGui; ++ for (ImGuiViewportP* viewport : g.Viewports) ++ if (viewport->ID == id) ++ return viewport; ++ return NULL; + } + +-// Update viewports and monitor infos +-static void ImGui::UpdateViewportsNewFrame() ++ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle) + { + ImGuiContext& g = *GImGui; +- IM_ASSERT(g.Viewports.Size == 1); +- +- // Update main viewport with current platform position. +- // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent. +- ImGuiViewportP* main_viewport = g.Viewports[0]; +- main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp; +- main_viewport->Pos = ImVec2(0.0f, 0.0f); +- main_viewport->Size = g.IO.DisplaySize; +- + for (ImGuiViewportP* viewport : g.Viewports) +- { +- // Lock down space taken by menu bars and status bars ++ if (viewport->PlatformHandle == platform_handle) ++ return viewport; ++ return NULL; ++} ++ ++void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport) ++{ ++ ImGuiContext& g = *GImGui; ++ (void)current_window; ++ ++ if (viewport) ++ viewport->LastFrameActive = g.FrameCount; ++ if (g.CurrentViewport == viewport) ++ return; ++ g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f; ++ g.CurrentViewport = viewport; ++ //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0); ++ ++ // Notify platform layer of viewport changes ++ // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI ++ if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport) ++ g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport); ++} ++ ++void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport) ++{ ++ // Abandon viewport ++ if (window->ViewportOwned && window->Viewport->Window == window) ++ window->Viewport->Size = ImVec2(0.0f, 0.0f); ++ ++ window->Viewport = viewport; ++ window->ViewportId = viewport->ID; ++ window->ViewportOwned = (viewport->Window == window); ++} ++ ++static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) ++{ ++ // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own. ++ ImGuiContext& g = *GImGui; ++ if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge)) ++ if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) ++ if (!window->DockIsActive) ++ if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0) ++ if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0) ++ return true; ++ return false; ++} ++ ++static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport) ++{ ++ ImGuiContext& g = *GImGui; ++ if (window->Viewport == viewport) ++ return false; ++ if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0) ++ return false; ++ if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0) ++ return false; ++ if (!viewport->GetMainRect().Contains(window->Rect())) ++ return false; ++ if (GetWindowAlwaysWantOwnViewport(window)) ++ return false; ++ ++ // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could.. ++ for (ImGuiWindow* window_behind : g.Windows) ++ { ++ if (window_behind == window) ++ break; ++ if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow)) ++ if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect())) ++ return false; ++ } ++ ++ // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child) ++ ImGuiViewportP* old_viewport = window->Viewport; ++ if (window->ViewportOwned) ++ for (int n = 0; n < g.Windows.Size; n++) ++ if (g.Windows[n]->Viewport == old_viewport) ++ SetWindowViewport(g.Windows[n], viewport); ++ SetWindowViewport(window, viewport); ++ BringWindowToDisplayFront(window); ++ ++ return true; ++} ++ ++// FIXME: handle 0 to N host viewports ++static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window) ++{ ++ ImGuiContext& g = *GImGui; ++ return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]); ++} ++ ++// Translate Dear ImGui windows when a Host Viewport has been moved ++// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) ++void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos, const ImVec2& old_size, const ImVec2& new_size) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows)); ++ ++ // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently ++ // translate imgui windows from OS-window-local to absolute coordinates or vice-versa. ++ // 2) If it's not going to fit into the new size, keep it at same absolute position. ++ // One problem with this is that most Win32 applications doesn't update their render while dragging, ++ // and so the window will appear to teleport when releasing the mouse. ++ const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable); ++ ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size); ++ ImVec2 delta_pos = new_pos - old_pos; ++ for (ImGuiWindow* window : g.Windows) // FIXME-OPT ++ if (translate_all_windows || (window->Viewport == viewport && (old_size == new_size || test_still_fit_rect.Contains(window->Rect())))) ++ TranslateWindow(window, delta_pos); ++} ++ ++// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) ++void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) ++{ ++ ImGuiContext& g = *GImGui; ++ if (viewport->Window) ++ { ++ ScaleWindow(viewport->Window, scale); ++ } ++ else ++ { ++ for (ImGuiWindow* window : g.Windows) ++ if (window->Viewport == viewport) ++ ScaleWindow(window, scale); ++ } ++} ++ ++// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves. ++// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. ++// B) It requires Platform_GetWindowFocus to be implemented by backend. ++ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiViewportP* best_candidate = NULL; ++ for (ImGuiViewportP* viewport : g.Viewports) ++ if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos)) ++ if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount) ++ best_candidate = viewport; ++ return best_candidate; ++} ++ ++// Update viewports and monitor infos ++// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. ++static void ImGui::UpdateViewportsNewFrame() ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size); ++ ++ // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport) ++ // Update Focused status ++ const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0; ++ if (viewports_enabled) ++ { ++ ImGuiViewportP* focused_viewport = NULL; ++ for (ImGuiViewportP* viewport : g.Viewports) ++ { ++ const bool platform_funcs_available = viewport->PlatformWindowCreated; ++ if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available) ++ { ++ bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); ++ if (is_minimized) ++ viewport->Flags |= ImGuiViewportFlags_IsMinimized; ++ else ++ viewport->Flags &= ~ImGuiViewportFlags_IsMinimized; ++ } ++ ++ // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport. ++ // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored. ++ if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available) ++ { ++ bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport); ++ if (is_focused) ++ viewport->Flags |= ImGuiViewportFlags_IsFocused; ++ else ++ viewport->Flags &= ~ImGuiViewportFlags_IsFocused; ++ if (is_focused) ++ focused_viewport = viewport; ++ } ++ } ++ ++ // Focused viewport has changed? ++ if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID) ++ { ++ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID); ++ const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId); ++ const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false); ++ ++ // Store a tag so we can infer z-order easily from all our windows ++ // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag ++ // will keep the front most stamp instead of losing it back to their parent viewport. ++ if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount) ++ focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount; ++ g.PlatformLastFocusedViewportId = focused_viewport->ID; ++ ++ // Focus associated dear imgui window ++ // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299) ++ // - if focus didn't happen because we destroyed another window (#6462) ++ // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well. ++ const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed; ++ if (apply_imgui_focus_on_focused_viewport) ++ { ++ focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus. ++ ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild; ++ if (focused_viewport->Window != NULL) ++ FocusWindow(focused_viewport->Window, focus_request_flags); ++ else if (focused_viewport->LastFocusedHadNavWindow) ++ FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport ++ else ++ FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused ++ } ++ } ++ if (focused_viewport) ++ focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); ++ } ++ ++ // Create/update main viewport with current platform position. ++ // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent. ++ ImGuiViewportP* main_viewport = g.Viewports[0]; ++ IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID); ++ IM_ASSERT(main_viewport->Window == NULL); ++ ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f); ++ ImVec2 main_viewport_size = g.IO.DisplaySize; ++ if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized)) ++ { ++ main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path) ++ main_viewport_size = main_viewport->Size; ++ } ++ AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows); ++ ++ g.CurrentDpiScale = 0.0f; ++ g.CurrentViewport = NULL; ++ g.MouseViewport = NULL; ++ for (int n = 0; n < g.Viewports.Size; n++) ++ { ++ ImGuiViewportP* viewport = g.Viewports[n]; ++ viewport->Idx = n; ++ ++ // Erase unused viewports ++ if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2) ++ { ++ DestroyViewport(viewport); ++ n--; ++ continue; ++ } ++ ++ const bool platform_funcs_available = viewport->PlatformWindowCreated; ++ if (viewports_enabled) ++ { ++ // Update Position and Size (from Platform Window to ImGui) if requested. ++ // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities. ++ if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available) ++ { ++ // Viewport->WorkPos and WorkSize will be updated below ++ if (viewport->PlatformRequestMove) ++ viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport); ++ if (viewport->PlatformRequestResize) ++ viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport); ++ } ++ } ++ ++ // Update/copy monitor info ++ UpdateViewportPlatformMonitor(viewport); ++ ++ // Lock down space taken by menu bars and status bars + query initial insets from backend + // Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc. + viewport->WorkInsetMin = viewport->BuildWorkInsetMin; + viewport->WorkInsetMax = viewport->BuildWorkInsetMax; + viewport->BuildWorkInsetMin = viewport->BuildWorkInsetMax = ImVec2(0.0f, 0.0f); ++ if (g.PlatformIO.Platform_GetWindowWorkAreaInsets != NULL && platform_funcs_available) ++ { ++ ImVec4 insets = g.PlatformIO.Platform_GetWindowWorkAreaInsets(viewport); ++ IM_ASSERT(insets.x >= 0.0f && insets.y >= 0.0f && insets.z >= 0.0f && insets.w >= 0.0f); ++ viewport->BuildWorkInsetMin = ImVec2(insets.x, insets.y); ++ viewport->BuildWorkInsetMax = ImVec2(insets.z, insets.w); ++ } + viewport->UpdateWorkRect(); ++ ++ // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back. ++ viewport->Alpha = 1.0f; ++ ++ // Translate Dear ImGui windows when a Host Viewport has been moved ++ // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) ++ const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos; ++ if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f)) ++ TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos, viewport->LastSize, viewport->Size); ++ ++ // Update DPI scale ++ float new_dpi_scale; ++ if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available) ++ new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport); ++ else if (viewport->PlatformMonitor != -1) ++ new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; ++ else ++ new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f; ++ if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale) ++ { ++ float scale_factor = new_dpi_scale / viewport->DpiScale; ++ if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) ++ ScaleWindowsInViewport(viewport, scale_factor); ++ //if (viewport == GetMainViewport()) ++ // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor); ++ ++ // Scale our window moving pivot so that the window will rescale roughly around the mouse position. ++ // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border. ++ // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.) ++ //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport) ++ // g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor); ++ } ++ viewport->DpiScale = new_dpi_scale; ++ } ++ ++ // Update fallback monitor ++ g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); ++ if (g.PlatformIO.Monitors.Size == 0) ++ { ++ ImGuiPlatformMonitor* monitor = &g.FallbackMonitor; ++ monitor->MainPos = main_viewport->Pos; ++ monitor->MainSize = main_viewport->Size; ++ monitor->WorkPos = main_viewport->WorkPos; ++ monitor->WorkSize = main_viewport->WorkSize; ++ monitor->DpiScale = main_viewport->DpiScale; ++ g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos); ++ g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize); ++ } ++ else ++ { ++ g.FallbackMonitor = g.PlatformIO.Monitors[0]; ++ } ++ for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors) ++ { ++ g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos); ++ g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize); ++ } ++ ++ if (!viewports_enabled) ++ { ++ g.MouseViewport = main_viewport; ++ return; ++ } ++ ++ // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport. ++ // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set. ++ ImGuiViewportP* viewport_hovered = NULL; ++ if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) ++ { ++ viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL; ++ if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) ++ viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback. ++ } ++ else ++ { ++ // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search: ++ // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. ++ // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order. ++ // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO) ++ viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); ++ } ++ if (viewport_hovered != NULL) ++ g.MouseLastHoveredViewport = viewport_hovered; ++ else if (g.MouseLastHoveredViewport == NULL) ++ g.MouseLastHoveredViewport = g.Viewports[0]; ++ ++ // Update mouse reference viewport ++ // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode) ++ // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details) ++ if (g.MovingWindow && g.MovingWindow->Viewport) ++ g.MouseViewport = g.MovingWindow->Viewport; ++ else ++ g.MouseViewport = g.MouseLastHoveredViewport; ++ ++ // When dragging something, always refer to the last hovered viewport. ++ // - when releasing a moving window we will revert to aiming behind (at viewport_hovered) ++ // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info) ++ // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release. ++ // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that. ++ const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive; ++ if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL) ++ viewport_hovered = g.MouseLastHoveredViewport; ++ if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown()) ++ if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) ++ g.MouseViewport = viewport_hovered; ++ ++ IM_ASSERT(g.MouseViewport != NULL); ++} ++ ++// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) ++static void ImGui::UpdateViewportsEndFrame() ++{ ++ ImGuiContext& g = *GImGui; ++ g.PlatformIO.Viewports.resize(0); ++ for (int i = 0; i < g.Viewports.Size; i++) ++ { ++ ImGuiViewportP* viewport = g.Viewports[i]; ++ viewport->LastPos = viewport->Pos; ++ viewport->LastSize = viewport->Size; ++ if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f) ++ if (i > 0) // Always include main viewport in the list ++ continue; ++ if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)) ++ continue; ++ if (i > 0) ++ IM_ASSERT(viewport->Window != NULL); ++ g.PlatformIO.Viewports.push_back(viewport); ++ } ++ g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called ++} ++ ++// FIXME: We should ideally refactor the system to call this every frame (we currently don't) ++ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(id != 0); ++ ++ flags |= ImGuiViewportFlags_IsPlatformWindow; ++ if (window != NULL) ++ { ++ if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window) ++ flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing; ++ if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) ++ flags |= ImGuiViewportFlags_NoInputs; ++ if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing) ++ flags |= ImGuiViewportFlags_NoFocusOnAppearing; ++ } ++ ++ ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id); ++ if (viewport) ++ { ++ // Always update for main viewport as we are already pulling correct platform pos/size (see #4900) ++ if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID) ++ viewport->Pos = pos; ++ if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID) ++ viewport->Size = size; ++ viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags ++ } ++ else ++ { ++ // New viewport ++ viewport = IM_NEW(ImGuiViewportP)(); ++ viewport->ID = id; ++ viewport->Idx = g.Viewports.Size; ++ viewport->Pos = viewport->LastPos = pos; ++ viewport->Size = viewport->LastSize = size; ++ viewport->Flags = flags; ++ UpdateViewportPlatformMonitor(viewport); ++ g.Viewports.push_back(viewport); ++ g.ViewportCreatedCount++; ++ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : ""); ++ ++ // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport. ++ // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame ++ g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x); ++ g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y); ++ g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x); ++ g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y); ++ ++ // Store initial DpiScale before the OS platform window creation, based on expected monitor data. ++ // This is so we can select an appropriate font size on the first frame of our window lifetime ++ if (viewport->PlatformMonitor != -1) ++ viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; ++ } ++ ++ viewport->Window = window; ++ viewport->LastFrameActive = g.FrameCount; ++ viewport->UpdateWorkRect(); ++ IM_ASSERT(window == NULL || viewport->ID == window->ID); ++ ++ if (window != NULL) ++ window->ViewportOwned = true; ++ ++ return viewport; ++} ++ ++static void ImGui::DestroyViewport(ImGuiViewportP* viewport) ++{ ++ // Clear references to this viewport in windows (window->ViewportId becomes the master data) ++ ImGuiContext& g = *GImGui; ++ for (ImGuiWindow* window : g.Windows) ++ { ++ if (window->Viewport != viewport) ++ continue; ++ window->Viewport = NULL; ++ window->ViewportOwned = false; ++ } ++ if (viewport == g.MouseLastHoveredViewport) ++ g.MouseLastHoveredViewport = NULL; ++ ++ // Destroy ++ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); ++ DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here. ++ IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false); ++ IM_ASSERT(g.Viewports[viewport->Idx] == viewport); ++ g.Viewports.erase(g.Viewports.Data + viewport->Idx); ++ IM_DELETE(viewport); ++} ++ ++// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. ++static void ImGui::WindowSelectViewport(ImGuiWindow* window) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiWindowFlags flags = window->Flags; ++ window->ViewportAllowPlatformMonitorExtend = -1; ++ ++ // Restore main viewport if multi-viewport is not supported by the backend ++ ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport(); ++ if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) ++ { ++ SetWindowViewport(window, main_viewport); ++ return; ++ } ++ window->ViewportOwned = false; ++ ++ // Appearing popups reset their viewport so they can inherit again ++ if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing) ++ { ++ window->Viewport = NULL; ++ window->ViewportId = 0; ++ } ++ ++ if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0) ++ { ++ // By default inherit from parent window ++ if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive)) ++ window->Viewport = window->ParentWindow->Viewport; ++ ++ // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file ++ if (window->Viewport == NULL && window->ViewportId != 0) ++ { ++ window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId); ++ if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX) ++ window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None); ++ } ++ } ++ ++ bool lock_viewport = false; ++ if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) ++ { ++ // Code explicitly request a viewport ++ window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId); ++ window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet. ++ if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL) ++ { ++ window->Viewport->Window = window; ++ window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node) ++ } ++ lock_viewport = true; ++ } ++ else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu)) ++ { ++ // Always inherit viewport from parent window ++ if (window->DockNode && window->DockNode->HostWindow) ++ IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport); ++ window->Viewport = window->ParentWindow->Viewport; ++ } ++ else if (window->DockNode && window->DockNode->HostWindow) ++ { ++ // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame ++ window->Viewport = window->DockNode->HostWindow->Viewport; ++ } ++ else if (flags & ImGuiWindowFlags_Tooltip) ++ { ++ window->Viewport = g.MouseViewport; ++ } ++ else if (GetWindowAlwaysWantOwnViewport(window)) ++ { ++ window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); ++ } ++ else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid()) ++ { ++ if (window->Viewport != NULL && window->Viewport->Window == window) ++ window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); ++ } ++ else ++ { ++ // Merge into host viewport? ++ // We cannot test window->ViewportOwned as it set lower in the function. ++ // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212) ++ bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap)); ++ if (try_to_merge_into_host_viewport) ++ UpdateTryMergeWindowIntoHostViewports(window); ++ } ++ ++ // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport ++ if (window->Viewport == NULL) ++ if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport)) ++ window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); ++ ++ // Mark window as allowed to protrude outside of its viewport and into the current monitor ++ if (!lock_viewport) ++ { ++ if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) ++ { ++ // We need to take account of the possibility that mouse may become invalid. ++ // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds. ++ ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos; ++ bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow); ++ bool mouse_valid = IsMousePosValid(&mouse_ref); ++ if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid)) ++ window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos()); ++ else ++ window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; ++ } ++ else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL) ++ { ++ // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code. ++ const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true; ++ if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible) ++ { ++ // Steal/transfer ownership ++ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name); ++ window->Viewport->Window = window; ++ window->Viewport->ID = window->ID; ++ window->Viewport->LastNameHash = 0; ++ } ++ else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge? ++ { ++ // New viewport ++ window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); ++ } ++ } ++ else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0) ++ { ++ // Regular (non-child, non-popup) windows by default are also allowed to protrude ++ // Child windows are kept contained within their parent. ++ window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; ++ } ++ } ++ ++ // Update flags ++ window->ViewportOwned = (window == window->Viewport->Window); ++ window->ViewportId = window->Viewport->ID; ++ ++ // If the OS window has a title bar, hide our imgui title bar ++ //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration)) ++ // window->Flags |= ImGuiWindowFlags_NoTitleBar; ++} ++ ++void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack) ++{ ++ ImGuiContext& g = *GImGui; ++ ++ bool viewport_rect_changed = false; ++ ++ // Synchronize window --> viewport in most situations ++ // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM ++ if (window->Viewport->PlatformRequestMove) ++ { ++ window->Pos = window->Viewport->Pos; ++ MarkIniSettingsDirty(window); ++ } ++ else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0) ++ { ++ viewport_rect_changed = true; ++ window->Viewport->Pos = window->Pos; ++ } ++ ++ if (window->Viewport->PlatformRequestResize) ++ { ++ window->Size = window->SizeFull = window->Viewport->Size; ++ MarkIniSettingsDirty(window); ++ } ++ else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0) ++ { ++ viewport_rect_changed = true; ++ window->Viewport->Size = window->Size; ++ } ++ window->Viewport->UpdateWorkRect(); ++ ++ // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame() ++ // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect. ++ if (viewport_rect_changed) ++ UpdateViewportPlatformMonitor(window->Viewport); ++ ++ // Update common viewport flags ++ const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear; ++ ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear; ++ ImGuiWindowFlags window_flags = window->Flags; ++ const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0; ++ const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0; ++ if (window_flags & ImGuiWindowFlags_Tooltip) ++ viewport_flags |= ImGuiViewportFlags_TopMost; ++ if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal) ++ viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon; ++ if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window) ++ viewport_flags |= ImGuiViewportFlags_NoDecoration; ++ ++ // Not correct to set modal as topmost because: ++ // - Because other popups can be stacked above a modal (e.g. combo box in a modal) ++ // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost" ++ //if (flags & ImGuiWindowFlags_Modal) ++ // viewport_flags |= ImGuiViewportFlags_TopMost; ++ ++ // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them ++ // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration). ++ // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app, ++ // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere. ++ if (is_short_lived_floating_window && !is_modal) ++ viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick; ++ ++ // We can overwrite viewport flags using ImGuiWindowClass (advanced users) ++ if (window->WindowClass.ViewportFlagsOverrideSet) ++ viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet; ++ if (window->WindowClass.ViewportFlagsOverrideClear) ++ viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear; ++ ++ // We can also tell the backend that clearing the platform window won't be necessary, ++ // as our window background is filling the viewport and we have disabled BgAlpha. ++ // FIXME: Work on support for per-viewport transparency (#2766) ++ if (!(window_flags & ImGuiWindowFlags_NoBackground)) ++ viewport_flags |= ImGuiViewportFlags_NoRendererClear; ++ ++ window->Viewport->Flags = viewport_flags; ++ ++ // Update parent viewport ID ++ // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport()) ++ if (window->WindowClass.ParentViewportId != (ImGuiID)-1) ++ window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId; ++ else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive)) ++ window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID; ++ else ++ window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID; ++} ++ ++// Called by user at the end of the main loop, after EndFrame() ++// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api. ++void ImGui::UpdatePlatformWindows() ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?"); ++ IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount); ++ g.FrameCountPlatformEnded = g.FrameCount; ++ if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) ++ return; ++ ++ // Create/resize/destroy platform windows to match each active viewport. ++ // Skip the main viewport (index 0), which is always fully handled by the application! ++ for (int i = 1; i < g.Viewports.Size; i++) ++ { ++ ImGuiViewportP* viewport = g.Viewports[i]; ++ ++ // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window ++ // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame) ++ bool destroy_platform_window = false; ++ destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1); ++ destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)); ++ if (destroy_platform_window) ++ { ++ DestroyPlatformWindow(viewport); ++ continue; ++ } ++ ++ // New windows that appears directly in a new viewport won't always have a size on their first frame ++ if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0) ++ continue; ++ ++ // Create window ++ const bool is_new_platform_window = (viewport->PlatformWindowCreated == false); ++ if (is_new_platform_window) ++ { ++ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); ++ g.PlatformIO.Platform_CreateWindow(viewport); ++ if (g.PlatformIO.Renderer_CreateWindow != NULL) ++ g.PlatformIO.Renderer_CreateWindow(viewport); ++ g.PlatformWindowsCreatedCount++; ++ viewport->LastNameHash = 0; ++ viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?) ++ viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it. ++ viewport->PlatformWindowCreated = true; ++ } ++ ++ // Apply Position and Size (from ImGui to Platform/Renderer backends) ++ if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove) ++ g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos); ++ if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize) ++ g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size); ++ if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize) ++ g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size); ++ viewport->LastPlatformPos = viewport->Pos; ++ viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size; ++ ++ // Update title bar (if it changed) ++ if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window)) ++ { ++ const char* title_begin = window_for_title->Name; ++ char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin); ++ const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin); ++ if (viewport->LastNameHash != title_hash) ++ { ++ char title_end_backup_c = *title_end; ++ *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain. ++ g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin); ++ *title_end = title_end_backup_c; ++ viewport->LastNameHash = title_hash; ++ } ++ } ++ ++ // Update alpha (if it changed) ++ if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha) ++ g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha); ++ viewport->LastAlpha = viewport->Alpha; ++ ++ // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed. ++ if (g.PlatformIO.Platform_UpdateWindow) ++ g.PlatformIO.Platform_UpdateWindow(viewport); ++ ++ if (is_new_platform_window) ++ { ++ // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late) ++ if (g.FrameCount < 3) ++ viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing; ++ ++ // Show window ++ g.PlatformIO.Platform_ShowWindow(viewport); ++ ++ // Even without focus, we assume the window becomes front-most. ++ // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available. ++ if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount) ++ viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount; ++ } ++ ++ // Clear request flags ++ viewport->ClearRequestFlags(); ++ } ++} ++ ++// This is a default/basic function for performing the rendering/swap of multiple Platform Windows. ++// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves. ++// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself: ++// ++// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ++// for (int i = 1; i < platform_io.Viewports.Size; i++) ++// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) ++// MyRenderFunction(platform_io.Viewports[i], my_args); ++// for (int i = 1; i < platform_io.Viewports.Size; i++) ++// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) ++// MySwapBufferFunction(platform_io.Viewports[i], my_args); ++// ++void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg) ++{ ++ // Skip the main viewport (index 0), which is always fully handled by the application! ++ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ++ for (int i = 1; i < platform_io.Viewports.Size; i++) ++ { ++ ImGuiViewport* viewport = platform_io.Viewports[i]; ++ if (viewport->Flags & ImGuiViewportFlags_IsMinimized) ++ continue; ++ if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg); ++ if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg); ++ } ++ for (int i = 1; i < platform_io.Viewports.Size; i++) ++ { ++ ImGuiViewport* viewport = platform_io.Viewports[i]; ++ if (viewport->Flags & ImGuiViewportFlags_IsMinimized) ++ continue; ++ if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg); ++ if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg); ++ } ++} ++ ++static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos) ++{ ++ ImGuiContext& g = *GImGui; ++ for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) ++ { ++ const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; ++ if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos)) ++ return monitor_n; ++ } ++ return -1; ++} ++ ++// Search for the monitor with the largest intersection area with the given rectangle ++// We generally try to avoid searching loops but the monitor count should be very small here ++// FIXME-OPT: We could test the last monitor used for that viewport first, and early ++static int ImGui::FindPlatformMonitorForRect(const ImRect& rect) ++{ ++ ImGuiContext& g = *GImGui; ++ ++ const int monitor_count = g.PlatformIO.Monitors.Size; ++ if (monitor_count <= 1) ++ return monitor_count - 1; ++ ++ // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position. ++ // This is necessary for tooltips which always resize down to zero at first. ++ const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f); ++ int best_monitor_n = -1; ++ float best_monitor_surface = 0.001f; ++ ++ for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++) ++ { ++ const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; ++ const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize); ++ if (monitor_rect.Contains(rect)) ++ return monitor_n; ++ ImRect overlapping_rect = rect; ++ overlapping_rect.ClipWithFull(monitor_rect); ++ float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight(); ++ if (overlapping_surface < best_monitor_surface) ++ continue; ++ best_monitor_surface = overlapping_surface; ++ best_monitor_n = monitor_n; ++ } ++ return best_monitor_n; ++} ++ ++// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor) ++static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport) ++{ ++ viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect()); ++} ++ ++// Return value is always != NULL, but don't hold on it across frames. ++const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p; ++ int monitor_idx = viewport->PlatformMonitor; ++ if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size) ++ return &g.PlatformIO.Monitors[monitor_idx]; ++ return &g.FallbackMonitor; ++} ++ ++void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport) ++{ ++ ImGuiContext& g = *GImGui; ++ if (viewport->PlatformWindowCreated) ++ { ++ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); ++ if (g.PlatformIO.Renderer_DestroyWindow) ++ g.PlatformIO.Renderer_DestroyWindow(viewport); ++ if (g.PlatformIO.Platform_DestroyWindow) ++ g.PlatformIO.Platform_DestroyWindow(viewport); ++ IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL); ++ ++ // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize() ++ // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public. ++ if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID) ++ viewport->PlatformWindowCreated = false; ++ } ++ else ++ { ++ IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL); ++ } ++ viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL; ++ viewport->ClearRequestFlags(); ++} ++ ++void ImGui::DestroyPlatformWindows() ++{ ++ // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend ++ // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData. ++ // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling ++ // code to operator a consistent manner. ++ // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without ++ // crashing if it doesn't have data stored. ++ ImGuiContext& g = *GImGui; ++ for (ImGuiViewportP* viewport : g.Viewports) ++ DestroyPlatformWindow(viewport); ++} ++ ++ ++//----------------------------------------------------------------------------- ++// [SECTION] DOCKING ++//----------------------------------------------------------------------------- ++// Docking: Internal Types ++// Docking: Forward Declarations ++// Docking: ImGuiDockContext ++// Docking: ImGuiDockContext Docking/Undocking functions ++// Docking: ImGuiDockNode ++// Docking: ImGuiDockNode Tree manipulation functions ++// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) ++// Docking: Builder Functions ++// Docking: Begin/End Support Functions (called from Begin/End) ++// Docking: Settings ++//----------------------------------------------------------------------------- ++ ++//----------------------------------------------------------------------------- ++// Typical Docking call flow: (root level is generally public API): ++//----------------------------------------------------------------------------- ++// - NewFrame() new dear imgui frame ++// | DockContextNewFrameUpdateUndocking() - process queued undocking requests ++// | - DockContextProcessUndockWindow() - process one window undocking request ++// | - DockContextProcessUndockNode() - process one whole node undocking request ++// | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes ++// | - update g.HoveredDockNode - [debug] update node hovered by mouse ++// | - DockContextProcessDock() - process one docking request ++// | - DockNodeUpdate() ++// | - DockNodeUpdateForRootNode() ++// | - DockNodeUpdateFlagsAndCollapse() ++// | - DockNodeFindInfo() ++// | - destroy unused node or tab bar ++// | - create dock node host window ++// | - Begin() etc. ++// | - DockNodeStartMouseMovingWindow() ++// | - DockNodeTreeUpdatePosSize() ++// | - DockNodeTreeUpdateSplitter() ++// | - draw node background ++// | - DockNodeUpdateTabBar() - create/update tab bar for a docking node ++// | - DockNodeAddTabBar() ++// | - DockNodeWindowMenuUpdate() ++// | - DockNodeCalcTabBarLayout() ++// | - BeginTabBarEx() ++// | - TabItemEx() calls ++// | - EndTabBar() ++// | - BeginDockableDragDropTarget() ++// | - DockNodeUpdate() - recurse into child nodes... ++//----------------------------------------------------------------------------- ++// - DockSpace() user submit a dockspace into a window ++// | Begin(Child) - create a child window ++// | DockNodeUpdate() - call main dock node update function ++// | End(Child) ++// | ItemSize() ++//----------------------------------------------------------------------------- ++// - Begin() ++// | BeginDocked() ++// | BeginDockableDragDropSource() ++// | BeginDockableDragDropTarget() ++// | - DockNodePreviewDockRender() ++//----------------------------------------------------------------------------- ++// - EndFrame() ++// | DockContextEndFrame() ++//----------------------------------------------------------------------------- ++ ++//----------------------------------------------------------------------------- ++// Docking: Internal Types ++//----------------------------------------------------------------------------- ++// - ImGuiDockRequestType ++// - ImGuiDockRequest ++// - ImGuiDockPreviewData ++// - ImGuiDockNodeSettings ++// - ImGuiDockContext ++//----------------------------------------------------------------------------- ++ ++enum ImGuiDockRequestType ++{ ++ ImGuiDockRequestType_None = 0, ++ ImGuiDockRequestType_Dock, ++ ImGuiDockRequestType_Undock, ++ ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload ++}; ++ ++struct ImGuiDockRequest ++{ ++ ImGuiDockRequestType Type; ++ ImGuiWindow* DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL) ++ ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into ++ ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional] ++ ImGuiDir DockSplitDir; ++ float DockSplitRatio; ++ bool DockSplitOuter; ++ ImGuiWindow* UndockTargetWindow; ++ ImGuiDockNode* UndockTargetNode; ++ ++ ImGuiDockRequest() ++ { ++ Type = ImGuiDockRequestType_None; ++ DockTargetWindow = DockPayload = UndockTargetWindow = NULL; ++ DockTargetNode = UndockTargetNode = NULL; ++ DockSplitDir = ImGuiDir_None; ++ DockSplitRatio = 0.5f; ++ DockSplitOuter = false; ++ } ++}; ++ ++struct ImGuiDockPreviewData ++{ ++ ImGuiDockNode FutureNode; ++ bool IsDropAllowed; ++ bool IsCenterAvailable; ++ bool IsSidesAvailable; // Hold your breath, grammar freaks.. ++ bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window) ++ ImGuiDockNode* SplitNode; ++ ImGuiDir SplitDir; ++ float SplitRatio; ++ ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects() ++ ++ ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); } ++}; ++ ++// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes) ++struct ImGuiDockNodeSettings ++{ ++ ImGuiID ID; ++ ImGuiID ParentNodeId; ++ ImGuiID ParentWindowId; ++ ImGuiID SelectedTabId; ++ signed char SplitAxis; ++ char Depth; ++ ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_) ++ ImVec2ih Pos; ++ ImVec2ih Size; ++ ImVec2ih SizeRef; ++ ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; } ++}; ++ ++//----------------------------------------------------------------------------- ++// Docking: Forward Declarations ++//----------------------------------------------------------------------------- ++ ++namespace ImGui ++{ ++ // ImGuiDockContext ++ static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id); ++ static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node); ++ static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node); ++ static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req); ++ static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx); ++ static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window); ++ static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count); ++ static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all ++ ++ // ImGuiDockNode ++ static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar); ++ static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node); ++ static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node); ++ static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id); ++ static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node); ++ static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id); ++ static void DockNodeHideHostWindow(ImGuiDockNode* node); ++ static void DockNodeUpdate(ImGuiDockNode* node); ++ static void DockNodeUpdateForRootNode(ImGuiDockNode* node); ++ static void DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node); ++ static void DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node); ++ static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window); ++ static void DockNodeAddTabBar(ImGuiDockNode* node); ++ static void DockNodeRemoveTabBar(ImGuiDockNode* node); ++ static void DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar); ++ static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node); ++ static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window); ++ static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window); ++ static void DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking); ++ static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data); ++ static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos); ++ static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired); ++ static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos); ++ static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; } ++ static int DockNodeGetTabOrder(ImGuiWindow* window); ++ ++ // ImGuiDockNode tree manipulations ++ static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node); ++ static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child); ++ static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL); ++ static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node); ++ static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos); ++ static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node); ++ ++ // Settings ++ static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id); ++ static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count); ++ static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id); ++ static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); ++ static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); ++ static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); ++ static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); ++ static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf); ++} ++ ++//----------------------------------------------------------------------------- ++// Docking: ImGuiDockContext ++//----------------------------------------------------------------------------- ++// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings, ++// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active. ++// At boot time only, we run a simple GC to remove nodes that have no references. ++// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures), ++// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does). ++// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data. ++//----------------------------------------------------------------------------- ++// - DockContextInitialize() ++// - DockContextShutdown() ++// - DockContextClearNodes() ++// - DockContextRebuildNodes() ++// - DockContextNewFrameUpdateUndocking() ++// - DockContextNewFrameUpdateDocking() ++// - DockContextEndFrame() ++// - DockContextFindNodeByID() ++// - DockContextBindNodeToWindow() ++// - DockContextGenNodeID() ++// - DockContextAddNode() ++// - DockContextRemoveNode() ++// - ImGuiDockContextPruneNodeData ++// - DockContextPruneUnusedSettingsNodes() ++// - DockContextBuildNodesFromSettings() ++// - DockContextBuildAddWindowsToNodes() ++//----------------------------------------------------------------------------- ++ ++void ImGui::DockContextInitialize(ImGuiContext* ctx) ++{ ++ ImGuiContext& g = *ctx; ++ ++ // Add .ini handle for persistent docking data ++ ImGuiSettingsHandler ini_handler; ++ ini_handler.TypeName = "Docking"; ++ ini_handler.TypeHash = ImHashStr("Docking"); ++ ini_handler.ClearAllFn = DockSettingsHandler_ClearAll; ++ ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read ++ ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen; ++ ini_handler.ReadLineFn = DockSettingsHandler_ReadLine; ++ ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; ++ ini_handler.WriteAllFn = DockSettingsHandler_WriteAll; ++ g.SettingsHandlers.push_back(ini_handler); ++ ++ g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default; ++} ++ ++void ImGui::DockContextShutdown(ImGuiContext* ctx) ++{ ++ ImGuiDockContext* dc = &ctx->DockContext; ++ for (int n = 0; n < dc->Nodes.Data.Size; n++) ++ if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) ++ IM_DELETE(node); ++} ++ ++void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs) ++{ ++ IM_UNUSED(ctx); ++ IM_ASSERT(ctx == GImGui); ++ DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs); ++ DockBuilderRemoveNodeChildNodes(root_id); ++} ++ ++// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch ++// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!) ++void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) ++{ ++ ImGuiContext& g = *ctx; ++ ImGuiDockContext* dc = &ctx->DockContext; ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n"); ++ SaveIniSettingsToMemory(); ++ ImGuiID root_id = 0; // Rebuild all ++ DockContextClearNodes(ctx, root_id, false); ++ DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); ++ DockContextBuildAddWindowsToNodes(ctx, root_id); ++} ++ ++// Docking context update function, called by NewFrame() ++void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx) ++{ ++ ImGuiContext& g = *ctx; ++ ImGuiDockContext* dc = &ctx->DockContext; ++ if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) ++ { ++ if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0) ++ DockContextClearNodes(ctx, 0, true); ++ return; ++ } ++ ++ // Setting NoSplit at runtime merges all nodes ++ if (g.IO.ConfigDockingNoSplit) ++ for (int n = 0; n < dc->Nodes.Data.Size; n++) ++ if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) ++ if (node->IsRootNode() && node->IsSplitNode()) ++ { ++ DockBuilderRemoveNodeChildNodes(node->ID); ++ //dc->WantFullRebuild = true; ++ } ++ ++ // Process full rebuild ++#if 0 ++ if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C))) ++ dc->WantFullRebuild = true; ++#endif ++ if (dc->WantFullRebuild) ++ { ++ DockContextRebuildNodes(ctx); ++ dc->WantFullRebuild = false; ++ } ++ ++ // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame) ++ for (ImGuiDockRequest& req : dc->Requests) ++ { ++ if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow) ++ DockContextProcessUndockWindow(ctx, req.UndockTargetWindow); ++ else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode) ++ DockContextProcessUndockNode(ctx, req.UndockTargetNode); ++ } ++} ++ ++// Docking context update function, called by NewFrame() ++void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx) ++{ ++ ImGuiContext& g = *ctx; ++ ImGuiDockContext* dc = &ctx->DockContext; ++ if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) ++ return; ++ ++ // [DEBUG] Store hovered dock node. ++ // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut. ++ // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering. ++ g.DebugHoveredDockNode = NULL; ++ if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow) ++ { ++ if (hovered_window->DockNodeAsHost) ++ g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos); ++ else if (hovered_window->RootWindow->DockNode) ++ g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode; ++ } ++ ++ // Process Docking requests ++ for (ImGuiDockRequest& req : dc->Requests) ++ if (req.Type == ImGuiDockRequestType_Dock) ++ DockContextProcessDock(ctx, &req); ++ dc->Requests.resize(0); ++ ++ // Create windows for each automatic docking nodes ++ // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high) ++ for (int n = 0; n < dc->Nodes.Data.Size; n++) ++ if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) ++ if (node->IsFloatingNode()) ++ DockNodeUpdate(node); ++} ++ ++void ImGui::DockContextEndFrame(ImGuiContext* ctx) ++{ ++ // Draw backgrounds of node missing their window ++ ImGuiContext& g = *ctx; ++ ImGuiDockContext* dc = &g.DockContext; ++ for (int n = 0; n < dc->Nodes.Data.Size; n++) ++ if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) ++ if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame) ++ { ++ ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size); ++ ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize); ++ node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG); ++ node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags); ++ } ++} ++ ++ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id) ++{ ++ return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id); ++} ++ ++ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx) ++{ ++ // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used) ++ // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0 ++ // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted. ++ ImGuiID id = 0x0001; ++ while (DockContextFindNodeByID(ctx, id) != NULL) ++ id++; ++ return id; ++} ++ ++static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id) ++{ ++ // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window. ++ ImGuiContext& g = *ctx; ++ if (id == 0) ++ id = DockContextGenNodeID(ctx); ++ else ++ IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL); ++ ++ // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings! ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id); ++ ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id); ++ ctx->DockContext.Nodes.SetVoidPtr(node->ID, node); ++ return node; ++} ++ ++static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node) ++{ ++ ImGuiContext& g = *ctx; ++ ImGuiDockContext* dc = &ctx->DockContext; ++ ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID); ++ IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node); ++ IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL); ++ IM_ASSERT(node->Windows.Size == 0); ++ ++ if (node->HostWindow) ++ node->HostWindow->DockNodeAsHost = NULL; ++ ++ ImGuiDockNode* parent_node = node->ParentNode; ++ const bool merge = (merge_sibling_into_parent_node && parent_node != NULL); ++ if (merge) ++ { ++ IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node); ++ ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]); ++ DockNodeTreeMerge(&g, parent_node, sibling_node); ++ } ++ else ++ { ++ for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++) ++ if (parent_node->ChildNodes[n] == node) ++ node->ParentNode->ChildNodes[n] = NULL; ++ dc->Nodes.SetVoidPtr(node->ID, NULL); ++ IM_DELETE(node); ++ } ++} ++ ++static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs) ++{ ++ const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs; ++ const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs; ++ return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a); ++} ++ ++// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here. ++struct ImGuiDockContextPruneNodeData ++{ ++ int CountWindows, CountChildWindows, CountChildNodes; ++ ImGuiID RootId; ++ ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; } ++}; ++ ++// Garbage collect unused nodes (run once at init time) ++static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) ++{ ++ ImGuiContext& g = *ctx; ++ ImGuiDockContext* dc = &ctx->DockContext; ++ IM_ASSERT(g.Windows.Size == 0); ++ ++ ImPool pool; ++ pool.Reserve(dc->NodesSettings.Size); ++ ++ // Count child nodes and compute RootID ++ for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) ++ { ++ ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ++ ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0; ++ pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID; ++ if (settings->ParentNodeId) ++ pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++; ++ } ++ ++ // Count reference to dock ids from dockspaces ++ // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes() ++ for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) ++ { ++ ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ++ if (settings->ParentWindowId != 0) ++ if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId)) ++ if (window_settings->DockId) ++ if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId)) ++ data->CountChildNodes++; ++ } ++ ++ // Count reference to dock ids from window settings ++ // We guard against the possibility of an invalid .ini file (RootID may point to a missing node) ++ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) ++ if (ImGuiID dock_id = settings->DockId) ++ if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id)) ++ { ++ data->CountWindows++; ++ if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId)) ++ data_root->CountChildWindows++; ++ } ++ ++ // Prune ++ for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) ++ { ++ ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ++ ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID); ++ if (data->CountWindows > 1) ++ continue; ++ ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId); ++ ++ bool remove = false; ++ remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window ++ remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window ++ remove |= (data_root->CountChildWindows == 0); ++ if (remove) ++ { ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID); ++ DockSettingsRemoveNodeReferences(&settings->ID, 1); ++ settings->ID = 0; ++ } ++ } ++} ++ ++static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count) ++{ ++ // Build nodes ++ for (int node_n = 0; node_n < node_settings_count; node_n++) ++ { ++ ImGuiDockNodeSettings* settings = &node_settings_array[node_n]; ++ if (settings->ID == 0) ++ continue; ++ ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID); ++ node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL; ++ node->Pos = ImVec2(settings->Pos.x, settings->Pos.y); ++ node->Size = ImVec2(settings->Size.x, settings->Size.y); ++ node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y); ++ node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode; ++ if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL) ++ node->ParentNode->ChildNodes[0] = node; ++ else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL) ++ node->ParentNode->ChildNodes[1] = node; ++ node->SelectedTabId = settings->SelectedTabId; ++ node->SplitAxis = (ImGuiAxis)settings->SplitAxis; ++ node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_); ++ ++ // Bind host window immediately if it already exist (in case of a rebuild) ++ // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set. ++ char host_window_title[20]; ++ ImGuiDockNode* root_node = DockNodeGetRootNode(node); ++ node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title))); ++ } ++} ++ ++void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id) ++{ ++ // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame) ++ ImGuiContext& g = *ctx; ++ for (ImGuiWindow* window : g.Windows) ++ { ++ if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1) ++ continue; ++ if (window->DockNode != NULL) ++ continue; ++ ++ ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId); ++ IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings() ++ if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id) ++ DockNodeAddWindow(node, window, true); ++ } ++} ++ ++//----------------------------------------------------------------------------- ++// Docking: ImGuiDockContext Docking/Undocking functions ++//----------------------------------------------------------------------------- ++// - DockContextQueueDock() ++// - DockContextQueueUndockWindow() ++// - DockContextQueueUndockNode() ++// - DockContextQueueNotifyRemovedNode() ++// - DockContextProcessDock() ++// - DockContextProcessUndockWindow() ++// - DockContextProcessUndockNode() ++// - DockContextCalcDropPosForDocking() ++//----------------------------------------------------------------------------- ++ ++void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer) ++{ ++ IM_ASSERT(target != payload); ++ ImGuiDockRequest req; ++ req.Type = ImGuiDockRequestType_Dock; ++ req.DockTargetWindow = target; ++ req.DockTargetNode = target_node; ++ req.DockPayload = payload; ++ req.DockSplitDir = split_dir; ++ req.DockSplitRatio = split_ratio; ++ req.DockSplitOuter = split_outer; ++ ctx->DockContext.Requests.push_back(req); ++} ++ ++void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window) ++{ ++ ImGuiDockRequest req; ++ req.Type = ImGuiDockRequestType_Undock; ++ req.UndockTargetWindow = window; ++ ctx->DockContext.Requests.push_back(req); ++} ++ ++void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) ++{ ++ ImGuiDockRequest req; ++ req.Type = ImGuiDockRequestType_Undock; ++ req.UndockTargetNode = node; ++ ctx->DockContext.Requests.push_back(req); ++} ++ ++void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node) ++{ ++ ImGuiDockContext* dc = &ctx->DockContext; ++ for (ImGuiDockRequest& req : dc->Requests) ++ if (req.DockTargetNode == node) ++ req.Type = ImGuiDockRequestType_None; ++} ++ ++void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) ++{ ++ IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL)); ++ IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL); ++ ++ ImGuiContext& g = *ctx; ++ IM_UNUSED(g); ++ ++ ImGuiWindow* payload_window = req->DockPayload; // Optional ++ ImGuiWindow* target_window = req->DockTargetWindow; ++ ImGuiDockNode* node = req->DockTargetNode; ++ if (payload_window) ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir); ++ else ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir); ++ ++ // Decide which Tab will be selected at the end of the operation ++ ImGuiID next_selected_id = 0; ++ ImGuiDockNode* payload_node = NULL; ++ if (payload_window) ++ { ++ payload_node = payload_window->DockNodeAsHost; ++ payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later. ++ if (payload_node && payload_node->IsLeafNode()) ++ next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId; ++ if (payload_node == NULL) ++ next_selected_id = payload_window->TabId; ++ } ++ ++ // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well ++ // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==. ++ if (node) ++ IM_ASSERT(node->LastFrameAlive <= g.FrameCount); ++ if (node && target_window && node == target_window->DockNodeAsHost) ++ IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode()); ++ ++ // Create new node and add existing window to it ++ if (node == NULL) ++ { ++ node = DockContextAddNode(ctx, 0); ++ node->Pos = target_window->Pos; ++ node->Size = target_window->Size; ++ if (target_window->DockNodeAsHost == NULL) ++ { ++ DockNodeAddWindow(node, target_window, true); ++ node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted; ++ target_window->DockIsActive = true; ++ } ++ } ++ ++ ImGuiDir split_dir = req->DockSplitDir; ++ if (split_dir != ImGuiDir_None) ++ { ++ // Split into two, one side will be our payload node unless we are dropping a loose window ++ const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; ++ const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side ++ const float split_ratio = req->DockSplitRatio; ++ DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here! ++ ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1]; ++ new_node->HostWindow = node->HostWindow; ++ node = new_node; ++ } ++ node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar); ++ ++ if (node != payload_node) ++ { ++ // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!) ++ if (node->Windows.Size > 0 && node->TabBar == NULL) ++ { ++ DockNodeAddTabBar(node); ++ for (int n = 0; n < node->Windows.Size; n++) ++ TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]); ++ } ++ ++ if (payload_node != NULL) ++ { ++ // Transfer full payload node (with 1+ child windows or child nodes) ++ if (payload_node->IsSplitNode()) ++ { ++ if (node->Windows.Size > 0) ++ { ++ // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node. ++ // In this situation, we move the windows of the target node into the currently visible node of the payload. ++ // This allows us to preserve some of the underlying dock tree settings nicely. ++ IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted. ++ ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows; ++ if (visible_node->TabBar) ++ IM_ASSERT(visible_node->TabBar->Tabs.Size > 0); ++ DockNodeMoveWindows(node, visible_node); ++ DockNodeMoveWindows(visible_node, node); ++ DockSettingsRenameNodeReferences(node->ID, visible_node->ID); ++ } ++ if (node->IsCentralNode()) ++ { ++ // Central node property needs to be moved to a leaf node, pick the last focused one. ++ // FIXME-DOCK: If we had to transfer other flags here, what would the policy be? ++ ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId); ++ IM_ASSERT(last_focused_node != NULL); ++ ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node); ++ IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node)); ++ last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode); ++ node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode); ++ last_focused_root_node->CentralNode = last_focused_node; ++ } ++ ++ IM_ASSERT(node->Windows.Size == 0); ++ DockNodeMoveChildNodes(node, payload_node); ++ } ++ else ++ { ++ const ImGuiID payload_dock_id = payload_node->ID; ++ DockNodeMoveWindows(node, payload_node); ++ DockSettingsRenameNodeReferences(payload_dock_id, node->ID); ++ } ++ DockContextRemoveNode(ctx, payload_node, true); ++ } ++ else if (payload_window) ++ { ++ // Transfer single window ++ const ImGuiID payload_dock_id = payload_window->DockId; ++ node->VisibleWindow = payload_window; ++ DockNodeAddWindow(node, payload_window, true); ++ if (payload_dock_id != 0) ++ DockSettingsRenameNodeReferences(payload_dock_id, node->ID); ++ } ++ } ++ else ++ { ++ // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar ++ node->WantHiddenTabBarUpdate = true; ++ } ++ ++ // Update selection immediately ++ if (ImGuiTabBar* tab_bar = node->TabBar) ++ tab_bar->NextSelectedTabId = next_selected_id; ++ MarkIniSettingsDirty(); ++} ++ ++// Problem: ++// Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more ++// than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic ++// with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be ++// due to missing ImGuiBackendFlags_HasMouseCursors backend flag). ++// Solution: ++// When undocking a window we currently force its maximum size to 90% of the host viewport or monitor. ++// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch). ++static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport) ++{ ++ if (ref_viewport == NULL) ++ return size; ++ ++ ImGuiContext& g = *GImGui; ++ ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f); ++ if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) ++ { ++ const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport); ++ max_size = ImTrunc(monitor->WorkSize * 0.90f); ++ } ++ return ImMin(size, max_size); ++} ++ ++void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref) ++{ ++ ImGuiContext& g = *ctx; ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref); ++ if (window->DockNode) ++ DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId); ++ else ++ window->DockId = 0; ++ window->Collapsed = false; ++ window->DockIsActive = false; ++ window->DockNodeIsVisible = window->DockTabIsVisible = false; ++ window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport); ++ ++ MarkIniSettingsDirty(); ++} ++ ++void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) ++{ ++ ImGuiContext& g = *ctx; ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID); ++ IM_ASSERT(node->IsLeafNode()); ++ IM_ASSERT(node->Windows.Size >= 1); ++ ++ if (node->IsRootNode() || node->IsCentralNode()) ++ { ++ // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload. ++ ImGuiDockNode* new_node = DockContextAddNode(ctx, 0); ++ new_node->Pos = node->Pos; ++ new_node->Size = node->Size; ++ new_node->SizeRef = node->SizeRef; ++ DockNodeMoveWindows(new_node, node); ++ DockSettingsRenameNodeReferences(node->ID, new_node->ID); ++ node = new_node; ++ } ++ else ++ { ++ // Otherwise extract our node and merge our sibling back into the parent node. ++ IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); ++ int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1; ++ node->ParentNode->ChildNodes[index_in_parent] = NULL; ++ DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]); ++ node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport ++ node->ParentNode = NULL; ++ } ++ for (ImGuiWindow* window : node->Windows) ++ { ++ window->Flags &= ~ImGuiWindowFlags_ChildWindow; ++ if (window->ParentWindow) ++ window->ParentWindow->DC.ChildWindows.find_erase(window); ++ UpdateWindowParentAndRootLinks(window, window->Flags, NULL); ++ } ++ node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode; ++ node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport); ++ node->WantMouseMove = true; ++ MarkIniSettingsDirty(); ++} ++ ++// This is mostly used for automation. ++bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos) ++{ ++ if (target != NULL && target_node == NULL) ++ target_node = target->DockNode; ++ ++ // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects ++ // (which would be functionally identical) we only show the outer one. Reflect this here. ++ if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None) ++ split_outer = true; ++ ImGuiDockPreviewData split_data; ++ DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer); ++ if (split_data.DropRectsDraw[split_dir+1].IsInverted()) ++ return false; ++ *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter(); ++ return true; ++} ++ ++//----------------------------------------------------------------------------- ++// Docking: ImGuiDockNode ++//----------------------------------------------------------------------------- ++// - DockNodeGetTabOrder() ++// - DockNodeAddWindow() ++// - DockNodeRemoveWindow() ++// - DockNodeMoveChildNodes() ++// - DockNodeMoveWindows() ++// - DockNodeApplyPosSizeToWindows() ++// - DockNodeHideHostWindow() ++// - ImGuiDockNodeFindInfoResults ++// - DockNodeFindInfo() ++// - DockNodeFindWindowByID() ++// - DockNodeUpdateFlagsAndCollapse() ++// - DockNodeUpdateHasCentralNodeFlag() ++// - DockNodeUpdateVisibleFlag() ++// - DockNodeStartMouseMovingWindow() ++// - DockNodeUpdate() ++// - DockNodeUpdateWindowMenu() ++// - DockNodeBeginAmendTabBar() ++// - DockNodeEndAmendTabBar() ++// - DockNodeUpdateTabBar() ++// - DockNodeAddTabBar() ++// - DockNodeRemoveTabBar() ++// - DockNodeIsDropAllowedOne() ++// - DockNodeIsDropAllowed() ++// - DockNodeCalcTabBarLayout() ++// - DockNodeCalcSplitRects() ++// - DockNodeCalcDropRectsAndTestMousePos() ++// - DockNodePreviewDockSetup() ++// - DockNodePreviewDockRender() ++//----------------------------------------------------------------------------- ++ ++ImGuiDockNode::ImGuiDockNode(ImGuiID id) ++{ ++ ID = id; ++ SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None; ++ ParentNode = ChildNodes[0] = ChildNodes[1] = NULL; ++ TabBar = NULL; ++ SplitAxis = ImGuiAxis_None; ++ ++ State = ImGuiDockNodeState_Unknown; ++ LastBgColor = IM_COL32_WHITE; ++ HostWindow = VisibleWindow = NULL; ++ CentralNode = OnlyNodeWithWindows = NULL; ++ CountNodeWithWindows = 0; ++ LastFrameAlive = LastFrameActive = LastFrameFocused = -1; ++ LastFocusedNodeId = 0; ++ SelectedTabId = 0; ++ WantCloseTabId = 0; ++ RefViewportId = 0; ++ AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode; ++ AuthorityForViewport = ImGuiDataAuthority_Auto; ++ IsVisible = true; ++ IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false; ++ IsBgDrawnThisFrame = false; ++ WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false; ++} ++ ++ImGuiDockNode::~ImGuiDockNode() ++{ ++ IM_DELETE(TabBar); ++ TabBar = NULL; ++ ChildNodes[0] = ChildNodes[1] = NULL; ++} ++ ++int ImGui::DockNodeGetTabOrder(ImGuiWindow* window) ++{ ++ ImGuiTabBar* tab_bar = window->DockNode->TabBar; ++ if (tab_bar == NULL) ++ return -1; ++ ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId); ++ return tab ? TabBarGetTabOrder(tab_bar, tab) : -1; ++} ++ ++static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window) ++{ ++ window->Hidden = true; ++ window->HiddenFramesCanSkipItems = window->Active ? 1 : 2; ++} ++ ++static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar) ++{ ++ ImGuiContext& g = *GImGui; (void)g; ++ if (window->DockNode) ++ { ++ // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node) ++ IM_ASSERT(window->DockNode->ID != node->ID); ++ DockNodeRemoveWindow(window->DockNode, window, 0); ++ } ++ IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name); ++ ++ // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window, ++ // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame). ++ // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin() ++ if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false) ++ DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]); ++ ++ node->Windows.push_back(window); ++ node->WantHiddenTabBarUpdate = true; ++ window->DockNode = node; ++ window->DockId = node->ID; ++ window->DockIsActive = (node->Windows.Size > 1); ++ window->DockTabWantClose = false; ++ ++ // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage. ++ // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one. ++ if (node->HostWindow == NULL && node->IsFloatingNode()) ++ { ++ if (node->AuthorityForPos == ImGuiDataAuthority_Auto) ++ node->AuthorityForPos = ImGuiDataAuthority_Window; ++ if (node->AuthorityForSize == ImGuiDataAuthority_Auto) ++ node->AuthorityForSize = ImGuiDataAuthority_Window; ++ if (node->AuthorityForViewport == ImGuiDataAuthority_Auto) ++ node->AuthorityForViewport = ImGuiDataAuthority_Window; ++ } ++ ++ // Add to tab bar if requested ++ if (add_to_tab_bar) ++ { ++ if (node->TabBar == NULL) ++ { ++ DockNodeAddTabBar(node); ++ node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId; ++ ++ // Add existing windows ++ for (int n = 0; n < node->Windows.Size - 1; n++) ++ TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]); ++ } ++ TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window); ++ } ++ ++ DockNodeUpdateVisibleFlag(node); ++ ++ // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame. ++ if (node->HostWindow) ++ UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow); ++} ++ ++static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(window->DockNode == node); ++ //IM_ASSERT(window->RootWindowDockTree == node->HostWindow); ++ //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin() ++ IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID); ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name); ++ ++ window->DockNode = NULL; ++ window->DockIsActive = window->DockTabWantClose = false; ++ window->DockId = save_dock_id; ++ window->Flags &= ~ImGuiWindowFlags_ChildWindow; ++ if (window->ParentWindow) ++ window->ParentWindow->DC.ChildWindows.find_erase(window); ++ UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately ++ ++ if (node->HostWindow && node->HostWindow->ViewportOwned) ++ { ++ // When undocking from a user interaction this will always run in NewFrame() and have not much effect. ++ // But mid-frame, if we clear viewport we need to mark window as hidden as well. ++ window->Viewport = NULL; ++ window->ViewportId = 0; ++ window->ViewportOwned = false; ++ window->Hidden = true; ++ } ++ ++ // Remove window ++ bool erased = false; ++ for (int n = 0; n < node->Windows.Size; n++) ++ if (node->Windows[n] == window) ++ { ++ node->Windows.erase(node->Windows.Data + n); ++ erased = true; ++ break; ++ } ++ if (!erased) ++ IM_ASSERT(erased); ++ if (node->VisibleWindow == window) ++ node->VisibleWindow = NULL; ++ ++ // Remove tab and possibly tab bar ++ node->WantHiddenTabBarUpdate = true; ++ if (node->TabBar) ++ { ++ TabBarRemoveTab(node->TabBar, window->TabId); ++ const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2; ++ if (node->Windows.Size < tab_count_threshold_for_tab_bar) ++ DockNodeRemoveTabBar(node); ++ } ++ ++ if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID) ++ { ++ // Automatic dock node delete themselves if they are not holding at least one tab ++ DockContextRemoveNode(&g, node, true); ++ return; ++ } ++ ++ if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow) ++ { ++ ImGuiWindow* remaining_window = node->Windows[0]; ++ // Note: we used to transport viewport ownership here. ++ remaining_window->Collapsed = node->HostWindow->Collapsed; ++ } ++ ++ // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree ++ DockNodeUpdateVisibleFlag(node); ++} ++ ++static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node) ++{ ++ IM_ASSERT(dst_node->Windows.Size == 0); ++ dst_node->ChildNodes[0] = src_node->ChildNodes[0]; ++ dst_node->ChildNodes[1] = src_node->ChildNodes[1]; ++ if (dst_node->ChildNodes[0]) ++ dst_node->ChildNodes[0]->ParentNode = dst_node; ++ if (dst_node->ChildNodes[1]) ++ dst_node->ChildNodes[1]->ParentNode = dst_node; ++ dst_node->SplitAxis = src_node->SplitAxis; ++ dst_node->SizeRef = src_node->SizeRef; ++ src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL; ++} ++ ++static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node) ++{ ++ // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered) ++ IM_ASSERT(src_node && dst_node && dst_node != src_node); ++ ImGuiTabBar* src_tab_bar = src_node->TabBar; ++ if (src_tab_bar != NULL) ++ IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size); ++ ++ // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.) ++ bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL); ++ if (move_tab_bar) ++ { ++ dst_node->TabBar = src_node->TabBar; ++ src_node->TabBar = NULL; ++ } ++ ++ // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar(). ++ for (ImGuiWindow* window : src_node->Windows) ++ { ++ window->DockNode = NULL; ++ window->DockIsActive = false; ++ DockNodeAddWindow(dst_node, window, !move_tab_bar); ++ } ++ src_node->Windows.clear(); ++ ++ if (!move_tab_bar && src_node->TabBar) ++ { ++ if (dst_node->TabBar) ++ dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId; ++ DockNodeRemoveTabBar(src_node); ++ } ++} ++ ++static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node) ++{ ++ for (ImGuiWindow* window : node->Windows) ++ { ++ SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame ++ SetWindowSize(window, node->Size, ImGuiCond_Always); ++ } ++} ++ ++static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node) ++{ ++ if (node->HostWindow) ++ { ++ if (node->HostWindow->DockNodeAsHost == node) ++ node->HostWindow->DockNodeAsHost = NULL; ++ node->HostWindow = NULL; ++ } ++ ++ if (node->Windows.Size == 1) ++ { ++ node->VisibleWindow = node->Windows[0]; ++ node->Windows[0]->DockIsActive = false; ++ } ++ ++ if (node->TabBar) ++ DockNodeRemoveTabBar(node); ++} ++ ++// Search function called once by root node in DockNodeUpdate() ++struct ImGuiDockNodeTreeInfo ++{ ++ ImGuiDockNode* CentralNode; ++ ImGuiDockNode* FirstNodeWithWindows; ++ int CountNodesWithWindows; ++ //ImGuiWindowClass WindowClassForMerges; ++ ++ ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); } ++}; ++ ++static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info) ++{ ++ if (node->Windows.Size > 0) ++ { ++ if (info->FirstNodeWithWindows == NULL) ++ info->FirstNodeWithWindows = node; ++ info->CountNodesWithWindows++; ++ } ++ if (node->IsCentralNode()) ++ { ++ IM_ASSERT(info->CentralNode == NULL); // Should be only one ++ IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this."); ++ info->CentralNode = node; ++ } ++ if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL) ++ return; ++ if (node->ChildNodes[0]) ++ DockNodeFindInfo(node->ChildNodes[0], info); ++ if (node->ChildNodes[1]) ++ DockNodeFindInfo(node->ChildNodes[1], info); ++} ++ ++static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id) ++{ ++ IM_ASSERT(id != 0); ++ for (ImGuiWindow* window : node->Windows) ++ if (window->ID == id) ++ return window; ++ return NULL; ++} ++ ++// - Remove inactive windows/nodes. ++// - Update visibility flag. ++static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); ++ ++ // Inherit most flags ++ if (node->ParentNode) ++ node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; ++ ++ // Recurse into children ++ // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'. ++ // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node' ++ // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless) ++ node->HasCentralNodeChild = false; ++ if (node->ChildNodes[0]) ++ DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]); ++ if (node->ChildNodes[1]) ++ DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]); ++ ++ // Remove inactive windows, collapse nodes ++ // Merge node flags overrides stored in windows ++ node->LocalFlagsInWindows = ImGuiDockNodeFlags_None; ++ for (int window_n = 0; window_n < node->Windows.Size; window_n++) ++ { ++ ImGuiWindow* window = node->Windows[window_n]; ++ IM_ASSERT(window->DockNode == node); ++ ++ bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount); ++ bool remove = false; ++ remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount); ++ remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame ++ remove |= (window->DockTabWantClose); ++ if (remove) ++ { ++ window->DockTabWantClose = false; ++ if (node->Windows.Size == 1 && !node->IsCentralNode()) ++ { ++ DockNodeHideHostWindow(node); ++ node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; ++ DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return ++ return; ++ } ++ DockNodeRemoveWindow(node, window, node->ID); ++ window_n--; ++ continue; ++ } ++ ++ // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this. ++ //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear; ++ node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet; ++ } ++ node->UpdateMergedFlags(); ++ ++ // Auto-hide tab bar option ++ ImGuiDockNodeFlags node_flags = node->MergedFlags; ++ if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar()) ++ node->WantHiddenTabBarToggle = true; ++ node->WantHiddenTabBarUpdate = false; ++ ++ // Cancel toggling if we know our tab bar is enforced to be hidden at all times ++ if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar)) ++ node->WantHiddenTabBarToggle = false; ++ ++ // Apply toggles at a single point of the frame (here!) ++ if (node->Windows.Size > 1) ++ node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar); ++ else if (node->WantHiddenTabBarToggle) ++ node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar); ++ node->WantHiddenTabBarToggle = false; ++ ++ DockNodeUpdateVisibleFlag(node); ++} ++ ++// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames. ++static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node) ++{ ++ node->HasCentralNodeChild = false; ++ if (node->ChildNodes[0]) ++ DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]); ++ if (node->ChildNodes[1]) ++ DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]); ++ if (node->IsRootNode()) ++ { ++ ImGuiDockNode* mark_node = node->CentralNode; ++ while (mark_node) ++ { ++ mark_node->HasCentralNodeChild = true; ++ mark_node = mark_node->ParentNode; ++ } ++ } ++} ++ ++static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node) ++{ ++ // Update visibility flag ++ bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode(); ++ is_visible |= (node->Windows.Size > 0); ++ is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible); ++ is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible); ++ node->IsVisible = is_visible; ++} ++ ++static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(node->WantMouseMove == true); ++ StartMouseMovingWindow(window); ++ g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos; ++ g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision. ++ node->WantMouseMove = false; ++} ++ ++// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class. ++static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node) ++{ ++ DockNodeUpdateFlagsAndCollapse(node); ++ ++ // - Setup central node pointers ++ // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!) ++ // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing ++ ImGuiDockNodeTreeInfo info; ++ DockNodeFindInfo(node, &info); ++ node->CentralNode = info.CentralNode; ++ node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL; ++ node->CountNodeWithWindows = info.CountNodesWithWindows; ++ if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL) ++ node->LastFocusedNodeId = info.FirstNodeWithWindows->ID; ++ ++ // Copy the window class from of our first window so it can be used for proper dock filtering. ++ // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy. ++ // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec. ++ if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows) ++ { ++ node->WindowClass = first_node_with_windows->Windows[0]->WindowClass; ++ for (int n = 1; n < first_node_with_windows->Windows.Size; n++) ++ if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false) ++ { ++ node->WindowClass = first_node_with_windows->Windows[n]->WindowClass; ++ break; ++ } ++ } ++ ++ ImGuiDockNode* mark_node = node->CentralNode; ++ while (mark_node) ++ { ++ mark_node->HasCentralNodeChild = true; ++ mark_node = mark_node->ParentNode; ++ } ++} ++ ++static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window) ++{ ++ // Remove ourselves from any previous different host window ++ // This can happen if a user mistakenly does (see #4295 for details): ++ // - N+0: DockBuilderAddNode(id, 0) // missing ImGuiDockNodeFlags_DockSpace ++ // - N+1: NewFrame() // will create floating host window for that node ++ // - N+1: DockSpace(id) // requalify node as dockspace, moving host window ++ if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node) ++ node->HostWindow->DockNodeAsHost = NULL; ++ ++ host_window->DockNodeAsHost = node; ++ node->HostWindow = host_window; ++} ++ ++static void ImGui::DockNodeUpdate(ImGuiDockNode* node) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(node->LastFrameActive != g.FrameCount); ++ node->LastFrameAlive = g.FrameCount; ++ node->IsBgDrawnThisFrame = false; ++ ++ node->CentralNode = node->OnlyNodeWithWindows = NULL; ++ if (node->IsRootNode()) ++ DockNodeUpdateForRootNode(node); ++ ++ // Remove tab bar if not needed ++ if (node->TabBar && node->IsNoTabBar()) ++ DockNodeRemoveTabBar(node); ++ ++ // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) ++ bool want_to_hide_host_window = false; ++ if (node->IsFloatingNode()) ++ { ++ if (node->Windows.Size <= 1 && node->IsLeafNode()) ++ if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar)) ++ want_to_hide_host_window = true; ++ if (node->CountNodeWithWindows == 0) ++ want_to_hide_host_window = true; ++ } ++ if (want_to_hide_host_window) ++ { ++ if (node->Windows.Size == 1) ++ { ++ // Floating window pos/size is authoritative ++ ImGuiWindow* single_window = node->Windows[0]; ++ node->Pos = single_window->Pos; ++ node->Size = single_window->SizeFull; ++ node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; ++ ++ // Transfer focus immediately so when we revert to a regular window it is immediately selected ++ if (node->HostWindow && g.NavWindow == node->HostWindow) ++ FocusWindow(single_window); ++ if (node->HostWindow) ++ { ++ IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name); ++ single_window->Viewport = node->HostWindow->Viewport; ++ single_window->ViewportId = node->HostWindow->ViewportId; ++ if (node->HostWindow->ViewportOwned) ++ { ++ single_window->Viewport->ID = single_window->ID; ++ single_window->Viewport->Window = single_window; ++ single_window->ViewportOwned = true; ++ } ++ } ++ node->RefViewportId = single_window->ViewportId; ++ } ++ ++ DockNodeHideHostWindow(node); ++ node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; ++ node->WantCloseAll = false; ++ node->WantCloseTabId = 0; ++ node->HasCloseButton = node->HasWindowMenuButton = false; ++ node->LastFrameActive = g.FrameCount; ++ ++ if (node->WantMouseMove && node->Windows.Size == 1) ++ DockNodeStartMouseMovingWindow(node, node->Windows[0]); ++ return; ++ } ++ ++ // In some circumstance we will defer creating the host window (so everything will be kept hidden), ++ // while the expected visible window is resizing itself. ++ // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled, ++ // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up: ++ // N+0: Begin(): window created (with no known size), node is created ++ // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible ++ // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible ++ // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code. ++ // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin(). ++ // In reality it isn't very important as user quickly ends up with size data in .ini file. ++ if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode()) ++ { ++ IM_ASSERT(node->Windows.Size > 0); ++ ImGuiWindow* ref_window = NULL; ++ if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them! ++ ref_window = DockNodeFindWindowByID(node, node->SelectedTabId); ++ if (ref_window == NULL) ++ ref_window = node->Windows[0]; ++ if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0) ++ { ++ node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing; ++ return; ++ } ++ } ++ ++ const ImGuiDockNodeFlags node_flags = node->MergedFlags; ++ ++ // Decide if the node will have a close button and a window menu button ++ node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; ++ node->HasCloseButton = false; ++ for (ImGuiWindow* window : node->Windows) ++ { ++ // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call. ++ node->HasCloseButton |= window->HasCloseButton; ++ window->DockIsActive = (node->Windows.Size > 1); ++ } ++ if (node_flags & ImGuiDockNodeFlags_NoCloseButton) ++ node->HasCloseButton = false; ++ ++ // Bind or create host window ++ ImGuiWindow* host_window = NULL; ++ bool beginned_into_host_window = false; ++ if (node->IsDockSpace()) ++ { ++ // [Explicit root dockspace node] ++ IM_ASSERT(node->HostWindow); ++ host_window = node->HostWindow; ++ } ++ else ++ { ++ // [Automatic root or child nodes] ++ if (node->IsRootNode() && node->IsVisible) ++ { ++ ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL; ++ ++ // Sync Pos ++ if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window) ++ SetNextWindowPos(ref_window->Pos); ++ else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode) ++ SetNextWindowPos(node->Pos); ++ ++ // Sync Size ++ if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) ++ SetNextWindowSize(ref_window->SizeFull); ++ else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode) ++ SetNextWindowSize(node->Size); ++ ++ // Sync Collapsed ++ if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) ++ SetNextWindowCollapsed(ref_window->Collapsed); ++ ++ // Sync Viewport ++ if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window) ++ SetNextWindowViewport(ref_window->ViewportId); ++ else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0) ++ SetNextWindowViewport(node->RefViewportId); ++ ++ SetNextWindowClass(&node->WindowClass); ++ ++ // Begin into the host window ++ char window_label[20]; ++ DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label)); ++ ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost; ++ window_flags |= ImGuiWindowFlags_NoFocusOnAppearing; ++ window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse; ++ window_flags |= ImGuiWindowFlags_NoTitleBar; ++ ++ SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders ++ PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); ++ Begin(window_label, NULL, window_flags); ++ PopStyleVar(); ++ beginned_into_host_window = true; ++ ++ host_window = g.CurrentWindow; ++ DockNodeSetupHostWindow(node, host_window); ++ host_window->DC.CursorPos = host_window->Pos; ++ node->Pos = host_window->Pos; ++ node->Size = host_window->Size; ++ ++ // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow) ++ // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags. ++ // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again. ++ // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window ++ // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back ++ // after the dock host window, losing their top-most status. ++ if (node->HostWindow->Appearing) ++ BringWindowToDisplayFront(node->HostWindow); ++ ++ node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; ++ } ++ else if (node->ParentNode) ++ { ++ node->HostWindow = host_window = node->ParentNode->HostWindow; ++ node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; ++ } ++ if (node->WantMouseMove && node->HostWindow) ++ DockNodeStartMouseMovingWindow(node, node->HostWindow); ++ } ++ node->RefViewportId = 0; // Clear when we have a host window ++ ++ // Update focused node (the one whose title bar is highlight) within a node tree ++ if (node->IsSplitNode()) ++ IM_ASSERT(node->TabBar == NULL); ++ if (node->IsRootNode()) ++ if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL) ++ while (p_window != NULL && p_window->DockNode != NULL) ++ { ++ ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode); ++ if (p_node == node) ++ { ++ node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID! ++ break; ++ } ++ p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL; ++ } ++ ++ // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace ++ ImGuiDockNode* central_node = node->CentralNode; ++ const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty(); ++ bool central_node_hole_register_hit_test_hole = central_node_hole; ++ if (central_node_hole) ++ if (const ImGuiPayload* payload = ImGui::GetDragDropPayload()) ++ if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data)) ++ central_node_hole_register_hit_test_hole = false; ++ if (central_node_hole_register_hit_test_hole) ++ { ++ // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily. ++ // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen ++ // covering passthru node we'd have a gap on the edge not covered by the hole) ++ IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode ++ ImGuiDockNode* root_node = DockNodeGetRootNode(central_node); ++ ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size); ++ ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size); ++ if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; } ++ if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; } ++ if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; } ++ if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; } ++ //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255)); ++ if (central_node_hole && !hole_rect.IsInverted()) ++ { ++ SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min); ++ if (host_window->ParentWindow) ++ SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min); ++ } ++ } ++ ++ // Update position/size, process and draw resizing splitters ++ if (node->IsRootNode() && host_window) ++ { ++ DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size); ++ PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]); ++ PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]); ++ PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]); ++ DockNodeTreeUpdateSplitter(node); ++ PopStyleColor(3); ++ } ++ ++ // Draw empty node background (currently can only be the Central Node) ++ if (host_window && node->IsEmpty() && node->IsVisible) ++ { ++ host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG); ++ node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg); ++ if (node->LastBgColor != 0) ++ host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor); ++ node->IsBgDrawnThisFrame = true; ++ } ++ ++ // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set. ++ // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size ++ // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! ++ const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0; ++ if (render_dockspace_bg && node->IsVisible) ++ { ++ host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG); ++ if (central_node_hole) ++ RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f); ++ else ++ host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f); ++ } ++ ++ // Draw and populate Tab Bar ++ if (host_window) ++ host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); ++ if (host_window && node->Windows.Size > 0) ++ { ++ DockNodeUpdateTabBar(node, host_window); ++ } ++ else ++ { ++ node->WantCloseAll = false; ++ node->WantCloseTabId = 0; ++ node->IsFocused = false; ++ } ++ if (node->TabBar && node->TabBar->SelectedTabId) ++ node->SelectedTabId = node->TabBar->SelectedTabId; ++ else if (node->Windows.Size > 0) ++ node->SelectedTabId = node->Windows[0]->TabId; ++ ++ // Draw payload drop target ++ if (host_window && node->IsVisible) ++ if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window)) ++ BeginDockableDragDropTarget(host_window); ++ ++ // We update this after DockNodeUpdateTabBar() ++ node->LastFrameActive = g.FrameCount; ++ ++ // Recurse into children ++ // FIXME-DOCK FIXME-OPT: Should not need to recurse into children ++ if (host_window) ++ { ++ if (node->ChildNodes[0]) ++ DockNodeUpdate(node->ChildNodes[0]); ++ if (node->ChildNodes[1]) ++ DockNodeUpdate(node->ChildNodes[1]); ++ ++ // Render outer borders last (after the tab bar) ++ if (node->IsRootNode()) ++ RenderWindowOuterBorders(host_window); ++ } ++ ++ // End host window ++ if (beginned_into_host_window) //-V1020 ++ End(); ++} ++ ++// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame. ++static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs) ++{ ++ ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window; ++ ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window; ++ if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder)) ++ return d; ++ return (a->BeginOrderWithinContext - b->BeginOrderWithinContext); ++} ++ ++// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node. ++// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented) ++// Custom overrides may want to decorate, group, sort entries. ++// Please note those are internal structures: if you copy this expect occasional breakage. ++// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler) ++void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar) ++{ ++ IM_UNUSED(ctx); ++ if (tab_bar->Tabs.Size == 1) ++ { ++ // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table. ++ if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar())) ++ node->WantHiddenTabBarToggle = true; ++ } ++ else ++ { ++ // Display a selectable list of windows in this docking node ++ for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) ++ { ++ ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; ++ if (tab->Flags & ImGuiTabItemFlags_Button) ++ continue; ++ if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId)) ++ TabBarQueueFocus(tab_bar, tab); ++ SameLine(); ++ Text(" "); ++ } ++ } ++} ++ ++static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar) ++{ ++ // Try to position the menu so it is more likely to stays within the same viewport ++ ImGuiContext& g = *GImGui; ++ if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left) ++ SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f)); ++ else ++ SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f)); ++ if (BeginPopup("#WindowMenu")) ++ { ++ node->IsFocused = true; ++ g.DockNodeWindowMenuHandler(&g, node, tab_bar); ++ EndPopup(); ++ } ++} ++ ++// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button. ++bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node) ++{ ++ if (node->TabBar == NULL || node->HostWindow == NULL) ++ return false; ++ if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) ++ return false; ++ if (node->TabBar->ID == 0) ++ return false; ++ Begin(node->HostWindow->Name); ++ PushOverrideID(node->ID); ++ bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags); ++ IM_UNUSED(ret); ++ IM_ASSERT(ret); ++ return true; ++} ++ ++void ImGui::DockNodeEndAmendTabBar() ++{ ++ EndTabBar(); ++ PopID(); ++ End(); ++} ++ ++static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node) ++{ ++ // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy) ++ ImGuiContext& g = *GImGui; ++ if (g.NavWindowingTarget) ++ return (g.NavWindowingTarget->DockNode == node); ++ ++ // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window) ++ if (g.NavWindow && root_node->LastFocusedNodeId == node->ID) ++ { ++ // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node) ++ ImGuiWindow* parent_window = g.NavWindow->RootWindow; ++ while (parent_window->Flags & ImGuiWindowFlags_ChildMenu) ++ parent_window = parent_window->ParentWindow->RootWindow; ++ ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode; ++ for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL) ++ if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node) ++ return true; ++ } ++ return false; ++} ++ ++// Submit the tab bar corresponding to a dock node and various housekeeping details. ++static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiStyle& style = g.Style; ++ ++ const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount); ++ const bool closed_all = node->WantCloseAll && node_was_active; ++ const ImGuiID closed_one = node->WantCloseTabId && node_was_active; ++ node->WantCloseAll = false; ++ node->WantCloseTabId = 0; ++ ++ // Decide if we should use a focused title bar color ++ bool is_focused = false; ++ ImGuiDockNode* root_node = DockNodeGetRootNode(node); ++ if (IsDockNodeTitleBarHighlighted(node, root_node)) ++ is_focused = true; ++ ++ // Hidden tab bar will show a triangle on the upper-left (in Begin) ++ if (node->IsHiddenTabBar() || node->IsNoTabBar()) ++ { ++ node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL; ++ node->IsFocused = is_focused; ++ if (is_focused) ++ node->LastFrameFocused = g.FrameCount; ++ if (node->VisibleWindow) ++ { ++ // Notify root of visible window (used to display title in OS task bar) ++ if (is_focused || root_node->VisibleWindow == NULL) ++ root_node->VisibleWindow = node->VisibleWindow; ++ if (node->TabBar) ++ node->TabBar->VisibleTabId = node->VisibleWindow->TabId; ++ } ++ return; ++ } ++ ++ // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed ++ bool backup_skip_item = host_window->SkipItems; ++ if (!node->IsDockSpace()) ++ { ++ host_window->SkipItems = false; ++ host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; ++ } ++ ++ // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID. ++ // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs, ++ // as docked windows themselves will override the stack with their own root ID. ++ PushOverrideID(node->ID); ++ ImGuiTabBar* tab_bar = node->TabBar; ++ bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden ++ if (tab_bar == NULL) ++ { ++ DockNodeAddTabBar(node); ++ tab_bar = node->TabBar; ++ } ++ ++ ImGuiID focus_tab_id = 0; ++ node->IsFocused = is_focused; ++ ++ const ImGuiDockNodeFlags node_flags = node->MergedFlags; ++ const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None); ++ ++ // In a dock node, the Collapse Button turns into the Window Menu button. ++ // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes? ++ if (has_window_menu_button && IsPopupOpen("#WindowMenu")) ++ { ++ ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId; ++ DockNodeWindowMenuUpdate(node, tab_bar); ++ if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id) ++ focus_tab_id = tab_bar->NextSelectedTabId; ++ is_focused |= node->IsFocused; ++ } ++ ++ // Layout ++ ImRect title_bar_rect, tab_bar_rect; ++ ImVec2 window_menu_button_pos; ++ ImVec2 close_button_pos; ++ DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos); ++ ++ // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value. ++ const int tabs_count_old = tab_bar->Tabs.Size; ++ for (int window_n = 0; window_n < node->Windows.Size; window_n++) ++ { ++ ImGuiWindow* window = node->Windows[window_n]; ++ if (TabBarFindTabByID(tab_bar, window->TabId) == NULL) ++ TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window); ++ } ++ ++ // Title bar ++ if (is_focused) ++ node->LastFrameFocused = g.FrameCount; ++ ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); ++ ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize); ++ host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags); ++ ++ // Docking/Collapse button ++ if (has_window_menu_button) ++ { ++ if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node) ++ OpenPopup("#WindowMenu"); ++ if (IsItemActive()) ++ focus_tab_id = tab_bar->SelectedTabId; ++ if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f) ++ SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode)); ++ } ++ ++ // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value ++ int tabs_unsorted_start = tab_bar->Tabs.Size; ++ for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--) ++ { ++ // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? ++ tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted; ++ tabs_unsorted_start = tab_n; ++ } ++ if (tab_bar->Tabs.Size > tabs_unsorted_start) ++ { ++ IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : ""); ++ for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++) ++ { ++ ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; ++ IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1); ++ } ++ IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1); ++ if (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ++ ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder); ++ } ++ ++ // Apply NavWindow focus back to the tab bar ++ if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node) ++ tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId; ++ ++ // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated ++ if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL) ++ tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId; ++ else if (tab_bar->Tabs.Size > tabs_count_old) ++ tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId; ++ ++ // Begin tab bar ++ ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons); ++ tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll; ++ tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline; ++ if (!host_window->Collapsed && is_focused) ++ tab_bar_flags |= ImGuiTabBarFlags_IsFocused; ++ tab_bar->ID = GetID("#TabBar"); ++ tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width ++ tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize; ++ BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags); ++ //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255)); ++ ++ // Backup style colors ++ ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT]; ++ for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) ++ backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]]; ++ ++ // Submit actual tabs ++ node->VisibleWindow = NULL; ++ for (int window_n = 0; window_n < node->Windows.Size; window_n++) ++ { ++ ImGuiWindow* window = node->Windows[window_n]; ++ if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument)) ++ continue; ++ if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active) ++ { ++ ImGuiTabItemFlags tab_item_flags = 0; ++ tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet; ++ if (window->Flags & ImGuiWindowFlags_UnsavedDocument) ++ tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument; ++ if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) ++ tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; ++ ++ // Apply stored style overrides for the window ++ for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) ++ g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]); ++ ++ // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so) ++ bool tab_open = true; ++ TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window); ++ if (!tab_open) ++ node->WantCloseTabId = window->TabId; ++ if (tab_bar->VisibleTabId == window->TabId) ++ node->VisibleWindow = window; ++ ++ // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call ++ window->DockTabItemStatusFlags = g.LastItemData.StatusFlags; ++ window->DockTabItemRect = g.LastItemData.Rect; ++ ++ // Update navigation ID on menu layer ++ if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0) ++ host_window->NavLastIds[1] = window->TabId; ++ } ++ } ++ ++ // Restore style colors ++ for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) ++ g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n]; ++ ++ // Notify root of visible window (used to display title in OS task bar) ++ if (node->VisibleWindow) ++ if (is_focused || root_node->VisibleWindow == NULL) ++ root_node->VisibleWindow = node->VisibleWindow; ++ ++ // Close button (after VisibleWindow was updated) ++ // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId ++ const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton; ++ const bool close_button_is_visible = node->HasCloseButton; ++ //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one) ++ if (close_button_is_visible) ++ { ++ if (!close_button_is_enabled) ++ { ++ PushItemFlag(ImGuiItemFlags_Disabled, true); ++ PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f)); ++ } ++ if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos)) ++ { ++ node->WantCloseAll = true; ++ for (int n = 0; n < tab_bar->Tabs.Size; n++) ++ TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]); ++ } ++ //if (IsItemActive()) ++ // focus_tab_id = tab_bar->SelectedTabId; ++ if (!close_button_is_enabled) ++ { ++ PopStyleColor(); ++ PopItemFlag(); ++ } ++ } ++ ++ // When clicking on the title bar outside of tabs, we still focus the selected tab for that node ++ // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them. ++ ImGuiID title_bar_id = host_window->GetID("#TITLEBAR"); ++ if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id) ++ { ++ // AllowOverlap mode required for appending into dock node tab bar, ++ // otherwise dragging window will steal HoveredId and amended tabs cannot get them. ++ bool held; ++ KeepAliveID(title_bar_id); ++ ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap); ++ if (g.HoveredId == title_bar_id) ++ { ++ g.LastItemData.ID = title_bar_id; ++ } ++ if (held) ++ { ++ if (IsMouseClicked(0)) ++ focus_tab_id = tab_bar->SelectedTabId; ++ ++ // Forward moving request to selected window ++ if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) ++ StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space ++ } ++ } ++ ++ // Forward focus from host node to selected window ++ //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget) ++ // focus_tab_id = tab_bar->SelectedTabId; ++ ++ // When clicked on a tab we requested focus to the docked child ++ // This overrides the value set by "forward focus from host node to selected window". ++ if (tab_bar->NextSelectedTabId) ++ focus_tab_id = tab_bar->NextSelectedTabId; ++ ++ // Apply navigation focus ++ if (focus_tab_id != 0) ++ if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id)) ++ if (tab->Window) ++ { ++ FocusWindow(tab->Window); ++ NavInitWindow(tab->Window, false); ++ } ++ ++ EndTabBar(); ++ PopID(); ++ ++ // Restore SkipItems flag ++ if (!node->IsDockSpace()) ++ { ++ host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main; ++ host_window->SkipItems = backup_skip_item; ++ } ++} ++ ++static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node) ++{ ++ IM_ASSERT(node->TabBar == NULL); ++ node->TabBar = IM_NEW(ImGuiTabBar); ++} ++ ++static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node) ++{ ++ if (node->TabBar == NULL) ++ return; ++ IM_DELETE(node->TabBar); ++ node->TabBar = NULL; ++} ++ ++static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window) ++{ ++ if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext) ++ return false; ++ ++ ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass; ++ ImGuiWindowClass* payload_class = &payload->WindowClass; ++ if (host_class->ClassId != payload_class->ClassId) ++ { ++ bool pass = false; ++ if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0) ++ pass = true; ++ if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0) ++ pass = true; ++ if (!pass) ++ return false; ++ } ++ ++ // Prevent docking any window created above a popup ++ // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features), ++ // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test. ++ // But it would requires more work on our end because the dock host windows is technically created in NewFrame() ++ // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking. ++ ImGuiContext& g = *GImGui; ++ for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--) ++ if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window) ++ if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window)) // Payload is created from within a popup begin stack. ++ return false; ++ ++ return true; ++} ++ ++static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload) ++{ ++ if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering ++ return true; ++ ++ const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1; ++ for (int payload_n = 0; payload_n < payload_count; payload_n++) ++ { ++ ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload; ++ if (DockNodeIsDropAllowedOne(payload, host_window)) ++ return true; ++ } ++ return false; ++} ++ ++// window menu button == collapse button when not in a dock node. ++// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code. ++static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiStyle& style = g.Style; ++ ++ ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f); ++ if (out_title_rect) { *out_title_rect = r; } ++ ++ r.Min.x += style.WindowBorderSize; ++ r.Max.x -= style.WindowBorderSize; ++ ++ float button_sz = g.FontSize; ++ r.Min.x += style.FramePadding.x; ++ r.Max.x -= style.FramePadding.x; ++ ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y); ++ if (node->HasCloseButton) ++ { ++ if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y); ++ r.Max.x -= button_sz + style.ItemInnerSpacing.x; ++ } ++ if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left) ++ { ++ r.Min.x += button_sz + style.ItemInnerSpacing.x; ++ } ++ else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right) ++ { ++ window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y); ++ r.Max.x -= button_sz + style.ItemInnerSpacing.x; ++ } ++ if (out_tab_bar_rect) { *out_tab_bar_rect = r; } ++ if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; } ++} ++ ++void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired) ++{ ++ ImGuiContext& g = *GImGui; ++ const float dock_spacing = g.Style.ItemInnerSpacing.x; ++ const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; ++ pos_new[axis ^ 1] = pos_old[axis ^ 1]; ++ size_new[axis ^ 1] = size_old[axis ^ 1]; ++ ++ // Distribute size on given axis (with a desired size or equally) ++ const float w_avail = size_old[axis] - dock_spacing; ++ if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f) ++ { ++ size_new[axis] = size_new_desired[axis]; ++ size_old[axis] = IM_TRUNC(w_avail - size_new[axis]); ++ } ++ else ++ { ++ size_new[axis] = IM_TRUNC(w_avail * 0.5f); ++ size_old[axis] = IM_TRUNC(w_avail - size_new[axis]); ++ } ++ ++ // Position each node ++ if (dir == ImGuiDir_Right || dir == ImGuiDir_Down) ++ { ++ pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing; ++ } ++ else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up) ++ { ++ pos_new[axis] = pos_old[axis]; ++ pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing; ++ } ++} ++ ++// Retrieve the drop rectangles for a given direction or for the center + perform hit testing. ++bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos) ++{ ++ ImGuiContext& g = *GImGui; ++ ++ const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight()); ++ const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f)); ++ float hs_w; // Half-size, longer axis ++ float hs_h; // Half-size, smaller axis ++ ImVec2 off; // Distance from edge or center ++ if (outer_docking) ++ { ++ //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f)); ++ //hs_h = ImTrunc(hs_w * 0.15f); ++ //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h)); ++ hs_w = ImTrunc(hs_for_central_nodes * 1.50f); ++ hs_h = ImTrunc(hs_for_central_nodes * 0.80f); ++ off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h)); ++ } ++ else ++ { ++ hs_w = ImTrunc(hs_for_central_nodes); ++ hs_h = ImTrunc(hs_for_central_nodes * 0.90f); ++ off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f)); ++ } ++ ++ ImVec2 c = ImTrunc(parent.GetCenter()); ++ if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); } ++ else if (dir == ImGuiDir_Up) { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); } ++ else if (dir == ImGuiDir_Down) { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); } ++ else if (dir == ImGuiDir_Left) { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); } ++ else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); } ++ ++ if (test_mouse_pos == NULL) ++ return false; ++ ++ ImRect hit_r = out_r; ++ if (!outer_docking) ++ { ++ // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides ++ hit_r.Expand(ImTrunc(hs_w * 0.30f)); ++ ImVec2 mouse_delta = (*test_mouse_pos - c); ++ float mouse_delta_len2 = ImLengthSqr(mouse_delta); ++ float r_threshold_center = hs_w * 1.4f; ++ float r_threshold_sides = hs_w * (1.4f + 1.2f); ++ if (mouse_delta_len2 < r_threshold_center * r_threshold_center) ++ return (dir == ImGuiDir_None); ++ if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides) ++ return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y)); ++ } ++ return hit_r.Contains(*test_mouse_pos); ++} ++ ++// host_node may be NULL if the window doesn't have a DockNode already. ++// FIXME-DOCK: This is misnamed since it's also doing the filtering. ++static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking) ++{ ++ ImGuiContext& g = *GImGui; ++ ++ // There is an edge case when docking into a dockspace which only has inactive nodes. ++ // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive. ++ // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference. ++ if (payload_node == NULL) ++ payload_node = payload_window->DockNodeAsHost; ++ ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node; ++ if (ref_node_for_rect) ++ IM_ASSERT(ref_node_for_rect->IsVisible == true); ++ ++ // Filter, figure out where we are allowed to dock ++ ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet; ++ ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet; ++ data->IsCenterAvailable = true; ++ if (is_outer_docking) ++ data->IsCenterAvailable = false; ++ else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe) ++ data->IsCenterAvailable = false; ++ else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode()) ++ data->IsCenterAvailable = false; ++ else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split? ++ data->IsCenterAvailable = false; ++ else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty())) ++ data->IsCenterAvailable = false; ++ else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty()) ++ data->IsCenterAvailable = false; ++ ++ data->IsSidesAvailable = true; ++ if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit) ++ data->IsSidesAvailable = false; ++ else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode()) ++ data->IsSidesAvailable = false; ++ else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther) ++ data->IsSidesAvailable = false; ++ ++ // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split) ++ data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton); ++ data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0); ++ data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos; ++ data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size; ++ ++ // Calculate drop shapes geometry for allowed splitting directions ++ IM_ASSERT(ImGuiDir_None == -1); ++ data->SplitNode = host_node; ++ data->SplitDir = ImGuiDir_None; ++ data->IsSplitDirExplicit = false; ++ if (!host_window->Collapsed) ++ for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++) ++ { ++ if (dir == ImGuiDir_None && !data->IsCenterAvailable) ++ continue; ++ if (dir != ImGuiDir_None && !data->IsSidesAvailable) ++ continue; ++ if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos)) ++ { ++ data->SplitDir = (ImGuiDir)dir; ++ data->IsSplitDirExplicit = true; ++ } ++ } ++ ++ // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar ++ data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable); ++ if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift) ++ data->IsDropAllowed = false; ++ ++ // Calculate split area ++ data->SplitRatio = 0.0f; ++ if (data->SplitDir != ImGuiDir_None) ++ { ++ ImGuiDir split_dir = data->SplitDir; ++ ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; ++ ImVec2 pos_new, pos_old = data->FutureNode.Pos; ++ ImVec2 size_new, size_old = data->FutureNode.Size; ++ DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size); ++ ++ // Calculate split ratio so we can pass it down the docking request ++ float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]); ++ data->FutureNode.Pos = pos_new; ++ data->FutureNode.Size = size_new; ++ data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio); ++ } ++} ++ ++static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes ++ ++ // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent. ++ // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes. ++ const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload; ++ ++ // In case the two windows involved are on different viewports, we will draw the overlay on each of them. ++ int overlay_draw_lists_count = 0; ++ ImDrawList* overlay_draw_lists[2]; ++ overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport); ++ if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload) ++ overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport); ++ ++ // Draw main preview rectangle ++ const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f); ++ const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f); ++ const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f); ++ const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f); ++ ++ // Display area preview ++ const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0); ++ if (data->IsDropAllowed) ++ { ++ ImRect overlay_rect = data->FutureNode.Rect(); ++ if (data->SplitDir == ImGuiDir_None && can_preview_tabs) ++ overlay_rect.Min.y += GetFrameHeight(); ++ if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable) ++ for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) ++ overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize)); ++ } ++ ++ // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read) ++ if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable) ++ { ++ // Compute target tab bar geometry so we can locate our preview tabs ++ ImRect tab_bar_rect; ++ DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL); ++ ImVec2 tab_pos = tab_bar_rect.Min; ++ if (host_node && host_node->TabBar) ++ { ++ if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar()) ++ tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission. ++ else ++ tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x; ++ } ++ else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost)) ++ { ++ tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar ++ } ++ ++ // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows) ++ if (root_payload->DockNodeAsHost) ++ IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size); ++ ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL; ++ const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1; ++ for (int payload_n = 0; payload_n < payload_count; payload_n++) ++ { ++ // DockNode's TabBar may have non-window Tabs manually appended by user ++ ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload; ++ if (tab_bar_with_payload && payload_window == NULL) ++ continue; ++ if (!DockNodeIsDropAllowedOne(payload_window, host_window)) ++ continue; ++ ++ // Calculate the tab bounding box for each payload window ++ ImVec2 tab_size = TabItemCalcSize(payload_window); ++ ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y); ++ tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x; ++ const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]); ++ const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]); ++ PushStyleColor(ImGuiCol_Text, overlay_col_text); ++ for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) ++ { ++ ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0; ++ if (!tab_bar_rect.Contains(tab_bb)) ++ overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max); ++ TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs); ++ TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL); ++ if (!tab_bar_rect.Contains(tab_bb)) ++ overlay_draw_lists[overlay_n]->PopClipRect(); ++ } ++ PopStyleColor(); ++ } ++ } ++ ++ // Display drop boxes ++ const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding); ++ for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++) ++ { ++ if (!data->DropRectsDraw[dir + 1].IsInverted()) ++ { ++ ImRect draw_r = data->DropRectsDraw[dir + 1]; ++ ImRect draw_r_in = draw_r; ++ draw_r_in.Expand(-2.0f); ++ ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop; ++ for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) ++ { ++ ImVec2 center = ImFloor(draw_r_in.GetCenter()); ++ overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding); ++ overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding); ++ if (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ++ overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines); ++ if (dir == ImGuiDir_Up || dir == ImGuiDir_Down) ++ overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines); ++ } ++ } ++ ++ // Stop after ImGuiDir_None ++ if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit) ++ return; ++ } ++} ++ ++//----------------------------------------------------------------------------- ++// Docking: ImGuiDockNode Tree manipulation functions ++//----------------------------------------------------------------------------- ++// - DockNodeTreeSplit() ++// - DockNodeTreeMerge() ++// - DockNodeTreeUpdatePosSize() ++// - DockNodeTreeUpdateSplitterFindTouchingNode() ++// - DockNodeTreeUpdateSplitter() ++// - DockNodeTreeFindFallbackLeafNode() ++// - DockNodeTreeFindNodeByPos() ++//----------------------------------------------------------------------------- ++ ++void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(split_axis != ImGuiAxis_None); ++ ++ ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0); ++ child_0->ParentNode = parent_node; ++ ++ ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0); ++ child_1->ParentNode = parent_node; ++ ++ ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1; ++ DockNodeMoveChildNodes(child_inheritor, parent_node); ++ parent_node->ChildNodes[0] = child_0; ++ parent_node->ChildNodes[1] = child_1; ++ parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow; ++ parent_node->SplitAxis = split_axis; ++ parent_node->VisibleWindow = NULL; ++ parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode; ++ ++ float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize); ++ size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f); ++ IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. ++ child_0->SizeRef = child_1->SizeRef = parent_node->Size; ++ child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio); ++ child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]); ++ ++ DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node); ++ DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID); ++ DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node)); ++ DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size); ++ ++ // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property) ++ child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; ++ child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; ++ child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_; ++ parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; ++ child_0->UpdateMergedFlags(); ++ child_1->UpdateMergedFlags(); ++ parent_node->UpdateMergedFlags(); ++ if (child_inheritor->IsCentralNode()) ++ DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor; ++} ++ ++void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child) ++{ ++ // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL. ++ ImGuiContext& g = *GImGui; ++ ImGuiDockNode* child_0 = parent_node->ChildNodes[0]; ++ ImGuiDockNode* child_1 = parent_node->ChildNodes[1]; ++ IM_ASSERT(child_0 || child_1); ++ IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1); ++ if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0)) ++ { ++ IM_ASSERT(parent_node->TabBar == NULL); ++ IM_ASSERT(parent_node->Windows.Size == 0); ++ } ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID); ++ ++ ImVec2 backup_last_explicit_size = parent_node->SizeRef; ++ DockNodeMoveChildNodes(parent_node, merge_lead_child); ++ if (child_0) ++ { ++ DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows ++ DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID); ++ } ++ if (child_1) ++ { ++ DockNodeMoveWindows(parent_node, child_1); ++ DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID); ++ } ++ DockNodeApplyPosSizeToWindows(parent_node); ++ parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto; ++ parent_node->VisibleWindow = merge_lead_child->VisibleWindow; ++ parent_node->SizeRef = backup_last_explicit_size; ++ ++ // Flags transfer ++ parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag ++ parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; ++ parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; ++ parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows ++ parent_node->UpdateMergedFlags(); ++ ++ if (child_0) ++ { ++ ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL); ++ IM_DELETE(child_0); ++ } ++ if (child_1) ++ { ++ ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL); ++ IM_DELETE(child_1); ++ } ++} ++ ++// Update Pos/Size for a node hierarchy (don't affect child Windows yet) ++// (Depth-first, Pre-Order) ++void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node) ++{ ++ // During the regular dock node update we write to all nodes. ++ // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away. ++ ImGuiContext& g = *GImGui; ++ const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node; ++ if (write_to_node) ++ { ++ node->Pos = pos; ++ node->Size = size; ++ } ++ ++ if (node->IsLeafNode()) ++ return; ++ ++ ImGuiDockNode* child_0 = node->ChildNodes[0]; ++ ImGuiDockNode* child_1 = node->ChildNodes[1]; ++ ImVec2 child_0_pos = pos, child_1_pos = pos; ++ ImVec2 child_0_size = size, child_1_size = size; ++ ++ const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0)); ++ const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1)); ++ const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node; ++ const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node; ++ ++ if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible) ++ { ++ const float spacing = g.Style.DockingSeparatorSize; ++ const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; ++ const float size_avail = ImMax(size[axis] - spacing, 0.0f); ++ ++ // Size allocation policy ++ // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows. ++ const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f); ++ ++ // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing. ++ // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc() ++ // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce ++ ++ // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge) ++ if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce) ++ { ++ child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]); ++ child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); ++ IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); ++ } ++ else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce) ++ { ++ child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]); ++ child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]); ++ IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); ++ } ++ else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce) ++ { ++ // FIXME-DOCK: We cannot honor the requested size, so apply ratio. ++ // Currently this path will only be taken if code programmatically sets WantLockSizeOnce ++ float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]); ++ child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio); ++ child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); ++ IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); ++ } ++ ++ // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node ++ else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild) ++ { ++ child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]); ++ child_1_size[axis] = (size_avail - child_0_size[axis]); ++ } ++ else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild) ++ { ++ child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]); ++ child_0_size[axis] = (size_avail - child_1_size[axis]); ++ } ++ else ++ { ++ // 4) Otherwise distribute according to the relative ratio of each SizeRef value ++ float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]); ++ child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f)); ++ child_1_size[axis] = (size_avail - child_0_size[axis]); ++ } ++ ++ child_1_pos[axis] += spacing + child_0_size[axis]; ++ } ++ ++ if (only_write_to_single_node == NULL) ++ child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false; ++ ++ const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible; ++ const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible; ++ if (child_0_recurse) ++ DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size); ++ if (child_1_recurse) ++ DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size); ++} ++ ++static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector* touching_nodes) ++{ ++ if (node->IsLeafNode()) ++ { ++ touching_nodes->push_back(node); ++ return; ++ } ++ if (node->ChildNodes[0]->IsVisible) ++ if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible) ++ DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes); ++ if (node->ChildNodes[1]->IsVisible) ++ if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible) ++ DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes); ++} ++ ++// (Depth-First, Pre-Order) ++void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) ++{ ++ if (node->IsLeafNode()) ++ return; ++ ++ ImGuiContext& g = *GImGui; ++ ++ ImGuiDockNode* child_0 = node->ChildNodes[0]; ++ ImGuiDockNode* child_1 = node->ChildNodes[1]; ++ if (child_0->IsVisible && child_1->IsVisible) ++ { ++ // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) ++ const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; ++ IM_ASSERT(axis != ImGuiAxis_None); ++ ImRect bb; ++ bb.Min = child_0->Pos; ++ bb.Max = child_1->Pos; ++ bb.Min[axis] += child_0->Size[axis]; ++ bb.Max[axis ^ 1] += child_1->Size[axis ^ 1]; ++ //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255)); ++ ++ const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs ++ const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY; ++ if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag)) ++ { ++ ImGuiWindow* window = g.CurrentWindow; ++ window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding); ++ } ++ else ++ { ++ //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node. ++ //bb.Max[axis] -= 1; ++ PushID(node->ID); ++ ++ // Find resizing limits by gathering list of nodes that are touching the splitter line. ++ ImVector touching_nodes[2]; ++ float min_size = g.Style.WindowMinSize[axis]; ++ float resize_limits[2]; ++ resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size; ++ resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size; ++ ++ ImGuiID splitter_id = GetID("##Splitter"); ++ if (g.ActiveId == splitter_id) // Only process when splitter is active ++ { ++ DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]); ++ DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]); ++ for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++) ++ resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size); ++ for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++) ++ resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size); ++ ++ // [DEBUG] Render touching nodes & limits ++ /* ++ ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport()); ++ for (int n = 0; n < 2; n++) ++ { ++ for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++) ++ draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255)); ++ if (axis == ImGuiAxis_X) ++ draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f); ++ else ++ draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f); ++ } ++ */ ++ } ++ ++ // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters ++ float cur_size_0 = child_0->Size[axis]; ++ float cur_size_1 = child_1->Size[axis]; ++ float min_size_0 = resize_limits[0] - child_0->Pos[axis]; ++ float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1]; ++ ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg); ++ if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col)) ++ { ++ if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0) ++ { ++ child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0; ++ child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis]; ++ child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1; ++ ++ // Lock the size of every node that is a sibling of the node we are touching ++ // This might be less desirable if we can merge sibling of a same axis into the same parental level. ++ for (int side_n = 0; side_n < 2; side_n++) ++ for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++) ++ { ++ ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n]; ++ //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport()); ++ //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255)); ++ while (touching_node->ParentNode != node) ++ { ++ if (touching_node->ParentNode->SplitAxis == axis) ++ { ++ // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize(). ++ ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n]; ++ node_to_preserve->WantLockSizeOnce = true; ++ //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255)); ++ //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100)); ++ } ++ touching_node = touching_node->ParentNode; ++ } ++ } ++ ++ DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size); ++ DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size); ++ MarkIniSettingsDirty(); ++ } ++ } ++ PopID(); ++ } ++ } ++ ++ if (child_0->IsVisible) ++ DockNodeTreeUpdateSplitter(child_0); ++ if (child_1->IsVisible) ++ DockNodeTreeUpdateSplitter(child_1); ++} ++ ++ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node) ++{ ++ if (node->IsLeafNode()) ++ return node; ++ if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0])) ++ return leaf_node; ++ if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1])) ++ return leaf_node; ++ return NULL; ++} ++ ++ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos) ++{ ++ if (!node->IsVisible) ++ return NULL; ++ ++ const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? ++ ImRect r(node->Pos, node->Pos + node->Size); ++ r.Expand(dock_spacing * 0.5f); ++ bool inside = r.Contains(pos); ++ if (!inside) ++ return NULL; ++ ++ if (node->IsLeafNode()) ++ return node; ++ if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos)) ++ return hovered_node; ++ if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos)) ++ return hovered_node; ++ ++ // This means we are hovering over the splitter/spacing of a parent node ++ return node; ++} ++ ++//----------------------------------------------------------------------------- ++// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) ++//----------------------------------------------------------------------------- ++// - SetWindowDock() [Internal] ++// - DockSpace() ++// - DockSpaceOverViewport() ++//----------------------------------------------------------------------------- ++ ++// [Internal] Called via SetNextWindowDockID() ++void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond) ++{ ++ // Test condition (NB: bit 0 is always true) and clear flags for next time ++ if (cond && (window->SetWindowDockAllowFlags & cond) == 0) ++ return; ++ window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); ++ ++ if (window->DockId == dock_id) ++ return; ++ ++ // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot ++ ImGuiContext& g = *GImGui; ++ if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id)) ++ if (new_node->IsSplitNode()) ++ { ++ // Policy: Find central node or latest focused node. We first move back to our root node. ++ new_node = DockNodeGetRootNode(new_node); ++ if (new_node->CentralNode) ++ { ++ IM_ASSERT(new_node->CentralNode->IsCentralNode()); ++ dock_id = new_node->CentralNode->ID; ++ } ++ else ++ { ++ dock_id = new_node->LastFocusedNodeId; ++ } ++ } ++ ++ if (window->DockId == dock_id) ++ return; ++ ++ if (window->DockNode) ++ DockNodeRemoveWindow(window->DockNode, window, 0); ++ window->DockId = dock_id; ++} ++ ++// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default. ++// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors. ++// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app. ++// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location). ++ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiWindow* window = GetCurrentWindowRead(); ++ if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) ++ return 0; ++ ++ // Early out if parent window is hidden/collapsed ++ // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960. ++ // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true. ++ if (window->SkipItems) ++ flags |= ImGuiDockNodeFlags_KeepAliveOnly; ++ if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0) ++ window = GetCurrentWindow(); // call to set window->WriteAccessed = true; ++ ++ IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); ++ IM_ASSERT(dockspace_id != 0); ++ ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id); ++ if (node == NULL) ++ { ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id); ++ node = DockContextAddNode(&g, dockspace_id); ++ node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode); ++ } ++ if (window_class && window_class->ClassId != node->WindowClass.ClassId) ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", dockspace_id, node->WindowClass.ClassId, window_class->ClassId); ++ node->SharedFlags = flags; ++ node->WindowClass = window_class ? *window_class : ImGuiWindowClass(); ++ ++ // When a DockSpace transitioned form implicit to explicit this may be called a second time ++ // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again. ++ if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly)) ++ { ++ IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID"); ++ node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace); ++ return dockspace_id; ++ } ++ node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace); ++ ++ // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible ++ if (flags & ImGuiDockNodeFlags_KeepAliveOnly) ++ { ++ node->LastFrameAlive = g.FrameCount; ++ return dockspace_id; ++ } ++ ++ const ImVec2 content_avail = GetContentRegionAvail(); ++ ImVec2 size = ImTrunc(size_arg); ++ if (size.x <= 0.0f) ++ size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues) ++ if (size.y <= 0.0f) ++ size.y = ImMax(content_avail.y + size.y, 4.0f); ++ IM_ASSERT(size.x > 0.0f && size.y > 0.0f); ++ ++ node->Pos = window->DC.CursorPos; ++ node->Size = node->SizeRef = size; ++ SetNextWindowPos(node->Pos); ++ SetNextWindowSize(node->Size); ++ g.NextWindowData.PosUndock = false; ++ ++ // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window? ++ // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented) ++ ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost; ++ window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar; ++ window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; ++ window_flags |= ImGuiWindowFlags_NoBackground; ++ ++ char title[256]; ++ ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, dockspace_id); ++ ++ PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f); ++ Begin(title, NULL, window_flags); ++ PopStyleVar(); ++ ++ ImGuiWindow* host_window = g.CurrentWindow; ++ DockNodeSetupHostWindow(node, host_window); ++ host_window->ChildId = window->GetID(title); ++ node->OnlyNodeWithWindows = NULL; ++ ++ IM_ASSERT(node->IsRootNode()); ++ ++ // We need to handle the rare case were a central node is missing. ++ // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace. ++ // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split. ++ // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining. ++ // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property, ++ // as it doesn't make sense for an empty dockspace to not have this property. ++ if (node->IsLeafNode() && !node->IsCentralNode()) ++ node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode); ++ ++ // Update the node ++ DockNodeUpdate(node); ++ ++ End(); ++ ++ ImRect bb(node->Pos, node->Pos + size); ++ ItemSize(size); ++ ItemAdd(bb, dockspace_id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?) ++ if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild() ++ g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; ++ ++ return dockspace_id; ++} ++ ++// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode! ++// The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar(). ++// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function. ++// If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it. ++ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class) ++{ ++ if (viewport == NULL) ++ viewport = GetMainViewport(); ++ ++ // Submit a window filling the entire viewport ++ SetNextWindowPos(viewport->WorkPos); ++ SetNextWindowSize(viewport->WorkSize); ++ SetNextWindowViewport(viewport->ID); ++ ++ ImGuiWindowFlags host_window_flags = 0; ++ host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking; ++ host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; ++ if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) ++ host_window_flags |= ImGuiWindowFlags_NoBackground; ++ ++ char label[32]; ++ ImFormatString(label, IM_ARRAYSIZE(label), "WindowOverViewport_%08X", viewport->ID); ++ ++ PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ++ PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ++ PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ++ Begin(label, NULL, host_window_flags); ++ PopStyleVar(3); ++ ++ // Submit the dockspace ++ if (dockspace_id == 0) ++ dockspace_id = GetID("DockSpace"); ++ DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class); ++ ++ End(); ++ ++ return dockspace_id; ++} ++ ++//----------------------------------------------------------------------------- ++// Docking: Builder Functions ++//----------------------------------------------------------------------------- ++// Very early end-user API to manipulate dock nodes. ++// Only available in imgui_internal.h. Expect this API to change/break! ++// It is expected that those functions are all called _before_ the dockspace node submission. ++//----------------------------------------------------------------------------- ++// - DockBuilderDockWindow() ++// - DockBuilderGetNode() ++// - DockBuilderSetNodePos() ++// - DockBuilderSetNodeSize() ++// - DockBuilderAddNode() ++// - DockBuilderRemoveNode() ++// - DockBuilderRemoveNodeChildNodes() ++// - DockBuilderRemoveNodeDockedWindows() ++// - DockBuilderSplitNode() ++// - DockBuilderCopyNodeRec() ++// - DockBuilderCopyNode() ++// - DockBuilderCopyWindowSettings() ++// - DockBuilderCopyDockSpace() ++// - DockBuilderFinish() ++//----------------------------------------------------------------------------- ++ ++void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id) ++{ ++ // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1) ++ ImGuiContext& g = *GImGui; IM_UNUSED(g); ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id); ++ ImGuiID window_id = ImHashStr(window_name); ++ if (ImGuiWindow* window = FindWindowByID(window_id)) ++ { ++ // Apply to created window ++ ImGuiID prev_node_id = window->DockId; ++ SetWindowDock(window, node_id, ImGuiCond_Always); ++ if (window->DockId != prev_node_id) ++ window->DockOrder = -1; ++ } ++ else ++ { ++ // Apply to settings ++ ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id); ++ if (settings == NULL) ++ settings = CreateNewWindowSettings(window_name); ++ if (settings->DockId != node_id) ++ settings->DockOrder = -1; ++ settings->DockId = node_id; ++ } ++} ++ ++ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id) ++{ ++ ImGuiContext& g = *GImGui; ++ return DockContextFindNodeByID(&g, node_id); ++} ++ ++void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id); ++ if (node == NULL) ++ return; ++ node->Pos = pos; ++ node->AuthorityForPos = ImGuiDataAuthority_DockNode; ++} ++ ++void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id); ++ if (node == NULL) ++ return; ++ IM_ASSERT(size.x > 0.0f && size.y > 0.0f); ++ node->Size = node->SizeRef = size; ++ node->AuthorityForSize = ImGuiDataAuthority_DockNode; ++} ++ ++// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node! ++// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node. ++// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary. ++// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand! ++// For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect. ++// - Use (id == 0) to let the system allocate a node identifier. ++// - Existing node with a same id will be removed. ++ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags) ++{ ++ ImGuiContext& g = *GImGui; IM_UNUSED(g); ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags); ++ ++ if (node_id != 0) ++ DockBuilderRemoveNode(node_id); ++ ++ ImGuiDockNode* node = NULL; ++ if (flags & ImGuiDockNodeFlags_DockSpace) ++ { ++ DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly); ++ node = DockContextFindNodeByID(&g, node_id); ++ } ++ else ++ { ++ node = DockContextAddNode(&g, node_id); ++ node->SetLocalFlags(flags); ++ } ++ node->LastFrameAlive = g.FrameCount; // Set this otherwise BeginDocked will undock during the same frame. ++ return node->ID; ++} ++ ++void ImGui::DockBuilderRemoveNode(ImGuiID node_id) ++{ ++ ImGuiContext& g = *GImGui; IM_UNUSED(g); ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id); ++ ++ ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id); ++ if (node == NULL) ++ return; ++ DockBuilderRemoveNodeDockedWindows(node_id, true); ++ DockBuilderRemoveNodeChildNodes(node_id); ++ // Node may have moved or deleted if e.g. any merge happened ++ node = DockContextFindNodeByID(&g, node_id); ++ if (node == NULL) ++ return; ++ if (node->IsCentralNode() && node->ParentNode) ++ node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode); ++ DockContextRemoveNode(&g, node, true); ++} ++ ++// root_id = 0 to remove all, root_id != 0 to remove child of given node. ++void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiDockContext* dc = &g.DockContext; ++ ++ ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL; ++ if (root_id && root_node == NULL) ++ return; ++ bool has_central_node = false; ++ ++ ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto; ++ ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto; ++ ++ // Process active windows ++ ImVector nodes_to_remove; ++ for (int n = 0; n < dc->Nodes.Data.Size; n++) ++ if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) ++ { ++ bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id); ++ if (want_removal) ++ { ++ if (node->IsCentralNode()) ++ has_central_node = true; ++ if (root_id != 0) ++ DockContextQueueNotifyRemovedNode(&g, node); ++ if (root_node) ++ { ++ DockNodeMoveWindows(root_node, node); ++ DockSettingsRenameNodeReferences(node->ID, root_node->ID); ++ } ++ nodes_to_remove.push_back(node); ++ } ++ } ++ ++ // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge) ++ // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead) ++ if (root_node) ++ { ++ root_node->AuthorityForPos = backup_root_node_authority_for_pos; ++ root_node->AuthorityForSize = backup_root_node_authority_for_size; ++ } ++ ++ // Apply to settings ++ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) ++ if (ImGuiID window_settings_dock_id = settings->DockId) ++ for (int n = 0; n < nodes_to_remove.Size; n++) ++ if (nodes_to_remove[n]->ID == window_settings_dock_id) ++ { ++ settings->DockId = root_id; ++ break; ++ } ++ ++ // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes ++ if (nodes_to_remove.Size > 1) ++ ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst); ++ for (int n = 0; n < nodes_to_remove.Size; n++) ++ DockContextRemoveNode(&g, nodes_to_remove[n], false); ++ ++ if (root_id == 0) ++ { ++ dc->Nodes.Clear(); ++ dc->Requests.clear(); ++ } ++ else if (has_central_node) ++ { ++ root_node->CentralNode = root_node; ++ root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode); ++ } ++} ++ ++void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs) ++{ ++ // Clear references in settings ++ ImGuiContext& g = *GImGui; ++ if (clear_settings_refs) ++ { ++ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) ++ { ++ bool want_removal = (root_id == 0) || (settings->DockId == root_id); ++ if (!want_removal && settings->DockId != 0) ++ if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId)) ++ if (DockNodeGetRootNode(node)->ID == root_id) ++ want_removal = true; ++ if (want_removal) ++ settings->DockId = 0; ++ } ++ } ++ ++ // Clear references in windows ++ for (int n = 0; n < g.Windows.Size; n++) ++ { ++ ImGuiWindow* window = g.Windows[n]; ++ bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id); ++ if (want_removal) ++ { ++ const ImGuiID backup_dock_id = window->DockId; ++ IM_UNUSED(backup_dock_id); ++ DockContextProcessUndockWindow(&g, window, clear_settings_refs); ++ if (!clear_settings_refs) ++ IM_ASSERT(window->DockId == backup_dock_id); ++ } ++ } ++} ++ ++// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created. ++// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set. ++// FIXME-DOCK: We are not exposing nor using split_outer. ++ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(split_dir != ImGuiDir_None); ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir); ++ ++ ImGuiDockNode* node = DockContextFindNodeByID(&g, id); ++ if (node == NULL) ++ { ++ IM_ASSERT(node != NULL); ++ return 0; ++ } ++ ++ IM_ASSERT(!node->IsSplitNode()); // Assert if already Split ++ ++ ImGuiDockRequest req; ++ req.Type = ImGuiDockRequestType_Split; ++ req.DockTargetWindow = NULL; ++ req.DockTargetNode = node; ++ req.DockPayload = NULL; ++ req.DockSplitDir = split_dir; ++ req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir); ++ req.DockSplitOuter = false; ++ DockContextProcessDock(&g, &req); ++ ++ ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID; ++ ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID; ++ if (out_id_at_dir) ++ *out_id_at_dir = id_at_dir; ++ if (out_id_at_opposite_dir) ++ *out_id_at_opposite_dir = id_at_opposite_dir; ++ return id_at_dir; ++} ++ ++static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector* out_node_remap_pairs) ++{ ++ ImGuiContext& g = *GImGui; ++ ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known); ++ dst_node->SharedFlags = src_node->SharedFlags; ++ dst_node->LocalFlags = src_node->LocalFlags; ++ dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None; ++ dst_node->Pos = src_node->Pos; ++ dst_node->Size = src_node->Size; ++ dst_node->SizeRef = src_node->SizeRef; ++ dst_node->SplitAxis = src_node->SplitAxis; ++ dst_node->UpdateMergedFlags(); ++ ++ out_node_remap_pairs->push_back(src_node->ID); ++ out_node_remap_pairs->push_back(dst_node->ID); ++ ++ for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++) ++ if (src_node->ChildNodes[child_n]) ++ { ++ dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs); ++ dst_node->ChildNodes[child_n]->ParentNode = dst_node; ++ } ++ ++ IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0); ++ return dst_node; ++} ++ ++void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector* out_node_remap_pairs) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(src_node_id != 0); ++ IM_ASSERT(dst_node_id != 0); ++ IM_ASSERT(out_node_remap_pairs != NULL); ++ ++ DockBuilderRemoveNode(dst_node_id); ++ ++ ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id); ++ IM_ASSERT(src_node != NULL); ++ ++ out_node_remap_pairs->clear(); ++ DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs); ++ ++ IM_ASSERT((out_node_remap_pairs->Size % 2) == 0); ++} ++ ++void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name) ++{ ++ ImGuiWindow* src_window = FindWindowByName(src_name); ++ if (src_window == NULL) ++ return; ++ if (ImGuiWindow* dst_window = FindWindowByName(dst_name)) ++ { ++ dst_window->Pos = src_window->Pos; ++ dst_window->Size = src_window->Size; ++ dst_window->SizeFull = src_window->SizeFull; ++ dst_window->Collapsed = src_window->Collapsed; ++ } ++ else ++ { ++ ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name)); ++ if (!dst_settings) ++ dst_settings = CreateNewWindowSettings(dst_name); ++ ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos); ++ if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID) ++ { ++ dst_settings->ViewportPos = window_pos_2ih; ++ dst_settings->ViewportId = src_window->ViewportId; ++ dst_settings->Pos = ImVec2ih(0, 0); ++ } ++ else ++ { ++ dst_settings->Pos = window_pos_2ih; ++ } ++ dst_settings->Size = ImVec2ih(src_window->SizeFull); ++ dst_settings->Collapsed = src_window->Collapsed; ++ } ++} ++ ++// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed. ++void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(src_dockspace_id != 0); ++ IM_ASSERT(dst_dockspace_id != 0); ++ IM_ASSERT(in_window_remap_pairs != NULL); ++ IM_ASSERT((in_window_remap_pairs->Size % 2) == 0); ++ ++ // Duplicate entire dock ++ // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart, ++ // whereas we could attempt to at least keep them together in a new, same floating node. ++ ImVector node_remap_pairs; ++ DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs); ++ ++ // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes ++ // (The windows associated to src_dockspace_id are staying in place) ++ ImVector src_windows; ++ for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2) ++ { ++ const char* src_window_name = (*in_window_remap_pairs)[remap_window_n]; ++ const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1]; ++ ImGuiID src_window_id = ImHashStr(src_window_name); ++ src_windows.push_back(src_window_id); ++ ++ // Search in the remapping tables ++ ImGuiID src_dock_id = 0; ++ if (ImGuiWindow* src_window = FindWindowByID(src_window_id)) ++ src_dock_id = src_window->DockId; ++ else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id)) ++ src_dock_id = src_window_settings->DockId; ++ ImGuiID dst_dock_id = 0; ++ for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2) ++ if (node_remap_pairs[dock_remap_n] == src_dock_id) ++ { ++ dst_dock_id = node_remap_pairs[dock_remap_n + 1]; ++ //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear ++ break; ++ } ++ ++ if (dst_dock_id != 0) ++ { ++ // Docked windows gets redocked into the new node hierarchy. ++ IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id); ++ DockBuilderDockWindow(dst_window_name, dst_dock_id); ++ } ++ else ++ { ++ // Floating windows gets their settings transferred (regardless of whether the new window already exist or not) ++ // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together? ++ IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name); ++ DockBuilderCopyWindowSettings(src_window_name, dst_window_name); ++ } + } ++ ++ // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list. ++ // Find those windows and move to them to the cloned dock node. This may be optional? ++ // Dock those are a second step as undocking would invalidate source dock nodes. ++ struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } }; ++ ImVector dock_remaining_windows; ++ for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2) ++ if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n]) ++ { ++ ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1]; ++ ImGuiDockNode* node = DockBuilderGetNode(src_dock_id); ++ for (int window_n = 0; window_n < node->Windows.Size; window_n++) ++ { ++ ImGuiWindow* window = node->Windows[window_n]; ++ if (src_windows.contains(window->ID)) ++ continue; ++ ++ // Docked windows gets redocked into the new node hierarchy. ++ IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id); ++ dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id)); ++ } ++ } ++ for (const DockRemainingWindowTask& task : dock_remaining_windows) ++ DockBuilderDockWindow(task.Window->Name, task.DockId); ++} ++ ++// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node. ++void ImGui::DockBuilderFinish(ImGuiID root_id) ++{ ++ ImGuiContext& g = *GImGui; ++ //DockContextRebuild(&g); ++ DockContextBuildAddWindowsToNodes(&g, root_id); + } + + //----------------------------------------------------------------------------- +-// [SECTION] DOCKING ++// Docking: Begin/End Support Functions (called from Begin/End) ++//----------------------------------------------------------------------------- ++// - GetWindowAlwaysWantOwnTabBar() ++// - DockContextBindNodeToWindow() ++// - BeginDocked() ++// - BeginDockableDragDropSource() ++// - BeginDockableDragDropTarget() ++//----------------------------------------------------------------------------- ++ ++bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window) ++{ ++ ImGuiContext& g = *GImGui; ++ if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar) ++ if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0) ++ if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise ++ return true; ++ return false; ++} ++ ++static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window) ++{ ++ ImGuiContext& g = *ctx; ++ ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId); ++ IM_ASSERT(window->DockNode == NULL); ++ ++ // We should not be docking into a split node (SetWindowDock should avoid this) ++ if (node && node->IsSplitNode()) ++ { ++ DockContextProcessUndockWindow(ctx, window); ++ return NULL; ++ } ++ ++ // Create node ++ if (node == NULL) ++ { ++ node = DockContextAddNode(ctx, window->DockId); ++ node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; ++ node->LastFrameAlive = g.FrameCount; ++ } ++ ++ // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, ++ // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). ++ // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. ++ // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. ++ if (!node->IsVisible) ++ { ++ ImGuiDockNode* ancestor_node = node; ++ while (!ancestor_node->IsVisible && ancestor_node->ParentNode) ++ ancestor_node = ancestor_node->ParentNode; ++ IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f); ++ DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node)); ++ DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node); ++ } ++ ++ // Add window to node ++ bool node_was_visible = node->IsVisible; ++ DockNodeAddWindow(node, window, true); ++ node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see) ++ IM_ASSERT(node == window->DockNode); ++ return node; ++} ++ ++static void StoreDockStyleForWindow(ImGuiWindow* window) ++{ ++ ImGuiContext& g = *GImGui; ++ for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) ++ window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]); ++} ++ ++void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) ++{ ++ ImGuiContext& g = *GImGui; ++ ++ // Clear fields ahead so most early-out paths don't have to do it ++ window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false; ++ ++ const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window); ++ if (auto_dock_node) ++ { ++ if (window->DockId == 0) ++ { ++ IM_ASSERT(window->DockNode == NULL); ++ window->DockId = DockContextGenNodeID(&g); ++ } ++ } ++ else ++ { ++ // Calling SetNextWindowPos() undock windows by default (by setting PosUndock) ++ bool want_undock = false; ++ want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0; ++ want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock; ++ if (want_undock) ++ { ++ DockContextProcessUndockWindow(&g, window); ++ return; ++ } ++ } ++ ++ // Bind to our dock node ++ ImGuiDockNode* node = window->DockNode; ++ if (node != NULL) ++ IM_ASSERT(window->DockId == node->ID); ++ if (window->DockId != 0 && node == NULL) ++ { ++ node = DockContextBindNodeToWindow(&g, window); ++ if (node == NULL) ++ return; ++ } ++ ++#if 0 ++ // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set ++ if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode)) ++ { ++ DockContextProcessUndockWindow(ctx, window); ++ return; ++ } ++#endif ++ ++ // Undock if our dockspace node disappeared ++ // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly. ++ if (node->LastFrameAlive < g.FrameCount) ++ { ++ // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking() ++ ImGuiDockNode* root_node = DockNodeGetRootNode(node); ++ if (root_node->LastFrameAlive < g.FrameCount) ++ DockContextProcessUndockWindow(&g, window); ++ else ++ window->DockIsActive = true; ++ return; ++ } ++ ++ // Store style overrides ++ StoreDockStyleForWindow(window); ++ ++ // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window, ++ // and never create neither a host window neither a tab bar. ++ // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test) ++ if (node->HostWindow == NULL) ++ { ++ if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing) ++ window->DockIsActive = true; ++ if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window ++ DockNodeHideWindowDuringHostWindowCreation(window); ++ return; ++ } ++ ++ // We can have zero-sized nodes (e.g. children of a small-size dockspace) ++ IM_ASSERT(node->HostWindow); ++ IM_ASSERT(node->IsLeafNode()); ++ IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f); ++ node->State = ImGuiDockNodeState_HostWindowVisible; ++ ++ // Undock if we are submitted earlier than the host window ++ if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext) ++ { ++ DockContextProcessUndockWindow(&g, window); ++ return; ++ } ++ ++ // Position/Size window ++ SetNextWindowPos(node->Pos); ++ SetNextWindowSize(node->Size); ++ g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos() ++ window->DockIsActive = true; ++ window->DockNodeIsVisible = true; ++ window->DockTabIsVisible = false; ++ if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) ++ return; ++ ++ // When the window is selected we mark it as visible. ++ if (node->VisibleWindow == window) ++ window->DockTabIsVisible = true; ++ ++ // Update window flag ++ IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0); ++ window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize; ++ window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding; ++ if (node->IsHiddenTabBar() || node->IsNoTabBar()) ++ window->Flags |= ImGuiWindowFlags_NoTitleBar; ++ else ++ window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! ++ ++ // Save new dock order only if the window has been visible once already ++ // This allows multiple windows to be created in the same frame and have their respective dock orders preserved. ++ if (node->TabBar && window->WasActive) ++ window->DockOrder = (short)DockNodeGetTabOrder(window); ++ ++ if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL) ++ *p_open = false; ++ ++ // Update ChildId to allow returning from Child to Parent with Escape ++ ImGuiWindow* parent_window = window->DockNode->HostWindow; ++ window->ChildId = parent_window->GetID(window->Name); ++} ++ ++void ImGui::BeginDockableDragDropSource(ImGuiWindow* window) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(g.ActiveId == window->MoveId); ++ IM_ASSERT(g.MovingWindow == window); ++ IM_ASSERT(g.CurrentWindow == window); ++ ++ // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking. ++ if (g.IO.ConfigDockingWithShift != g.IO.KeyShift) ++ { ++ // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance. ++ // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active ++ // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function) ++ IM_ASSERT(g.NextWindowData.Flags == 0); ++ if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f) ++ SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock)); ++ return; ++ } ++ ++ g.LastItemData.ID = window->MoveId; ++ window = window->RootWindowDockTree; ++ IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); ++ bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit ++ ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess; ++ if (is_drag_docking && BeginDragDropSource(drag_drop_flags)) ++ { ++ SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window)); ++ EndDragDropSource(); ++ StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it. ++ } ++} ++ ++void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) ++{ ++ ImGuiContext& g = *GImGui; ++ ++ //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace ++ IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); ++ if (!g.DragDropActive) ++ return; ++ //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); ++ if (!BeginDragDropTargetCustom(window->Rect(), window->ID)) ++ return; ++ ++ // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering ++ // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly) ++ const ImGuiPayload* payload = &g.DragDropPayload; ++ if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data)) ++ { ++ EndDragDropTarget(); ++ return; ++ } ++ ++ ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data; ++ if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) ++ { ++ // Select target node ++ // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation) ++ bool dock_into_floating_window = false; ++ ImGuiDockNode* node = NULL; ++ if (window->DockNodeAsHost) ++ { ++ // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos(). ++ node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); ++ ++ // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active) ++ // In this case we need to fallback into any leaf mode, possibly the central node. ++ // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. ++ if (node && node->IsDockSpace() && node->IsRootNode()) ++ node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node); ++ } ++ else ++ { ++ if (window->DockNode) ++ node = window->DockNode; ++ else ++ dock_into_floating_window = true; // Dock into a regular window ++ } ++ ++ const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); ++ const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max); ++ ++ // Preview docking request and find out split direction/ratio ++ //const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window. ++ const bool do_preview = payload->IsPreview() || payload->IsDelivery(); ++ if (do_preview && (node != NULL || dock_into_floating_window)) ++ { ++ // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear. ++ ImGuiDockPreviewData split_inner; ++ ImGuiDockPreviewData split_outer; ++ ImGuiDockPreviewData* split_data = &split_inner; ++ if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode())) ++ if (ImGuiDockNode* root_node = DockNodeGetRootNode(node)) ++ { ++ DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true); ++ if (split_outer.IsSplitDirExplicit) ++ split_data = &split_outer; ++ } ++ if (!node || node->IsLeafNode()) ++ DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false); ++ if (split_data == &split_outer) ++ split_inner.IsDropAllowed = false; ++ ++ // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes ++ DockNodePreviewDockRender(window, node, payload_window, &split_inner); ++ DockNodePreviewDockRender(window, node, payload_window, &split_outer); ++ ++ // Queue docking request ++ if (split_data->IsDropAllowed && payload->IsDelivery()) ++ DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer); ++ } ++ } ++ EndDragDropTarget(); ++} ++ + //----------------------------------------------------------------------------- ++// Docking: Settings ++//----------------------------------------------------------------------------- ++// - DockSettingsRenameNodeReferences() ++// - DockSettingsRemoveNodeReferences() ++// - DockSettingsFindNodeSettings() ++// - DockSettingsHandler_ApplyAll() ++// - DockSettingsHandler_ReadOpen() ++// - DockSettingsHandler_ReadLine() ++// - DockSettingsHandler_DockNodeToSettings() ++// - DockSettingsHandler_WriteAll() ++//----------------------------------------------------------------------------- ++ ++static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id) ++{ ++ ImGuiContext& g = *GImGui; ++ IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id); ++ for (int window_n = 0; window_n < g.Windows.Size; window_n++) ++ { ++ ImGuiWindow* window = g.Windows[window_n]; ++ if (window->DockId == old_node_id && window->DockNode == NULL) ++ window->DockId = new_node_id; ++ } ++ //// FIXME-OPT: We could remove this loop by storing the index in the map ++ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) ++ if (settings->DockId == old_node_id) ++ settings->DockId = new_node_id; ++} ++ ++// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings ++static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count) ++{ ++ ImGuiContext& g = *GImGui; ++ int found = 0; ++ //// FIXME-OPT: We could remove this loop by storing the index in the map ++ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) ++ for (int node_n = 0; node_n < node_ids_count; node_n++) ++ if (settings->DockId == node_ids[node_n]) ++ { ++ settings->DockId = 0; ++ settings->DockOrder = -1; ++ if (++found < node_ids_count) ++ break; ++ return; ++ } ++} ++ ++static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id) ++{ ++ // FIXME-OPT ++ ImGuiDockContext* dc = &ctx->DockContext; ++ for (int n = 0; n < dc->NodesSettings.Size; n++) ++ if (dc->NodesSettings[n].ID == id) ++ return &dc->NodesSettings[n]; ++ return NULL; ++} ++ ++// Clear settings data ++static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) ++{ ++ ImGuiDockContext* dc = &ctx->DockContext; ++ dc->NodesSettings.clear(); ++ DockContextClearNodes(ctx, 0, true); ++} ++ ++// Recreate nodes based on settings data ++static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) ++{ ++ // Prune settings at boot time only ++ ImGuiDockContext* dc = &ctx->DockContext; ++ if (ctx->Windows.Size == 0) ++ DockContextPruneUnusedSettingsNodes(ctx); ++ DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); ++ DockContextBuildAddWindowsToNodes(ctx, 0); ++} ++ ++static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) ++{ ++ if (strcmp(name, "Data") != 0) ++ return NULL; ++ return (void*)1; ++} ++ ++static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line) ++{ ++ char c = 0; ++ int x = 0, y = 0; ++ int r = 0; ++ ++ // Parsing, e.g. ++ // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 " ++ // " DockNode ID=0x00000002 Parent=0x00000001 " ++ // Important: this code expect currently fields in a fixed order. ++ ImGuiDockNodeSettings node; ++ line = ImStrSkipBlank(line); ++ if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); } ++ else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; } ++ else return; ++ if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return; ++ if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; } ++ if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; } ++ if (node.ParentNodeId == 0) ++ { ++ if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return; ++ if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return; ++ } ++ else ++ { ++ if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); } ++ } ++ if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; } ++ if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; } ++ if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; } ++ if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; } ++ if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; } ++ if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; } ++ if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; } ++ if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; } ++ if (node.ParentNodeId != 0) ++ if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId)) ++ node.Depth = parent_settings->Depth + 1; ++ ctx->DockContext.NodesSettings.push_back(node); ++} ++ ++static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth) ++{ ++ ImGuiDockNodeSettings node_settings; ++ IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3))); ++ node_settings.ID = node->ID; ++ node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0; ++ node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0; ++ node_settings.SelectedTabId = node->SelectedTabId; ++ node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None); ++ node_settings.Depth = (char)depth; ++ node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_); ++ node_settings.Pos = ImVec2ih(node->Pos); ++ node_settings.Size = ImVec2ih(node->Size); ++ node_settings.SizeRef = ImVec2ih(node->SizeRef); ++ dc->NodesSettings.push_back(node_settings); ++ if (node->ChildNodes[0]) ++ DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1); ++ if (node->ChildNodes[1]) ++ DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1); ++} ++ ++static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) ++{ ++ ImGuiContext& g = *ctx; ++ ImGuiDockContext* dc = &ctx->DockContext; ++ if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) ++ return; ++ ++ // Gather settings data ++ // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer) ++ dc->NodesSettings.resize(0); ++ dc->NodesSettings.reserve(dc->Nodes.Data.Size); ++ for (int n = 0; n < dc->Nodes.Data.Size; n++) ++ if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) ++ if (node->IsRootNode()) ++ DockSettingsHandler_DockNodeToSettings(dc, node, 0); ++ ++ int max_depth = 0; ++ for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) ++ max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth); ++ ++ // Write to text buffer ++ buf->appendf("[%s][Data]\n", handler->TypeName); ++ for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) ++ { ++ const int line_start_pos = buf->size(); (void)line_start_pos; ++ const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n]; ++ buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file ++ buf->appendf(" ID=0x%08X", node_settings->ID); ++ if (node_settings->ParentNodeId) ++ { ++ buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y); ++ } ++ else ++ { ++ if (node_settings->ParentWindowId) ++ buf->appendf(" Window=0x%08X", node_settings->ParentWindowId); ++ buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y); ++ } ++ if (node_settings->SplitAxis != ImGuiAxis_None) ++ buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y'); ++ if (node_settings->Flags & ImGuiDockNodeFlags_NoResize) ++ buf->appendf(" NoResize=1"); ++ if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode) ++ buf->appendf(" CentralNode=1"); ++ if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar) ++ buf->appendf(" NoTabBar=1"); ++ if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar) ++ buf->appendf(" HiddenTabBar=1"); ++ if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton) ++ buf->appendf(" NoWindowMenuButton=1"); ++ if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton) ++ buf->appendf(" NoCloseButton=1"); ++ if (node_settings->SelectedTabId) ++ buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId); ++ ++ // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!) ++ if (g.IO.ConfigDebugIniSettings) ++ if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID)) ++ { ++ buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything ++ if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ++ buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name); ++ // Iterate settings so we can give info about windows that didn't exist during the session. ++ int contains_window = 0; ++ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) ++ if (settings->DockId == node_settings->ID) ++ { ++ if (contains_window++ == 0) ++ buf->appendf(" ; contains "); ++ buf->appendf("'%s' ", settings->GetName()); ++ } ++ } + +-// (this section is filled in the 'docking' branch) ++ buf->appendf("\n"); ++ } ++ buf->appendf("\n"); ++} + + + //----------------------------------------------------------------------------- +@@ -15008,14 +20646,14 @@ static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* view + if (HIMC himc = ::ImmGetContext(hwnd)) + { + COMPOSITIONFORM composition_form = {}; +- composition_form.ptCurrentPos.x = (LONG)data->InputPos.x; +- composition_form.ptCurrentPos.y = (LONG)data->InputPos.y; ++ composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x); ++ composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y); + composition_form.dwStyle = CFS_FORCE_POSITION; + ::ImmSetCompositionWindow(himc, &composition_form); + CANDIDATEFORM candidate_form = {}; + candidate_form.dwStyle = CFS_CANDIDATEPOS; +- candidate_form.ptCurrentPos.x = (LONG)data->InputPos.x; +- candidate_form.ptCurrentPos.y = (LONG)data->InputPos.y; ++ candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x); ++ candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y); + ::ImmSetCandidateWindow(himc, &candidate_form); + ::ImmReleaseContext(hwnd, himc); + } +@@ -15037,6 +20675,7 @@ static void Platform_SetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImG + // - ShowFontAtlas() [Internal] + // - ShowMetricsWindow() + // - DebugNodeColumns() [Internal] ++// - DebugNodeDockNode() [Internal] + // - DebugNodeDrawList() [Internal] + // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal] + // - DebugNodeFont() [Internal] +@@ -15059,12 +20698,14 @@ void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* + + ImVec2 scale = bb.GetSize() / viewport->Size; + ImVec2 off = bb.Min - viewport->Pos * scale; +- float alpha_mul = 1.0f; ++ float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f; + window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f)); + for (ImGuiWindow* thumb_window : g.Windows) + { + if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow)) + continue; ++ if (thumb_window->Viewport != viewport) ++ continue; + + ImRect thumb_r = thumb_window->Rect(); + ImRect title_r = thumb_window->TitleBarRect(); +@@ -15088,10 +20729,19 @@ static void RenderViewportsThumbnails() + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ++ // Draw monitor and calculate their boundaries + float SCALE = 1.0f / 8.0f; +- ImRect bb_full(g.Viewports[0]->Pos, g.Viewports[0]->Pos + g.Viewports[0]->Size); ++ ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); ++ for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors) ++ bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize)); + ImVec2 p = window->DC.CursorPos; + ImVec2 off = p - bb_full.Min * SCALE; ++ for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors) ++ { ++ ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE); ++ window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f); ++ window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f); ++ } + + // Draw viewports + for (ImGuiViewportP* viewport : g.Viewports) +@@ -15102,6 +20752,13 @@ static void RenderViewportsThumbnails() + ImGui::Dummy(bb_full.GetSize() * SCALE); + } + ++static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs) ++{ ++ const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs; ++ const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs; ++ return b->LastFocusedStampCount - a->LastFocusedStampCount; ++} ++ + // Draw an arbitrary US keyboard layout to visualize translated keys + void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list) + { +@@ -15469,14 +21126,38 @@ void ImGui::ShowMetricsWindow(bool* p_open) + Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh); + Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes); + for (ImGuiViewportP* viewport : g.Viewports) ++ { ++ bool viewport_has_drawlist = false; + for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists) ++ { ++ if (!viewport_has_drawlist) ++ Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID); ++ viewport_has_drawlist = true; + DebugNodeDrawList(NULL, viewport, draw_list, "DrawList"); ++ } ++ } + TreePop(); + } + + // Viewports + if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size)) + { ++ cfg->HighlightMonitorIdx = -1; ++ bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size); ++ SameLine(); ++ MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors."); ++ if (open) ++ { ++ for (int i = 0; i < g.PlatformIO.Monitors.Size; i++) ++ { ++ DebugNodePlatformMonitor(&g.PlatformIO.Monitors[i], "Monitor", i); ++ if (IsItemHovered()) ++ cfg->HighlightMonitorIdx = i; ++ } ++ DebugNodePlatformMonitor(&g.FallbackMonitor, "Fallback", 0); ++ TreePop(); ++ } ++ + SetNextItemOpen(true, ImGuiCond_Once); + if (TreeNode("Windows Minimap")) + { +@@ -15485,6 +21166,26 @@ void ImGui::ShowMetricsWindow(bool* p_open) + } + cfg->HighlightViewportID = 0; + ++ BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0); ++ if (TreeNode("Inferred Z order (front-to-back)")) ++ { ++ static ImVector viewports; ++ viewports.resize(g.Viewports.Size); ++ memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes()); ++ if (viewports.Size > 1) ++ ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount); ++ for (ImGuiViewportP* viewport : viewports) ++ { ++ BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"", ++ viewport->Idx, viewport->ID, viewport->LastFocusedStampCount, ++ (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A", ++ viewport->Window ? viewport->Window->Name : "N/A"); ++ if (IsItemHovered()) ++ cfg->HighlightViewportID = viewport->ID; ++ } ++ TreePop(); ++ } ++ + for (ImGuiViewportP* viewport : g.Viewports) + DebugNodeViewport(viewport); + TreePop(); +@@ -15563,6 +21264,17 @@ void ImGui::ShowMetricsWindow(bool* p_open) + #ifdef IMGUI_HAS_DOCK + if (TreeNode("Docking")) + { ++ static bool root_nodes_only = true; ++ ImGuiDockContext* dc = &g.DockContext; ++ Checkbox("List root nodes", &root_nodes_only); ++ Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes); ++ if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } ++ SameLine(); ++ if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } ++ for (int n = 0; n < dc->Nodes.Data.Size; n++) ++ if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) ++ if (!root_nodes_only || node->IsRootNode()) ++ DebugNodeDockNode(node, "Node"); + TreePop(); + } + #endif // #ifdef IMGUI_HAS_DOCK +@@ -15606,11 +21318,34 @@ void ImGui::ShowMetricsWindow(bool* p_open) + } + + #ifdef IMGUI_HAS_DOCK ++ if (TreeNode("SettingsDocking", "Settings packed data: Docking")) ++ { ++ ImGuiDockContext* dc = &g.DockContext; ++ Text("In SettingsWindows:"); ++ for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) ++ if (settings->DockId != 0) ++ BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder); ++ Text("In SettingsNodes:"); ++ for (int n = 0; n < dc->NodesSettings.Size; n++) ++ { ++ ImGuiDockNodeSettings* settings = &dc->NodesSettings[n]; ++ const char* selected_tab_name = NULL; ++ if (settings->SelectedTabId) ++ { ++ if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId)) ++ selected_tab_name = window->Name; ++ else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId)) ++ selected_tab_name = window_settings->GetName(); ++ } ++ BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : ""); ++ } ++ TreePop(); ++ } + #endif // #ifdef IMGUI_HAS_DOCK + + if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) + { +- InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly); ++ InputTextMultiline("##Ini", const_cast(g.SettingsIniData.c_str()), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly); + TreePop(); + } + TreePop(); +@@ -15739,9 +21474,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) + Text("WINDOWING"); + Indent(); + Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); +- Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindow->Name : "NULL"); ++ Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL"); + Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); ++ Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0); + Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); ++ Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0); + Unindent(); + + Text("ITEMS"); +@@ -15835,8 +21572,21 @@ void ImGui::ShowMetricsWindow(bool* p_open) + + #ifdef IMGUI_HAS_DOCK + // Overlay: Display Docking info +- if (show_docking_nodes && g.IO.KeyCtrl) +- { ++ if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode) ++ { ++ char buf[64] = ""; ++ char* p = buf; ++ ImGuiDockNode* node = g.DebugHoveredDockNode; ++ ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport()); ++ p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : ""); ++ p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId); ++ p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y); ++ p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y); ++ int depth = DockNodeGetDepth(node); ++ overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255)); ++ ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth; ++ overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255)); ++ overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf); + } + #endif // #ifdef IMGUI_HAS_DOCK + +@@ -15912,6 +21662,93 @@ void ImGui::DebugNodeColumns(ImGuiOldColumns* columns) + TreePop(); + } + ++static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled) ++{ ++ using namespace ImGui; ++ PushID(label); ++ PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); ++ Text("%s:", label); ++ if (!enabled) ++ BeginDisabled(); ++ CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize); ++ CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX); ++ CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY); ++ CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar); ++ CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar); ++ CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton); ++ CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton); ++ CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute); ++ CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags ++ CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit); ++ CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther); ++ CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe); ++ CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther); ++ CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty); ++ CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking); ++ if (!enabled) ++ EndDisabled(); ++ PopStyleVar(); ++ PopID(); ++} ++ ++// [DEBUG] Display contents of ImDockNode ++void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label) ++{ ++ ImGuiContext& g = *GImGui; ++ const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly ++ const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted ++ if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } ++ bool open; ++ ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None; ++ if (node->Windows.Size > 0) ++ open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); ++ else ++ open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); ++ if (!is_alive) { PopStyleColor(); } ++ if (is_active && IsItemHovered()) ++ if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow) ++ GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255)); ++ if (open) ++ { ++ IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node); ++ IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node); ++ BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)", ++ node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y); ++ DebugNodeWindow(node->HostWindow, "HostWindow"); ++ DebugNodeWindow(node->VisibleWindow, "VisibleWindow"); ++ BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId); ++ BulletText("Misc:%s%s%s%s%s%s%s", ++ node->IsDockSpace() ? " IsDockSpace" : "", ++ node->IsCentralNode() ? " IsCentralNode" : "", ++ is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "", ++ node->WantLockSizeOnce ? " WantLockSizeOnce" : "", ++ node->HasCentralNodeChild ? " HasCentralNodeChild" : ""); ++ if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags)) ++ { ++ if (BeginTable("flags", 4)) ++ { ++ TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false); ++ TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true); ++ TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false); ++ TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true); ++ EndTable(); ++ } ++ TreePop(); ++ } ++ if (node->ParentNode) ++ DebugNodeDockNode(node->ParentNode, "ParentNode"); ++ if (node->ChildNodes[0]) ++ DebugNodeDockNode(node->ChildNodes[0], "Child[0]"); ++ if (node->ChildNodes[1]) ++ DebugNodeDockNode(node->ChildNodes[1], "Child[1]"); ++ if (node->TabBar) ++ DebugNodeTabBar(node->TabBar, "TabBar"); ++ DebugNodeWindowsList(&node->Windows, "Windows"); ++ ++ TreePop(); ++ } ++} ++ + static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id) + { + union { void* ptr; int integer; } tex_id_opaque; +@@ -15923,10 +21760,10 @@ static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID + } + + // [DEBUG] Display contents of ImDrawList ++// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport. + void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label) + { + ImGuiContext& g = *GImGui; +- IM_UNUSED(viewport); // Used in docking branch + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + int cmd_count = draw_list->CmdBuffer.Size; + if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL) +@@ -15941,7 +21778,7 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con + return; + } + +- ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list ++ ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list + if (window && IsItemHovered() && fg_draw_list) + fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!node_open) +@@ -16207,25 +22044,46 @@ void ImGui::DebugNodeViewport(ImGuiViewportP* viewport) + { + ImGuiContext& g = *GImGui; + SetNextItemOpen(true, ImGuiCond_Once); +- bool open = TreeNode("viewport0", "Viewport #%d", 0); ++ bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"); + if (IsItemHovered()) + g.DebugMetricsConfig.HighlightViewportID = viewport->ID; + if (open) + { + ImGuiWindowFlags flags = viewport->Flags; +- BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f", ++ BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Inset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%", + viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y, +- viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y); +- BulletText("Flags: 0x%04X =%s%s%s", viewport->Flags, +- (flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", ++ viewport->WorkInsetMin.x, viewport->WorkInsetMin.y, viewport->WorkInsetMax.x, viewport->WorkInsetMax.y, ++ viewport->PlatformMonitor, viewport->DpiScale * 100.0f); ++ if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } } ++ BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags, ++ //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard + (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "", +- (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : ""); ++ (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "", ++ (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "", ++ (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "", ++ (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "", ++ (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "", ++ (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", ++ (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "", ++ (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "", ++ (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", ++ (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "", ++ (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "", ++ (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : ""); + for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists) + DebugNodeDrawList(NULL, viewport, draw_list, "DrawList"); + TreePop(); + } + } + ++void ImGui::DebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor, const char* label, int idx) ++{ ++ BulletText("%s %d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)", ++ label, idx, monitor->DpiScale * 100.0f, ++ monitor->MainPos.x, monitor->MainPos.y, monitor->MainPos.x + monitor->MainSize.x, monitor->MainPos.y + monitor->MainSize.y, monitor->MainSize.x, monitor->MainSize.y, ++ monitor->WorkPos.x, monitor->WorkPos.y, monitor->WorkPos.x + monitor->WorkSize.x, monitor->WorkPos.y + monitor->WorkSize.y, monitor->WorkSize.x, monitor->WorkSize.y); ++} ++ + void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label) + { + if (window == NULL) +@@ -16264,6 +22122,7 @@ void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label) + (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "", + (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "", + (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : ""); ++ BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId); + BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : ""); + BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); + BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); +@@ -16280,7 +22139,15 @@ void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label) + for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++) + BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater. + BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); ++ ++ BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y); ++ BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1); ++ BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible); ++ if (window->DockNode || window->DockNodeAsHost) ++ DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode"); ++ + if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); } ++ if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); } + if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); } + if (window->ParentWindowForFocusRoute != NULL) { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); } + if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); } +@@ -16421,11 +22288,13 @@ void ImGui::ShowDebugLogWindow(bool* p_open) + ShowDebugLogFlag("Errors", ImGuiDebugLogFlags_EventError); + ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId); + ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper); ++ ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking); + ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus); + ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO); + ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav); + ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup); + ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection); ++ ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport); + ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting); + + if (SmallButton("Clear")) +diff --git a/imgui.h b/imgui.h +index 77ca8e04..24a004b6 100644 +--- a/imgui.h ++++ b/imgui.h +@@ -31,6 +31,8 @@ + #define IMGUI_VERSION "1.91.3" + #define IMGUI_VERSION_NUM 19130 + #define IMGUI_HAS_TABLE ++#define IMGUI_HAS_VIEWPORT // Viewport WIP branch ++#define IMGUI_HAS_DOCK // Docking WIP branch + + /* + +@@ -43,13 +45,13 @@ Index of this file: + // [SECTION] Helpers: Debug log, Memory allocations macros, ImVector<> + // [SECTION] ImGuiStyle + // [SECTION] ImGuiIO +-// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) ++// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiWindowClass, ImGuiPayload) + // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) + // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) + // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) + // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) + // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) +-// [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformImeData) ++// [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) + // [SECTION] Obsolete functions and types + + */ +@@ -103,8 +105,10 @@ Index of this file: + #define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) + #define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) + #elif !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__)) +-#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) +-#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) ++//#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) ++//#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) ++#define IM_FMTARGS(FMT) ++#define IM_FMTLIST(FMT) + #else + #define IM_FMTARGS(FMT) + #define IM_FMTLIST(FMT) +@@ -179,8 +183,9 @@ struct ImGuiListClipper; // Helper to manually clip large list of ite + struct ImGuiMultiSelectIO; // Structure to interact with a BeginMultiSelect()/EndMultiSelect() block + struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame + struct ImGuiPayload; // User data payload for drag and drop operations +-struct ImGuiPlatformIO; // Interface between platform/renderer backends and ImGui (e.g. Clipboard, IME hooks). Extends ImGuiIO. In docking branch, this gets extended to support multi-viewports. ++struct ImGuiPlatformIO; // Interface between platform/renderer backends and ImGui (e.g. Clipboard, IME, Multi-Viewport support). Extends ImGuiIO. + struct ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. ++struct ImGuiPlatformMonitor; // Multi-viewport support: user-provided bounds for each connected monitor/display. Used when positioning popups and tooltips to avoid them straddling monitors + struct ImGuiSelectionBasicStorage; // Optional helper to store multi-selection state + apply multi-selection requests. + struct ImGuiSelectionExternalStorage;//Optional helper to apply multi-selection requests to existing randomly accessible storage. + struct ImGuiSelectionRequest; // A selection request (stored in ImGuiMultiSelectIO) +@@ -192,7 +197,8 @@ struct ImGuiTableSortSpecs; // Sorting specifications for a table (often + struct ImGuiTableColumnSortSpecs; // Sorting specification for one column of a table + struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) + struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]") +-struct ImGuiViewport; // A Platform Window (always only one in 'master' branch), in the future may represent Platform Monitor ++struct ImGuiViewport; // A Platform Window (always 1 unless multi-viewport are enabled. One per platform window to output to). In the future may represent Platform Monitor ++struct ImGuiWindowClass; // Window class (rare/advanced uses: provide hints to the platform backend via altered viewport flags and parent/child info) + + // Enumerations + // - We don't use strongly typed enums much because they add constraints (can't extend in private code, can't store typed in bit fields, extra casting on iteration) +@@ -226,6 +232,7 @@ typedef int ImGuiChildFlags; // -> enum ImGuiChildFlags_ // Flags: f + typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. + typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags + typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() ++typedef int ImGuiDockNodeFlags; // -> enum ImGuiDockNodeFlags_ // Flags: for DockSpace() + typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() + typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() + typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. +@@ -395,10 +402,12 @@ namespace ImGui + IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. + IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options. IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. + IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives ++ IMGUI_API float GetWindowDpiScale(); // get DPI scale currently associated to the current window's viewport. + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) + IMGUI_API ImVec2 GetWindowSize(); // get current window size (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) + IMGUI_API float GetWindowWidth(); // get current window width (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().x. + IMGUI_API float GetWindowHeight(); // get current window height (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().y. ++ IMGUI_API ImGuiViewport*GetWindowViewport(); // get viewport currently associated to the current window. + + // Window manipulation + // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). +@@ -410,6 +419,7 @@ namespace ImGui + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin() + IMGUI_API void SetNextWindowScroll(const ImVec2& scroll); // set next window scrolling value (use < 0.0f to not affect a given axis). + IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. ++ IMGUI_API void SetNextWindowViewport(ImGuiID viewport_id); // set next window viewport + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). +@@ -861,6 +871,26 @@ namespace ImGui + IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. + IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. + ++ // Docking ++ // [BETA API] Enable with io.ConfigFlags |= ImGuiConfigFlags_DockingEnable. ++ // Note: You can use most Docking facilities without calling any API. You DO NOT need to call DockSpace() to use Docking! ++ // - Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking. ++ // - Drag from window menu button (upper-left button) to undock an entire node (all windows). ++ // - When io.ConfigDockingWithShift == true, you instead need to hold SHIFT to enable docking. ++ // About dockspaces: ++ // - Use DockSpaceOverViewport() to create a window covering the screen or a specific viewport + a dockspace inside it. ++ // This is often used with ImGuiDockNodeFlags_PassthruCentralNode to make it transparent. ++ // - Use DockSpace() to create an explicit dock node _within_ an existing window. See Docking demo for details. ++ // - Important: Dockspaces need to be submitted _before_ any window they can host. Submit it early in your frame! ++ // - Important: Dockspaces need to be kept alive if hidden, otherwise windows docked into it will be undocked. ++ // e.g. if you have multiple tabs with a dockspace inside each tab: submit the non-visible dockspaces with ImGuiDockNodeFlags_KeepAliveOnly. ++ IMGUI_API ImGuiID DockSpace(ImGuiID dockspace_id, const ImVec2& size = ImVec2(0, 0), ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); ++ IMGUI_API ImGuiID DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); ++ IMGUI_API void SetNextWindowDockID(ImGuiID dock_id, ImGuiCond cond = 0); // set next window dock id ++ IMGUI_API void SetNextWindowClass(const ImGuiWindowClass* window_class); // set next window class (control docking compatibility + provide hints to platform backend via custom viewport flags and platform parent/child relationship) ++ IMGUI_API ImGuiID GetWindowDockID(); ++ IMGUI_API bool IsWindowDocked(); // is current window docked into another window? ++ + // Logging/Capture + // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. + IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout) +@@ -933,8 +963,8 @@ namespace ImGui + IMGUI_API ImGuiViewport* GetMainViewport(); // return primary/default viewport. This can never be NULL. + + // Background/Foreground Draw Lists +- IMGUI_API ImDrawList* GetBackgroundDrawList(); // this draw list will be the first rendered one. Useful to quickly draw shapes/text behind dear imgui contents. +- IMGUI_API ImDrawList* GetForegroundDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. ++ IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport = NULL); // get background draw list for the given viewport or viewport associated to the current window. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. ++ IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport = NULL); // get foreground draw list for the given viewport or viewport associated to the current window. this draw list will be the top-most rendered one. Useful to quickly draw shapes/text over dear imgui contents. + + // Miscellaneous Utilities + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. +@@ -1049,6 +1079,15 @@ namespace ImGui + IMGUI_API void* MemAlloc(size_t size); + IMGUI_API void MemFree(void* ptr); + ++ // (Optional) Platform/OS interface for multi-viewport support ++ // Read comments around the ImGuiPlatformIO structure for more details. ++ // Note: You may use GetWindowViewport() to get the current viewport of the current window. ++ IMGUI_API void UpdatePlatformWindows(); // call in main loop. will call CreateWindow/ResizeWindow/etc. platform functions for each secondary viewport, and DestroyWindow for each inactive viewport. ++ IMGUI_API void RenderPlatformWindowsDefault(void* platform_render_arg = NULL, void* renderer_render_arg = NULL); // call in main loop. will call RenderWindow/SwapBuffers platform functions for each secondary viewport which doesn't have the ImGuiViewportFlags_Minimized flag set. May be reimplemented by user for custom rendering needs. ++ IMGUI_API void DestroyPlatformWindows(); // call DestroyWindow platform functions for all viewports. call from backend Shutdown() if you need to close platform windows before imgui shutdown. otherwise will be called by DestroyContext(). ++ IMGUI_API ImGuiViewport* FindViewportByID(ImGuiID id); // this is a helper for backends. ++ IMGUI_API ImGuiViewport* FindViewportByPlatformHandle(void* platform_handle); // this is a helper for backends. the type platform_handle is decided by the backend (e.g. HWND, MyWindow*, GLFWwindow* etc.) ++ + } // namespace ImGui + + //----------------------------------------------------------------------------- +@@ -1079,6 +1118,7 @@ enum ImGuiWindowFlags_ + ImGuiWindowFlags_NoNavInputs = 1 << 16, // No gamepad/keyboard navigation within the window + ImGuiWindowFlags_NoNavFocus = 1 << 17, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB) + ImGuiWindowFlags_UnsavedDocument = 1 << 18, // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. ++ ImGuiWindowFlags_NoDocking = 1 << 19, // Disable docking of this window + ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, + ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, +@@ -1089,6 +1129,7 @@ enum ImGuiWindowFlags_ + ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() + ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal() + ImGuiWindowFlags_ChildMenu = 1 << 28, // Don't use! For internal use by BeginMenu() ++ ImGuiWindowFlags_DockNodeHost = 1 << 29, // Don't use! For internal use by Begin()/NewFrame() + + // Obsolete names + #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +@@ -1303,7 +1344,7 @@ enum ImGuiFocusedFlags_ + ImGuiFocusedFlags_RootWindow = 1 << 1, // Test from root window (top most parent of the current hierarchy) + ImGuiFocusedFlags_AnyWindow = 1 << 2, // Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! + ImGuiFocusedFlags_NoPopupHierarchy = 1 << 3, // Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) +- //ImGuiFocusedFlags_DockHierarchy = 1 << 4, // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) ++ ImGuiFocusedFlags_DockHierarchy = 1 << 4, // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows, + }; + +@@ -1317,7 +1358,7 @@ enum ImGuiHoveredFlags_ + ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) + ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered + ImGuiHoveredFlags_NoPopupHierarchy = 1 << 3, // IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) +- //ImGuiHoveredFlags_DockHierarchy = 1 << 4, // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) ++ ImGuiHoveredFlags_DockHierarchy = 1 << 4, // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 5, // Return true even if a popup window is normally blocking access to this item/window + //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 6, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 7, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. +@@ -1347,6 +1388,27 @@ enum ImGuiHoveredFlags_ + ImGuiHoveredFlags_NoSharedDelay = 1 << 17, // IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) + }; + ++// Flags for ImGui::DockSpace(), shared/inherited by child nodes. ++// (Some flags can be applied to individual nodes directly) ++// FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. ++enum ImGuiDockNodeFlags_ ++{ ++ ImGuiDockNodeFlags_None = 0, ++ ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. ++ //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // // Disable Central Node (the node which can stay empty) ++ ImGuiDockNodeFlags_NoDockingOverCentralNode = 1 << 2, // // Disable docking over the Central Node, which will be always kept empty. ++ ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, // // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. ++ ImGuiDockNodeFlags_NoDockingSplit = 1 << 4, // // Disable other windows/nodes from splitting this node. ++ ImGuiDockNodeFlags_NoResize = 1 << 5, // Saved // Disable resizing node using the splitter/separators. Useful with programmatically setup dockspaces. ++ ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6, // // Tab bar will automatically hide when there is a single window in the dock node. ++ ImGuiDockNodeFlags_NoUndocking = 1 << 7, // // Disable undocking this node. ++ ++#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ++ ImGuiDockNodeFlags_NoSplit = ImGuiDockNodeFlags_NoDockingSplit, // Renamed in 1.90 ++ ImGuiDockNodeFlags_NoDockingInCentralNode = ImGuiDockNodeFlags_NoDockingOverCentralNode, // Renamed in 1.90 ++#endif ++}; ++ + // Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() + enum ImGuiDragDropFlags_ + { +@@ -1601,6 +1663,15 @@ enum ImGuiConfigFlags_ + ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. + ImGuiConfigFlags_NoKeyboard = 1 << 6, // Instruct dear imgui to disable keyboard inputs and interactions. This is done by ignoring keyboard events and clearing existing states. + ++ // [BETA] Docking ++ ImGuiConfigFlags_DockingEnable = 1 << 7, // Docking enable flags. ++ ++ // [BETA] Viewports ++ // When using viewports it is recommended that your default value for ImGuiCol_WindowBg is opaque (Alpha=1.0) so transition to a viewport won't be noticeable. ++ ImGuiConfigFlags_ViewportsEnable = 1 << 10, // Viewport enable flags (require both ImGuiBackendFlags_PlatformHasViewports + ImGuiBackendFlags_RendererHasViewports set by the respective backends) ++ ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 14, // [BETA: Don't use] FIXME-DPI: Reposition and resize imgui windows when the DpiScale of a viewport changed (mostly useful for the main viewport hosting other window). Note that resizing the main window itself is up to your application. ++ ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 15, // [BETA: Don't use] FIXME-DPI: Request bitmap-scaled fonts to match DpiScale. This is a very low-quality workaround. The correct way to handle DPI is _currently_ to replace the atlas and/or fonts in the Platform_OnChangedViewport callback, but this is all early work in progress. ++ + // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui) + ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. + ImGuiConfigFlags_IsTouchScreen = 1 << 21, // Application is using a touch screen instead of a mouse. +@@ -1614,6 +1685,11 @@ enum ImGuiBackendFlags_ + ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. + ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). + ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. ++ ++ // [BETA] Viewports ++ ImGuiBackendFlags_PlatformHasViewports = 1 << 10, // Backend Platform supports multiple viewports. ++ ImGuiBackendFlags_HasMouseHoveredViewport=1 << 11, // Backend Platform supports calling io.AddMouseViewportEvent() with the viewport under the mouse. IF POSSIBLE, ignore viewports with the ImGuiViewportFlags_NoInputs flag (Win32 backend, GLFW 3.30+ backend can do this, SDL backend cannot). If this cannot be done, Dear ImGui needs to use a flawed heuristic to find the viewport under. ++ ImGuiBackendFlags_RendererHasViewports = 1 << 12, // Backend Renderer supports multiple viewports. + }; + + // Enumeration for PushStyleColor() / PopStyleColor() +@@ -1659,6 +1735,8 @@ enum ImGuiCol_ + ImGuiCol_TabDimmed, // Tab background, when tab-bar is unfocused & tab is unselected + ImGuiCol_TabDimmedSelected, // Tab background, when tab-bar is unfocused & tab is selected + ImGuiCol_TabDimmedSelectedOverline,//..horizontal overline, when tab-bar is unfocused & tab is selected ++ ImGuiCol_DockingPreview, // Preview overlay color when about to docking something ++ ImGuiCol_DockingEmptyBg, // Background color for empty node (e.g. CentralNode with no window docked into it) + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, +@@ -1728,6 +1806,7 @@ enum ImGuiStyleVar_ + ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize + ImGuiStyleVar_SeparatorTextAlign, // ImVec2 SeparatorTextAlign + ImGuiStyleVar_SeparatorTextPadding, // ImVec2 SeparatorTextPadding ++ ImGuiStyleVar_DockingSeparatorSize, // float DockingSeparatorSize + ImGuiStyleVar_COUNT + }; + +@@ -2174,6 +2253,7 @@ struct ImGuiStyle + ImVec2 SeparatorTextPadding; // Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. + ImVec2 DisplayWindowPadding; // Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen. + ImVec2 DisplaySafeAreaPadding; // Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured). ++ float DockingSeparatorSize; // Thickness of resizing border between docked windows + float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). +@@ -2238,6 +2318,18 @@ struct ImGuiIO + ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. + ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale. + ++ // Docking options (when ImGuiConfigFlags_DockingEnable is set) ++ bool ConfigDockingNoSplit; // = false // Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars. ++ bool ConfigDockingWithShift; // = false // Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space) ++ bool ConfigDockingAlwaysTabBar; // = false // [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node. ++ bool ConfigDockingTransparentPayload;// = false // [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge. ++ ++ // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) ++ bool ConfigViewportsNoAutoMerge; // = false; // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags_NoAutoMerge on individual viewport. ++ bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it. ++ bool ConfigViewportsNoDecoration; // = true // Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size). ++ bool ConfigViewportsNoDefaultParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform backend to setup a parent/child relationship between the OS windows (some backend may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows. ++ + // Miscellaneous options + // (you can visualize and interact with all options in 'Demo->Configuration') + bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. +@@ -2333,6 +2425,7 @@ struct ImGuiIO + IMGUI_API void AddMouseButtonEvent(int button, bool down); // Queue a mouse button change + IMGUI_API void AddMouseWheelEvent(float wheel_x, float wheel_y); // Queue a mouse wheel update. wheel_y<0: scroll down, wheel_y>0: scroll up, wheel_x<0: scroll right, wheel_x>0: scroll left. + IMGUI_API void AddMouseSourceEvent(ImGuiMouseSource source); // Queue a mouse source change (Mouse/TouchScreen/Pen) ++ IMGUI_API void AddMouseViewportEvent(ImGuiID id); // Queue a mouse hovered viewport. Requires backend to set ImGuiBackendFlags_HasMouseHoveredViewport to call this (for multi-viewport support). + IMGUI_API void AddFocusEvent(bool focused); // Queue a gain/loss of focus for the application (generally based on OS/platform focus of your window) + IMGUI_API void AddInputCharacter(unsigned int c); // Queue a new character input + IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue a new character input from a UTF-16 character, it can be a surrogate +@@ -2381,6 +2474,7 @@ struct ImGuiIO + float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold SHIFT to turn vertical scroll into horizontal scroll. + float MouseWheelH; // Mouse wheel Horizontal. >0 scrolls Left, <0 scrolls Right. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends. + ImGuiMouseSource MouseSource; // Mouse actual input peripheral (Mouse/TouchScreen/Pen). ++ ImGuiID MouseHoveredViewport; // (Optional) Modify using io.AddMouseViewportEvent(). With multi-viewports: viewport the OS mouse is hovering. If possible _IGNORING_ viewports with the ImGuiViewportFlags_NoInputs flag is much better (few backends can handle that). Set io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport if you can provide this info. If you don't imgui will infer the value using the rectangles and last focused time of the viewports it knows about (ignoring other OS windows). + bool KeyCtrl; // Keyboard modifier down: Control + bool KeyShift; // Keyboard modifier down: Shift + bool KeyAlt; // Keyboard modifier down: Alt +@@ -2404,6 +2498,7 @@ struct ImGuiIO + bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a ctrl-click that spawned a simulated right click + float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) + float MouseDownDurationPrev[5]; // Previous time the mouse button has been down ++ ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point + float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) + float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. + bool AppFocusLost; // Only modify via AddFocusEvent() +@@ -2489,6 +2584,28 @@ struct ImGuiSizeCallbackData + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. + }; + ++// [ALPHA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. ++// Important: the content of this class is still highly WIP and likely to change and be refactored ++// before we stabilize Docking features. Please be mindful if using this. ++// Provide hints: ++// - To the platform backend via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) ++// - To the platform backend for OS level parent/child relationships of viewport. ++// - To the docking system for various options and filtering. ++struct ImGuiWindowClass ++{ ++ ImGuiID ClassId; // User data. 0 = Default class (unclassed). Windows of different classes cannot be docked with each others. ++ ImGuiID ParentViewportId; // Hint for the platform backend. -1: use default. 0: request platform backend to not parent the platform. != 0: request platform backend to create a parent<>child relationship between the platform windows. Not conforming backends are free to e.g. parent every viewport to the main viewport or not. ++ ImGuiID FocusRouteParentWindowId; // ID of parent window for shortcut focus route evaluation, e.g. Shortcut() call from Parent Window will succeed when this window is focused. ++ ImGuiViewportFlags ViewportFlagsOverrideSet; // Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. ++ ImGuiViewportFlags ViewportFlagsOverrideClear; // Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. ++ ImGuiTabItemFlags TabItemFlagsOverrideSet; // [EXPERIMENTAL] TabItem flags to set when a window of this class gets submitted into a dock node tab bar. May use with ImGuiTabItemFlags_Leading or ImGuiTabItemFlags_Trailing. ++ ImGuiDockNodeFlags DockNodeFlagsOverrideSet; // [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) ++ bool DockingAlwaysTabBar; // Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) ++ bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. // FIXME-DOCK: Move to DockNodeFlags override? ++ ++ ImGuiWindowClass() { memset(this, 0, sizeof(*this)); ParentViewportId = (ImGuiID)-1; DockingAllowUnclassed = true; } ++}; ++ + // Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() + struct ImGuiPayload + { +@@ -3192,7 +3309,7 @@ struct ImDrawList + struct ImDrawData + { + bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. +- int CmdListsCount; // Number of ImDrawList* to render (should always be == CmdLists.size) ++ int CmdListsCount; // Number of ImDrawList* to render + int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size + int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size + ImVector CmdLists; // Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. +@@ -3475,11 +3592,24 @@ enum ImGuiViewportFlags_ + ImGuiViewportFlags_None = 0, + ImGuiViewportFlags_IsPlatformWindow = 1 << 0, // Represent a Platform Window + ImGuiViewportFlags_IsPlatformMonitor = 1 << 1, // Represent a Platform Monitor (unused yet) +- ImGuiViewportFlags_OwnedByApp = 1 << 2, // Platform Window: Is created/managed by the application (rather than a dear imgui backend) ++ ImGuiViewportFlags_OwnedByApp = 1 << 2, // Platform Window: Is created/managed by the user application? (rather than our backend) ++ ImGuiViewportFlags_NoDecoration = 1 << 3, // Platform Window: Disable platform decorations: title bar, borders, etc. (generally set all windows, but if ImGuiConfigFlags_ViewportsDecoration is set we only set this on popups/tooltips) ++ ImGuiViewportFlags_NoTaskBarIcon = 1 << 4, // Platform Window: Disable platform task bar icon (generally set on popups/tooltips, or all windows if ImGuiConfigFlags_ViewportsNoTaskBarIcon is set) ++ ImGuiViewportFlags_NoFocusOnAppearing = 1 << 5, // Platform Window: Don't take focus when created. ++ ImGuiViewportFlags_NoFocusOnClick = 1 << 6, // Platform Window: Don't take focus when clicked on. ++ ImGuiViewportFlags_NoInputs = 1 << 7, // Platform Window: Make mouse pass through so we can drag this window while peaking behind it. ++ ImGuiViewportFlags_NoRendererClear = 1 << 8, // Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). ++ ImGuiViewportFlags_NoAutoMerge = 1 << 9, // Platform Window: Avoid merging this window into another host window. This can only be set via ImGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!). ++ ImGuiViewportFlags_TopMost = 1 << 10, // Platform Window: Display on top (for tooltips only). ++ ImGuiViewportFlags_CanHostOtherWindows = 1 << 11, // Viewport can host multiple imgui windows (secondary viewports are associated to a single window). // FIXME: In practice there's still probably code making the assumption that this is always and only on the MainViewport. Will fix once we add support for "no main viewport". ++ ++ // Output status flags (from Platform) ++ ImGuiViewportFlags_IsMinimized = 1 << 12, // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. ++ ImGuiViewportFlags_IsFocused = 1 << 13, // Platform Window: Window is focused (last call to Platform_GetWindowFocus() returned true) + }; + + // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. +-// - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. ++// - With multi-viewport enabled, we extend this concept to have multiple active viewports. + // - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. + // - About Main Area vs Work Area: + // - Main Area = entire viewport. +@@ -3493,12 +3623,26 @@ struct ImGuiViewport + ImVec2 Size; // Main Area: Size of the viewport. + ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) + ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) ++ float DpiScale; // 1.0f = 96 DPI = No extra scale. ++ ImGuiID ParentViewportId; // (Advanced) 0: no parent. Instruct the platform backend to setup a parent/child relationship between platform windows. ++ ImDrawData* DrawData; // The ImDrawData corresponding to this viewport. Valid after Render() and until the next call to NewFrame(). + + // Platform/Backend Dependent Data +- void* PlatformHandle; // void* to hold higher-level, platform window handle (e.g. HWND, GLFWWindow*, SDL_Window*) +- void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms) ++ // Our design separate the Renderer and Platform backends to facilitate combining default backends with each others. ++ // When our create your own backend for a custom engine, it is possible that both Renderer and Platform will be handled ++ // by the same system and you may not need to use all the UserData/Handle fields. ++ // The library never uses those fields, they are merely storage to facilitate backend implementation. ++ void* RendererUserData; // void* to hold custom data structure for the renderer (e.g. swap chain, framebuffers etc.). generally set by your Renderer_CreateWindow function. ++ void* PlatformUserData; // void* to hold custom data structure for the OS / platform (e.g. windowing info, render context). generally set by your Platform_CreateWindow function. ++ void* PlatformHandle; // void* to hold higher-level, platform window handle (e.g. HWND, GLFWWindow*, SDL_Window*), for FindViewportByPlatformHandle(). ++ void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms), when using an abstraction layer like GLFW or SDL (where PlatformHandle would be a SDL_Window*) ++ bool PlatformWindowCreated; // Platform window has been created (Platform_CreateWindow() has been called). This is false during the first frame where a viewport is being created. ++ bool PlatformRequestMove; // Platform window requested move (e.g. window was moved by the OS / host window manager, authoritative position will be OS window position) ++ bool PlatformRequestResize; // Platform window requested resize (e.g. window was resized by the OS / host window manager, authoritative size will be OS window size) ++ bool PlatformRequestClose; // Platform window requested closure (e.g. window was moved by the OS / host window manager, e.g. pressing ALT-F4) + + ImGuiViewport() { memset(this, 0, sizeof(*this)); } ++ ~ImGuiViewport() { IM_ASSERT(PlatformUserData == NULL && RendererUserData == NULL); } + + // Helpers + ImVec2 GetCenter() const { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } +@@ -3506,7 +3650,53 @@ struct ImGuiViewport + }; + + //----------------------------------------------------------------------------- +-// [SECTION] Platform Dependent Interfaces ++// [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) ++//----------------------------------------------------------------------------- ++ ++// [BETA] (Optional) Multi-Viewport Support! ++// If you are new to Dear ImGui and trying to integrate it into your engine, you can probably ignore this for now. ++// ++// This feature allows you to seamlessly drag Dear ImGui windows outside of your application viewport. ++// This is achieved by creating new Platform/OS windows on the fly, and rendering into them. ++// Dear ImGui manages the viewport structures, and the backend create and maintain one Platform/OS window for each of those viewports. ++// ++// See Recap: https://github.com/ocornut/imgui/wiki/Multi-Viewports ++// See Glossary https://github.com/ocornut/imgui/wiki/Glossary for details about some of the terminology. ++// ++// About the coordinates system: ++// - When multi-viewports are enabled, all Dear ImGui coordinates become absolute coordinates (same as OS coordinates!) ++// - So e.g. ImGui::SetNextWindowPos(ImVec2(0,0)) will position a window relative to your primary monitor! ++// - If you want to position windows relative to your main application viewport, use ImGui::GetMainViewport()->Pos as a base position. ++// ++// Steps to use multi-viewports in your application, when using a default backend from the examples/ folder: ++// - Application: Enable feature with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. ++// - Backend: The backend initialization will setup all necessary ImGuiPlatformIO's functions and update monitors info every frame. ++// - Application: In your main loop, call ImGui::UpdatePlatformWindows(), ImGui::RenderPlatformWindowsDefault() after EndFrame() or Render(). ++// - Application: Fix absolute coordinates used in ImGui::SetWindowPos() or ImGui::SetNextWindowPos() calls. ++// ++// Steps to use multi-viewports in your application, when using a custom backend: ++// - Important: THIS IS NOT EASY TO DO and comes with many subtleties not described here! ++// It's also an experimental feature, so some of the requirements may evolve. ++// Consider using default backends if you can. Either way, carefully follow and refer to examples/ backends for details. ++// - Application: Enable feature with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. ++// - Backend: Hook ImGuiPlatformIO's Platform_* and Renderer_* callbacks (see below). ++// Set 'io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports' and 'io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports'. ++// Update ImGuiPlatformIO's Monitors list every frame. ++// Update MousePos every frame, in absolute coordinates. ++// - Application: In your main loop, call ImGui::UpdatePlatformWindows(), ImGui::RenderPlatformWindowsDefault() after EndFrame() or Render(). ++// You may skip calling RenderPlatformWindowsDefault() if its API is not convenient for your needs. Read comments below. ++// - Application: Fix absolute coordinates used in ImGui::SetWindowPos() or ImGui::SetNextWindowPos() calls. ++// ++// About ImGui::RenderPlatformWindowsDefault(): ++// - This function is a mostly a _helper_ for the common-most cases, and to facilitate using default backends. ++// - You can check its simple source code to understand what it does. ++// It basically iterates secondary viewports and call 4 functions that are setup in ImGuiPlatformIO, if available: ++// Platform_RenderWindow(), Renderer_RenderWindow(), Platform_SwapBuffers(), Renderer_SwapBuffers() ++// Those functions pointers exists only for the benefit of RenderPlatformWindowsDefault(). ++// - If you have very specific rendering needs (e.g. flipping multiple swap-chain simultaneously, unusual sync/threading issues, etc.), ++// you may be tempted to ignore RenderPlatformWindowsDefault() and write customized code to perform your renderingg. ++// You may decide to setup the platform_io's *RenderWindow and *SwapBuffers pointers and call your functions through those pointers, ++// or you may decide to never setup those pointers and call your code directly. They are a convenience, not an obligatory interface. + //----------------------------------------------------------------------------- + + // Access via ImGui::GetPlatformIO() +@@ -3515,7 +3705,7 @@ struct ImGuiPlatformIO + IMGUI_API ImGuiPlatformIO(); + + //------------------------------------------------------------------ +- // Input - Interface with OS/backends ++ // Input - Interface with OS/backends (basic) + //------------------------------------------------------------------ + + // Optional: Access OS clipboard +@@ -3538,6 +3728,74 @@ struct ImGuiPlatformIO + // Optional: Platform locale + // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point + ImWchar Platform_LocaleDecimalPoint; // '.' ++ ++ //------------------------------------------------------------------ ++ // Input - Interface with OS/backends (Multi-Viewport support!) ++ //------------------------------------------------------------------ ++ ++ // For reference, the second column shows which function are generally calling the Platform Functions: ++ // N = ImGui::NewFrame() ~ beginning of the dear imgui frame: read info from platform/OS windows (latest size/position) ++ // F = ImGui::Begin(), ImGui::EndFrame() ~ during the dear imgui frame ++ // U = ImGui::UpdatePlatformWindows() ~ after the dear imgui frame: create and update all platform/OS windows ++ // R = ImGui::RenderPlatformWindowsDefault() ~ render ++ // D = ImGui::DestroyPlatformWindows() ~ shutdown ++ // The general idea is that NewFrame() we will read the current Platform/OS state, and UpdatePlatformWindows() will write to it. ++ ++ // The handlers are designed so we can mix and match two imgui_impl_xxxx files, one Platform backend and one Renderer backend. ++ // Custom engine backends will often provide both Platform and Renderer interfaces together and so may not need to use all functions. ++ // Platform functions are typically called _before_ their Renderer counterpart, apart from Destroy which are called the other way. ++ ++ // Platform Backend functions (e.g. Win32, GLFW, SDL) ------------------- Called by ----- ++ void (*Platform_CreateWindow)(ImGuiViewport* vp); // . . U . . // Create a new platform window for the given viewport ++ void (*Platform_DestroyWindow)(ImGuiViewport* vp); // N . U . D // ++ void (*Platform_ShowWindow)(ImGuiViewport* vp); // . . U . . // Newly created windows are initially hidden so SetWindowPos/Size/Title can be called on them before showing the window ++ void (*Platform_SetWindowPos)(ImGuiViewport* vp, ImVec2 pos); // . . U . . // Set platform window position (given the upper-left corner of client area) ++ ImVec2 (*Platform_GetWindowPos)(ImGuiViewport* vp); // N . . . . // ++ void (*Platform_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Set platform window client area size (ignoring OS decorations such as OS title bar etc.) ++ ImVec2 (*Platform_GetWindowSize)(ImGuiViewport* vp); // N . . . . // Get platform window client area size ++ void (*Platform_SetWindowFocus)(ImGuiViewport* vp); // N . . . . // Move window to front and set input focus ++ bool (*Platform_GetWindowFocus)(ImGuiViewport* vp); // . . U . . // ++ bool (*Platform_GetWindowMinimized)(ImGuiViewport* vp); // N . . . . // Get platform window minimized state. When minimized, we generally won't attempt to get/set size and contents will be culled more easily ++ void (*Platform_SetWindowTitle)(ImGuiViewport* vp, const char* str); // . . U . . // Set platform window title (given an UTF-8 string) ++ void (*Platform_SetWindowAlpha)(ImGuiViewport* vp, float alpha); // . . U . . // (Optional) Setup global transparency (not per-pixel transparency) ++ void (*Platform_UpdateWindow)(ImGuiViewport* vp); // . . U . . // (Optional) Called by UpdatePlatformWindows(). Optional hook to allow the platform backend from doing general book-keeping every frame. ++ void (*Platform_RenderWindow)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Main rendering (platform side! This is often unused, or just setting a "current" context for OpenGL bindings). 'render_arg' is the value passed to RenderPlatformWindowsDefault(). ++ void (*Platform_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Call Present/SwapBuffers (platform side! This is often unused!). 'render_arg' is the value passed to RenderPlatformWindowsDefault(). ++ float (*Platform_GetWindowDpiScale)(ImGuiViewport* vp); // N . . . . // (Optional) [BETA] FIXME-DPI: DPI handling: Return DPI scale for this viewport. 1.0f = 96 DPI. ++ void (*Platform_OnChangedViewport)(ImGuiViewport* vp); // . F . . . // (Optional) [BETA] FIXME-DPI: DPI handling: Called during Begin() every time the viewport we are outputting into changes, so backend has a chance to swap fonts to adjust style. ++ ImVec4 (*Platform_GetWindowWorkAreaInsets)(ImGuiViewport* vp); // N . . . . // (Optional) [BETA] Get initial work area inset for the viewport (won't be covered by main menu bar, dockspace over viewport etc.). Default to (0,0),(0,0). 'safeAreaInsets' in iOS land, 'DisplayCutout' in Android land. ++ int (*Platform_CreateVkSurface)(ImGuiViewport* vp, ImU64 vk_inst, const void* vk_allocators, ImU64* out_vk_surface); // (Optional) For a Vulkan Renderer to call into Platform code (since the surface creation needs to tie them both). ++ ++ // Renderer Backend functions (e.g. DirectX, OpenGL, Vulkan) ------------ Called by ----- ++ void (*Renderer_CreateWindow)(ImGuiViewport* vp); // . . U . . // Create swap chain, frame buffers etc. (called after Platform_CreateWindow) ++ void (*Renderer_DestroyWindow)(ImGuiViewport* vp); // N . U . D // Destroy swap chain, frame buffers etc. (called before Platform_DestroyWindow) ++ void (*Renderer_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Resize swap chain, frame buffers etc. (called after Platform_SetWindowSize) ++ void (*Renderer_RenderWindow)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Clear framebuffer, setup render target, then render the viewport->DrawData. 'render_arg' is the value passed to RenderPlatformWindowsDefault(). ++ void (*Renderer_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Call Present/SwapBuffers. 'render_arg' is the value passed to RenderPlatformWindowsDefault(). ++ ++ // (Optional) Monitor list ++ // - Updated by: app/backend. Update every frame to dynamically support changing monitor or DPI configuration. ++ // - Used by: dear imgui to query DPI info, clamp popups/tooltips within same monitor and not have them straddle monitors. ++ ImVector Monitors; ++ ++ //------------------------------------------------------------------ ++ // Output - List of viewports to render into platform windows ++ //------------------------------------------------------------------ ++ ++ // Viewports list (the list is updated by calling ImGui::EndFrame or ImGui::Render) ++ // (in the future we will attempt to organize this feature to remove the need for a "main viewport") ++ ImVector Viewports; // Main viewports, followed by all secondary viewports. ++}; ++ ++// (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI. ++// We use this information for multiple DPI support + clamping the position of popups and tooltips so they don't straddle multiple monitors. ++struct ImGuiPlatformMonitor ++{ ++ ImVec2 MainPos, MainSize; // Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right) ++ ImVec2 WorkPos, WorkSize; // Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize. ++ float DpiScale; // 1.0f = 96 DPI ++ void* PlatformHandle; // Backend dependant data (e.g. HMONITOR, GLFWmonitor*, SDL Display Index, NSScreen*) ++ ImGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = ImVec2(0, 0); DpiScale = 1.0f; PlatformHandle = NULL; } + }; + + // (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. +diff --git a/imgui_demo.cpp b/imgui_demo.cpp +index 8df1755f..3048b692 100644 +--- a/imgui_demo.cpp ++++ b/imgui_demo.cpp +@@ -94,6 +94,7 @@ Index of this file: + // [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() + // [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() + // [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() ++// [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() + // [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() + // [SECTION] Example App: Assets Browser / ShowExampleAppAssetsBrowser() + +@@ -207,6 +208,7 @@ static void ShowExampleAppMainMenuBar(); + static void ShowExampleAppAssetsBrowser(bool* p_open); + static void ShowExampleAppConsole(bool* p_open); + static void ShowExampleAppCustomRendering(bool* p_open); ++static void ShowExampleAppDockSpace(bool* p_open); + static void ShowExampleAppDocuments(bool* p_open); + static void ShowExampleAppLog(bool* p_open); + static void ShowExampleAppLayout(bool* p_open); +@@ -248,6 +250,16 @@ static void HelpMarker(const char* desc) + } + } + ++static void ShowDockingDisabledMessage() ++{ ++ ImGuiIO& io = ImGui::GetIO(); ++ ImGui::Text("ERROR: Docking is not enabled! See Demo > Configuration."); ++ ImGui::Text("Set io.ConfigFlags |= ImGuiConfigFlags_DockingEnable in your code, or "); ++ ImGui::SameLine(0.0f, 0.0f); ++ if (ImGui::SmallButton("click here")) ++ io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; ++} ++ + // Helper to wire demo markers located in code to an interactive browser + typedef void (*ImGuiDemoMarkerCallback)(const char* file, int line, const char* section, void* user_data); + extern ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback; +@@ -352,6 +364,7 @@ struct ImGuiDemoWindowData + bool ShowAppConsole = false; + bool ShowAppCustomRendering = false; + bool ShowAppDocuments = false; ++ bool ShowAppDockSpace = false; + bool ShowAppLog = false; + bool ShowAppLayout = false; + bool ShowAppPropertyEditor = false; +@@ -390,7 +403,8 @@ void ImGui::ShowDemoWindow(bool* p_open) + + // Examples Apps (accessible from the "Examples" menu) + if (demo_data.ShowMainMenuBar) { ShowExampleAppMainMenuBar(); } +- if (demo_data.ShowAppDocuments) { ShowExampleAppDocuments(&demo_data.ShowAppDocuments); } ++ if (demo_data.ShowAppDockSpace) { ShowExampleAppDockSpace(&demo_data.ShowAppDockSpace); } // Important: Process the Docking app first, as explicit DockSpace() nodes needs to be submitted early (read comments near the DockSpace function) ++ if (demo_data.ShowAppDocuments) { ShowExampleAppDocuments(&demo_data.ShowAppDocuments); } // ...process the Document app next, as it may also use a DockSpace() + if (demo_data.ShowAppAssetsBrowser) { ShowExampleAppAssetsBrowser(&demo_data.ShowAppAssetsBrowser); } + if (demo_data.ShowAppConsole) { ShowExampleAppConsole(&demo_data.ShowAppConsole); } + if (demo_data.ShowAppCustomRendering) { ShowExampleAppCustomRendering(&demo_data.ShowAppCustomRendering); } +@@ -427,6 +441,7 @@ void ImGui::ShowDemoWindow(bool* p_open) + static bool no_nav = false; + static bool no_background = false; + static bool no_bring_to_front = false; ++ static bool no_docking = false; + static bool unsaved_document = false; + + ImGuiWindowFlags window_flags = 0; +@@ -439,6 +454,7 @@ void ImGui::ShowDemoWindow(bool* p_open) + if (no_nav) window_flags |= ImGuiWindowFlags_NoNav; + if (no_background) window_flags |= ImGuiWindowFlags_NoBackground; + if (no_bring_to_front) window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus; ++ if (no_docking) window_flags |= ImGuiWindowFlags_NoDocking; + if (unsaved_document) window_flags |= ImGuiWindowFlags_UnsavedDocument; + if (no_close) p_open = NULL; // Don't pass our bool* to Begin + +@@ -529,6 +545,44 @@ void ImGui::ShowDemoWindow(bool* p_open) + ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor); + ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something)."); + ++ ImGui::SeparatorText("Docking"); ++ ImGui::CheckboxFlags("io.ConfigFlags: DockingEnable", &io.ConfigFlags, ImGuiConfigFlags_DockingEnable); ++ ImGui::SameLine(); ++ if (io.ConfigDockingWithShift) ++ HelpMarker("Drag from window title bar or their tab to dock/undock. Hold SHIFT to enable docking.\n\nDrag from window menu button (upper-left button) to undock an entire node (all windows)."); ++ else ++ HelpMarker("Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking.\n\nDrag from window menu button (upper-left button) to undock an entire node (all windows)."); ++ if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) ++ { ++ ImGui::Indent(); ++ ImGui::Checkbox("io.ConfigDockingNoSplit", &io.ConfigDockingNoSplit); ++ ImGui::SameLine(); HelpMarker("Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars."); ++ ImGui::Checkbox("io.ConfigDockingWithShift", &io.ConfigDockingWithShift); ++ ImGui::SameLine(); HelpMarker("Enable docking when holding Shift only (allow to drop in wider space, reduce visual noise)"); ++ ImGui::Checkbox("io.ConfigDockingAlwaysTabBar", &io.ConfigDockingAlwaysTabBar); ++ ImGui::SameLine(); HelpMarker("Create a docking node and tab-bar on single floating windows."); ++ ImGui::Checkbox("io.ConfigDockingTransparentPayload", &io.ConfigDockingTransparentPayload); ++ ImGui::SameLine(); HelpMarker("Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge."); ++ ImGui::Unindent(); ++ } ++ ++ ImGui::SeparatorText("Multi-viewports"); ++ ImGui::CheckboxFlags("io.ConfigFlags: ViewportsEnable", &io.ConfigFlags, ImGuiConfigFlags_ViewportsEnable); ++ ImGui::SameLine(); HelpMarker("[beta] Enable beta multi-viewports support. See ImGuiPlatformIO for details."); ++ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ++ { ++ ImGui::Indent(); ++ ImGui::Checkbox("io.ConfigViewportsNoAutoMerge", &io.ConfigViewportsNoAutoMerge); ++ ImGui::SameLine(); HelpMarker("Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it."); ++ ImGui::Checkbox("io.ConfigViewportsNoTaskBarIcon", &io.ConfigViewportsNoTaskBarIcon); ++ ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform backends won't refresh the task bar icon state right away)."); ++ ImGui::Checkbox("io.ConfigViewportsNoDecoration", &io.ConfigViewportsNoDecoration); ++ ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform backends won't refresh the decoration right away)."); ++ ImGui::Checkbox("io.ConfigViewportsNoDefaultParent", &io.ConfigViewportsNoDefaultParent); ++ ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform backends won't refresh the parenting right away)."); ++ ImGui::Unindent(); ++ } ++ + ImGui::SeparatorText("Widgets"); + ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink); + ImGui::SameLine(); HelpMarker("Enable blinking cursor (optional as some users consider it to be distracting)."); +@@ -590,12 +644,16 @@ void ImGui::ShowDemoWindow(bool* p_open) + "Those flags are set by the backends (imgui_impl_xxx files) to specify their capabilities.\n" + "Here we expose them as read-only fields to avoid breaking interactions with your backend."); + ++ // Make a local copy to avoid modifying actual backend flags. + // FIXME: Maybe we need a BeginReadonly() equivalent to keep label bright? + ImGui::BeginDisabled(); +- ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", &io.BackendFlags, ImGuiBackendFlags_HasGamepad); +- ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &io.BackendFlags, ImGuiBackendFlags_HasMouseCursors); +- ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", &io.BackendFlags, ImGuiBackendFlags_HasSetMousePos); +- ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &io.BackendFlags, ImGuiBackendFlags_RendererHasVtxOffset); ++ ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", &io.BackendFlags, ImGuiBackendFlags_HasGamepad); ++ ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &io.BackendFlags, ImGuiBackendFlags_HasMouseCursors); ++ ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", &io.BackendFlags, ImGuiBackendFlags_HasSetMousePos); ++ ImGui::CheckboxFlags("io.BackendFlags: PlatformHasViewports", &io.BackendFlags, ImGuiBackendFlags_PlatformHasViewports); ++ ImGui::CheckboxFlags("io.BackendFlags: HasMouseHoveredViewport",&io.BackendFlags, ImGuiBackendFlags_HasMouseHoveredViewport); ++ ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &io.BackendFlags, ImGuiBackendFlags_RendererHasVtxOffset); ++ ImGui::CheckboxFlags("io.BackendFlags: RendererHasViewports", &io.BackendFlags, ImGuiBackendFlags_RendererHasViewports); + ImGui::EndDisabled(); + + ImGui::TreePop(); +@@ -647,6 +705,7 @@ void ImGui::ShowDemoWindow(bool* p_open) + ImGui::TableNextColumn(); ImGui::Checkbox("No nav", &no_nav); + ImGui::TableNextColumn(); ImGui::Checkbox("No background", &no_background); + ImGui::TableNextColumn(); ImGui::Checkbox("No bring to front", &no_bring_to_front); ++ ImGui::TableNextColumn(); ImGui::Checkbox("No docking", &no_docking); + ImGui::TableNextColumn(); ImGui::Checkbox("Unsaved document", &unsaved_document); + ImGui::EndTable(); + } +@@ -689,6 +748,7 @@ static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data) + ImGui::MenuItem("Console", NULL, &demo_data->ShowAppConsole); + ImGui::MenuItem("Custom rendering", NULL, &demo_data->ShowAppCustomRendering); + ImGui::MenuItem("Documents", NULL, &demo_data->ShowAppDocuments); ++ ImGui::MenuItem("Dockspace", NULL, &demo_data->ShowAppDockSpace); + ImGui::MenuItem("Log", NULL, &demo_data->ShowAppLog); + ImGui::MenuItem("Property editor", NULL, &demo_data->ShowAppPropertyEditor); + ImGui::MenuItem("Simple layout", NULL, &demo_data->ShowAppLayout); +@@ -2814,18 +2874,24 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) + "IsWindowFocused() = %d\n" + "IsWindowFocused(_ChildWindows) = %d\n" + "IsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\n" ++ "IsWindowFocused(_ChildWindows|_DockHierarchy) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" ++ "IsWindowFocused(_ChildWindows|_RootWindow|_DockHierarchy) = %d\n" + "IsWindowFocused(_RootWindow) = %d\n" + "IsWindowFocused(_RootWindow|_NoPopupHierarchy) = %d\n" ++ "IsWindowFocused(_RootWindow|_DockHierarchy) = %d\n" + "IsWindowFocused(_AnyWindow) = %d\n", + ImGui::IsWindowFocused(), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_NoPopupHierarchy), ++ ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_DockHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), ++ ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_DockHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), ++ ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_DockHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)); + + // Testing IsWindowHovered() function with its various flags. +@@ -2835,10 +2901,13 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) + "IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" + "IsWindowHovered(_ChildWindows) = %d\n" + "IsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\n" ++ "IsWindowHovered(_ChildWindows|_DockHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" ++ "IsWindowHovered(_ChildWindows|_RootWindow|_DockHierarchy) = %d\n" + "IsWindowHovered(_RootWindow) = %d\n" + "IsWindowHovered(_RootWindow|_NoPopupHierarchy) = %d\n" ++ "IsWindowHovered(_RootWindow|_DockHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\n" + "IsWindowHovered(_AnyWindow) = %d\n" + "IsWindowHovered(_Stationary) = %d\n", +@@ -2847,10 +2916,13 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy), ++ ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_DockHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), ++ ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_DockHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), ++ ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_DockHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_Stationary)); +@@ -2863,10 +2935,13 @@ static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data) + + // Calling IsItemHovered() after begin returns the hovered status of the title bar. + // This is useful in particular if you want to create a context menu associated to the title bar of a window. ++ // This will also work when docked into a Tab (the Tab replace the Title Bar and guarantee the same properties). + static bool test_window = false; + ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window); + if (test_window) + { ++ // FIXME-DOCK: This window cannot be docked within the ImGui Demo window, this will cause a feedback loop and get them stuck. ++ // Could we fix this through an ImGuiWindowClass feature? Or an API call to tag our parent as "don't skip items"? + ImGui::Begin("Title bar Hovered/Active tests", &test_window); + if (ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered() + { +@@ -3851,7 +3926,7 @@ static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data) + ImGui::TableNextColumn(); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); +- ImGui::InputText("###NoLabel", (char*)(void*)item_category, strlen(item_category), ImGuiInputTextFlags_ReadOnly); ++ ImGui::InputText("###NoLabel", const_cast(item_category), strlen(item_category), ImGuiInputTextFlags_ReadOnly); + ImGui::PopStyleVar(); + } + +@@ -7746,6 +7821,12 @@ void ImGui::ShowAboutWindow(bool* p_open) + #ifdef __EMSCRIPTEN__ + ImGui::Text("define: __EMSCRIPTEN__"); + ImGui::Text("Emscripten: %d.%d.%d", __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__); ++#endif ++#ifdef IMGUI_HAS_VIEWPORT ++ ImGui::Text("define: IMGUI_HAS_VIEWPORT"); ++#endif ++#ifdef IMGUI_HAS_DOCK ++ ImGui::Text("define: IMGUI_HAS_DOCK"); + #endif + ImGui::Separator(); + ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL"); +@@ -7757,7 +7838,19 @@ void ImGui::ShowAboutWindow(bool* p_open) + if (io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard) ImGui::Text(" NavNoCaptureKeyboard"); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) ImGui::Text(" NoMouse"); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) ImGui::Text(" NoMouseCursorChange"); ++ if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) ImGui::Text(" DockingEnable"); ++ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ImGui::Text(" ViewportsEnable"); ++ if (io.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) ImGui::Text(" DpiEnableScaleViewports"); ++ if (io.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ImGui::Text(" DpiEnableScaleFonts"); + if (io.MouseDrawCursor) ImGui::Text("io.MouseDrawCursor"); ++ if (io.ConfigViewportsNoAutoMerge) ImGui::Text("io.ConfigViewportsNoAutoMerge"); ++ if (io.ConfigViewportsNoTaskBarIcon) ImGui::Text("io.ConfigViewportsNoTaskBarIcon"); ++ if (io.ConfigViewportsNoDecoration) ImGui::Text("io.ConfigViewportsNoDecoration"); ++ if (io.ConfigViewportsNoDefaultParent) ImGui::Text("io.ConfigViewportsNoDefaultParent"); ++ if (io.ConfigDockingNoSplit) ImGui::Text("io.ConfigDockingNoSplit"); ++ if (io.ConfigDockingWithShift) ImGui::Text("io.ConfigDockingWithShift"); ++ if (io.ConfigDockingAlwaysTabBar) ImGui::Text("io.ConfigDockingAlwaysTabBar"); ++ if (io.ConfigDockingTransparentPayload) ImGui::Text("io.ConfigDockingTransparentPayload"); + if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors"); + if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); + if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges"); +@@ -7767,7 +7860,10 @@ void ImGui::ShowAboutWindow(bool* p_open) + if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); + if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); + if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos"); ++ if (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) ImGui::Text(" PlatformHasViewports"); ++ if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)ImGui::Text(" HasMouseHoveredViewport"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset"); ++ if (io.BackendFlags & ImGuiBackendFlags_RendererHasViewports) ImGui::Text(" RendererHasViewports"); + ImGui::Separator(); + ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight); + ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); +@@ -7943,6 +8039,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) + ImGui::SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f"); + ImGui::SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); + ++ ImGui::SeparatorText("Docking"); ++ ImGui::SliderFloat("DockingSplitterSize", &style.DockingSeparatorSize, 0.0f, 12.0f, "%.0f"); ++ + ImGui::SeparatorText("Tooltips"); + for (int n = 0; n < 2; n++) + if (ImGui::TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav")) +@@ -9189,6 +9288,8 @@ static void ShowExampleAppConstrainedResize(bool* p_open) + else + { + ImGui::Text("(Hold SHIFT to display a dummy viewport)"); ++ if (ImGui::IsWindowDocked()) ++ ImGui::Text("Warning: Sizing Constraints won't work if the window is docked!"); + if (ImGui::Button("Set 200x200")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine(); + if (ImGui::Button("Set 500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine(); + if (ImGui::Button("Set 800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); } +@@ -9215,7 +9316,7 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) + { + static int location = 0; + ImGuiIO& io = ImGui::GetIO(); +- ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav; ++ ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav; + if (location >= 0) + { + const float PAD = 10.0f; +@@ -9228,6 +9329,7 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) + window_pos_pivot.x = (location & 1) ? 1.0f : 0.0f; + window_pos_pivot.y = (location & 2) ? 1.0f : 0.0f; + ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); ++ ImGui::SetNextWindowViewport(viewport->ID); + window_flags |= ImGuiWindowFlags_NoMove; + } + else if (location == -2) +@@ -9647,6 +9749,134 @@ static void ShowExampleAppCustomRendering(bool* p_open) + ImGui::End(); + } + ++//----------------------------------------------------------------------------- ++// [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() ++//----------------------------------------------------------------------------- ++ ++// Demonstrate using DockSpace() to create an explicit docking node within an existing window. ++// Note: You can use most Docking facilities without calling any API. You DO NOT need to call DockSpace() to use Docking! ++// - Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking. ++// - Drag from window menu button (upper-left button) to undock an entire node (all windows). ++// - When io.ConfigDockingWithShift == true, you instead need to hold SHIFT to enable docking. ++// About dockspaces: ++// - Use DockSpace() to create an explicit dock node _within_ an existing window. ++// - Use DockSpaceOverViewport() to create an explicit dock node covering the screen or a specific viewport. ++// This is often used with ImGuiDockNodeFlags_PassthruCentralNode. ++// - Important: Dockspaces need to be submitted _before_ any window they can host. Submit it early in your frame! (*) ++// - Important: Dockspaces need to be kept alive if hidden, otherwise windows docked into it will be undocked. ++// e.g. if you have multiple tabs with a dockspace inside each tab: submit the non-visible dockspaces with ImGuiDockNodeFlags_KeepAliveOnly. ++// (*) because of this constraint, the implicit \"Debug\" window can not be docked into an explicit DockSpace() node, ++// because that window is submitted as part of the part of the NewFrame() call. An easy workaround is that you can create ++// your own implicit "Debug##2" window after calling DockSpace() and leave it in the window stack for anyone to use. ++void ShowExampleAppDockSpace(bool* p_open) ++{ ++ // READ THIS !!! ++ // TL;DR; this demo is more complicated than what most users you would normally use. ++ // If we remove all options we are showcasing, this demo would become: ++ // void ShowExampleAppDockSpace() ++ // { ++ // ImGui::DockSpaceOverViewport(0, ImGui::GetMainViewport()); ++ // } ++ // In most cases you should be able to just call DockSpaceOverViewport() and ignore all the code below! ++ // In this specific demo, we are not using DockSpaceOverViewport() because: ++ // - (1) we allow the host window to be floating/moveable instead of filling the viewport (when opt_fullscreen == false) ++ // - (2) we allow the host window to have padding (when opt_padding == true) ++ // - (3) we expose many flags and need a way to have them visible. ++ // - (4) we have a local menu bar in the host window (vs. you could use BeginMainMenuBar() + DockSpaceOverViewport() ++ // in your code, but we don't here because we allow the window to be floating) ++ ++ static bool opt_fullscreen = true; ++ static bool opt_padding = false; ++ static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; ++ ++ // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, ++ // because it would be confusing to have two docking targets within each others. ++ ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; ++ if (opt_fullscreen) ++ { ++ const ImGuiViewport* viewport = ImGui::GetMainViewport(); ++ ImGui::SetNextWindowPos(viewport->WorkPos); ++ ImGui::SetNextWindowSize(viewport->WorkSize); ++ ImGui::SetNextWindowViewport(viewport->ID); ++ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ++ ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ++ window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; ++ window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; ++ } ++ else ++ { ++ dockspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode; ++ } ++ ++ // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background ++ // and handle the pass-thru hole, so we ask Begin() to not render a background. ++ if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) ++ window_flags |= ImGuiWindowFlags_NoBackground; ++ ++ // Important: note that we proceed even if Begin() returns false (aka window is collapsed). ++ // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, ++ // all active windows docked into it will lose their parent and become undocked. ++ // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise ++ // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. ++ if (!opt_padding) ++ ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ++ ImGui::Begin("DockSpace Demo", p_open, window_flags); ++ if (!opt_padding) ++ ImGui::PopStyleVar(); ++ ++ if (opt_fullscreen) ++ ImGui::PopStyleVar(2); ++ ++ // Submit the DockSpace ++ ImGuiIO& io = ImGui::GetIO(); ++ if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) ++ { ++ ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); ++ ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); ++ } ++ else ++ { ++ ShowDockingDisabledMessage(); ++ } ++ ++ if (ImGui::BeginMenuBar()) ++ { ++ if (ImGui::BeginMenu("Options")) ++ { ++ // Disabling fullscreen would allow the window to be moved to the front of other windows, ++ // which we can't undo at the moment without finer window depth/z control. ++ ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen); ++ ImGui::MenuItem("Padding", NULL, &opt_padding); ++ ImGui::Separator(); ++ ++ if (ImGui::MenuItem("Flag: NoDockingOverCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoDockingOverCentralNode; } ++ if (ImGui::MenuItem("Flag: NoDockingSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingSplit) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoDockingSplit; } ++ if (ImGui::MenuItem("Flag: NoUndocking", "", (dockspace_flags & ImGuiDockNodeFlags_NoUndocking) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoUndocking; } ++ if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoResize; } ++ if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; } ++ if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0, opt_fullscreen)) { dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode; } ++ ImGui::Separator(); ++ ++ if (ImGui::MenuItem("Close", NULL, false, p_open != NULL)) ++ *p_open = false; ++ ImGui::EndMenu(); ++ } ++ HelpMarker( ++ "When docking is enabled, you can ALWAYS dock MOST window into another! Try it now!" "\n" ++ "- Drag from window title bar or their tab to dock/undock." "\n" ++ "- Drag from window menu button (upper-left button) to undock an entire node (all windows)." "\n" ++ "- Hold SHIFT to disable docking (if io.ConfigDockingWithShift == false, default)" "\n" ++ "- Hold SHIFT to enable docking (if io.ConfigDockingWithShift == true)" "\n" ++ "This demo app has nothing to do with enabling docking!" "\n\n" ++ "This demo app only demonstrate the use of ImGui::DockSpace() which allows you to manually create a docking node _within_ another window." "\n\n" ++ "Read comments in ShowExampleAppDockSpace() for more details."); ++ ++ ImGui::EndMenuBar(); ++ } ++ ++ ImGui::End(); ++} ++ + //----------------------------------------------------------------------------- + // [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() + //----------------------------------------------------------------------------- +@@ -9772,11 +10002,25 @@ void ShowExampleAppDocuments(bool* p_open) + static ExampleAppDocuments app; + + // Options ++ enum Target ++ { ++ Target_None, ++ Target_Tab, // Create documents as local tab into a local tab bar ++ Target_DockSpaceAndWindow // Create documents as regular windows, and create an embedded dockspace ++ }; ++ static Target opt_target = Target_Tab; + static bool opt_reorderable = true; + static ImGuiTabBarFlags opt_fitting_flags = ImGuiTabBarFlags_FittingPolicyDefault_; + ++ // When (opt_target == Target_DockSpaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant") ++ // that we emit gets docked into the same spot as the parent window ("Example: Documents"). ++ // This would create a problematic feedback loop because selecting the "Eggplant" tab would make the "Example: Documents" tab ++ // not visible, which in turn would stop submitting the "Eggplant" window. ++ // We avoid this problem by submitting our documents window even if our parent window is not currently visible. ++ // Another solution may be to make the "Example: Documents" window use the ImGuiWindowFlags_NoDocking. ++ + bool window_contents_visible = ImGui::Begin("Example: Documents", p_open, ImGuiWindowFlags_MenuBar); +- if (!window_contents_visible) ++ if (!window_contents_visible && opt_target != Target_DockSpaceAndWindow) + { + ImGui::End(); + return; +@@ -9820,6 +10064,12 @@ void ShowExampleAppDocuments(bool* p_open) + doc.DoForceClose(); + ImGui::PopID(); + } ++ ImGui::PushItemWidth(ImGui::GetFontSize() * 12); ++ ImGui::Combo("Output", (int*)&opt_target, "None\0TabBar+Tabs\0DockSpace+Window\0"); ++ ImGui::PopItemWidth(); ++ bool redock_all = false; ++ if (opt_target == Target_Tab) { ImGui::SameLine(); ImGui::Checkbox("Reorderable Tabs", &opt_reorderable); } ++ if (opt_target == Target_DockSpaceAndWindow) { ImGui::SameLine(); redock_all = ImGui::Button("Redock all"); } + + ImGui::Separator(); + +@@ -9833,7 +10083,8 @@ void ShowExampleAppDocuments(bool* p_open) + // hole for one-frame, both in the tab-bar and in tab-contents when closing a tab/window. + // The rarely used SetTabItemClosed() function is a way to notify of programmatic closure to avoid the one-frame hole. + +- // Submit Tab Bar and Tabs ++ // Tabs ++ if (opt_target == Target_Tab) + { + ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0); + tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline; +@@ -9876,6 +10127,53 @@ void ShowExampleAppDocuments(bool* p_open) + ImGui::EndTabBar(); + } + } ++ else if (opt_target == Target_DockSpaceAndWindow) ++ { ++ if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable) ++ { ++ app.NotifyOfDocumentsClosedElsewhere(); ++ ++ // Create a DockSpace node where any window can be docked ++ ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); ++ ImGui::DockSpace(dockspace_id); ++ ++ // Create Windows ++ for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) ++ { ++ MyDocument* doc = &app.Documents[doc_n]; ++ if (!doc->Open) ++ continue; ++ ++ ImGui::SetNextWindowDockID(dockspace_id, redock_all ? ImGuiCond_Always : ImGuiCond_FirstUseEver); ++ ImGuiWindowFlags window_flags = (doc->Dirty ? ImGuiWindowFlags_UnsavedDocument : 0); ++ bool visible = ImGui::Begin(doc->Name, &doc->Open, window_flags); ++ ++ // Cancel attempt to close when unsaved add to save queue so we can display a popup. ++ if (!doc->Open && doc->Dirty) ++ { ++ doc->Open = true; ++ app.CloseQueue.push_back(doc); ++ } ++ ++ app.DisplayDocContextMenu(doc); ++ if (visible) ++ app.DisplayDocContents(doc); ++ ++ ImGui::End(); ++ } ++ } ++ else ++ { ++ ShowDockingDisabledMessage(); ++ } ++ } ++ ++ // Early out other contents ++ if (!window_contents_visible) ++ { ++ ImGui::End(); ++ return; ++ } + + // Display renaming UI + if (app.RenamingDoc != NULL) +diff --git a/imgui_draw.cpp b/imgui_draw.cpp +index 8084e53c..e4aa544f 100644 +--- a/imgui_draw.cpp ++++ b/imgui_draw.cpp +@@ -218,6 +218,8 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) + colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); ++ colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_HeaderActive] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f); ++ colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); +@@ -281,6 +283,8 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) + colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_TabDimmedSelectedOverline] = colors[ImGuiCol_HeaderActive]; ++ colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_Header] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f); ++ colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); +@@ -345,6 +349,8 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) + colors[ImGuiCol_TabDimmed] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabDimmedSelected] = ImLerp(colors[ImGuiCol_TabSelected], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_TabDimmedSelectedOverline] = ImVec4(0.26f, 0.59f, 1.00f, 1.00f); ++ colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_Header] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f); ++ colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); +@@ -3721,7 +3727,7 @@ bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) + + void ImFont::SetGlyphVisible(ImWchar c, bool visible) + { +- if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)c)) ++ if (ImFontGlyph* glyph = const_cast(FindGlyph((ImWchar)c))) + glyph->Visible = visible ? 1 : 0; + } + +@@ -4214,6 +4220,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im + // - RenderArrow() + // - RenderBullet() + // - RenderCheckMark() ++// - RenderArrowDockMenu() + // - RenderArrowPointingAt() + // - RenderRectFilledRangeH() + // - RenderRectFilledWithHole() +@@ -4288,6 +4295,14 @@ void ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half + } + } + ++// This is less wide than RenderArrow() and we use in dock nodes instead of the regular RenderArrow() to denote a change of functionality, ++// and because the saved space means that the left-most tab label can stay at exactly the same position as the label of a loose window. ++void ImGui::RenderArrowDockMenu(ImDrawList* draw_list, ImVec2 p_min, float sz, ImU32 col) ++{ ++ draw_list->AddRectFilled(p_min + ImVec2(sz * 0.20f, sz * 0.15f), p_min + ImVec2(sz * 0.80f, sz * 0.30f), col); ++ RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.50f, sz * 0.85f), ImVec2(sz * 0.30f, sz * 0.40f), ImGuiDir_Down, col); ++} ++ + static inline float ImAcos01(float x) + { + if (x <= 0.0f) return IM_PI * 0.5f; +@@ -4373,6 +4388,17 @@ void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, + if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomRight); + } + ++ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold) ++{ ++ bool round_l = r_in.Min.x <= r_outer.Min.x + threshold; ++ bool round_r = r_in.Max.x >= r_outer.Max.x - threshold; ++ bool round_t = r_in.Min.y <= r_outer.Min.y + threshold; ++ bool round_b = r_in.Max.y >= r_outer.Max.y - threshold; ++ return ImDrawFlags_RoundCornersNone ++ | ((round_t && round_l) ? ImDrawFlags_RoundCornersTopLeft : 0) | ((round_t && round_r) ? ImDrawFlags_RoundCornersTopRight : 0) ++ | ((round_b && round_l) ? ImDrawFlags_RoundCornersBottomLeft : 0) | ((round_b && round_r) ? ImDrawFlags_RoundCornersBottomRight : 0); ++} ++ + // Helper for ColorPicker4() + // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. + // Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. +diff --git a/imgui_internal.h b/imgui_internal.h +index 9f47ecd2..17651d44 100644 +--- a/imgui_internal.h ++++ b/imgui_internal.h +@@ -93,8 +93,8 @@ Index of this file: + #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access + #elif defined(__GNUC__) + #pragma GCC diagnostic push +-#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +-#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead ++#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind ++#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead + #pragma GCC diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated + #endif + +@@ -132,6 +132,10 @@ struct ImGuiContext; // Main Dear ImGui context + struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine + struct ImGuiDataVarInfo; // Variable information (e.g. to access style variables from an enum) + struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum ++struct ImGuiDockContext; // Docking system context ++struct ImGuiDockRequest; // Docking system dock/undock queued request ++struct ImGuiDockNode; // Docking system node (hold a list of Windows OR two child dock nodes) ++struct ImGuiDockNodeSettings; // Storage for a dock node in .ini file (we preserve those even if the associated dock node isn't active during the session) + struct ImGuiErrorRecoveryState; // Storage of stack sizes for error handling and recovery + struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() + struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box +@@ -163,12 +167,14 @@ struct ImGuiTreeNodeStackData; // Temporary storage for TreeNode(). + struct ImGuiTypingSelectState; // Storage for GetTypingSelectRequest() + struct ImGuiTypingSelectRequest; // Storage for GetTypingSelectRequest() (aimed to be public) + struct ImGuiWindow; // Storage for one window ++struct ImGuiWindowDockStyle; // Storage for window-style data which needs to be stored for docking purpose + struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame, in practice we currently keep it for each window) + struct ImGuiWindowSettings; // Storage for a window .ini settings (we keep one of those even if the actual window wasn't instanced during this session) + + // Enumerations + // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. + enum ImGuiLocKey : int; // -> enum ImGuiLocKey // Enum: a localization entry for translation. ++typedef int ImGuiDataAuthority; // -> enum ImGuiDataAuthority_ // Enum: for storing the source authority (dock node vs window) of a field + typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical + + // Flags +@@ -201,6 +207,9 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer + // [SECTION] Macros + //----------------------------------------------------------------------------- + ++// Internal Drag and Drop payload types. String starting with '_' are reserved for Dear ImGui. ++#define IMGUI_PAYLOAD_TYPE_WINDOW "_IMWINDOW" // Payload == ImGuiWindow* ++ + // Debug Printing Into TTY + // (since IMGUI_VERSION_NUM >= 18729: IMGUI_DEBUG_LOG was reworked into IMGUI_DEBUG_PRINTF (and removed framecount from it). If you were using a #define IMGUI_DEBUG_LOG please rename) + #ifndef IMGUI_DEBUG_PRINTF +@@ -226,6 +235,8 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer + #define IMGUI_DEBUG_LOG_CLIPPER(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventClipper) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) + #define IMGUI_DEBUG_LOG_IO(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) + #define IMGUI_DEBUG_LOG_INPUTROUTING(...) do{if (g.DebugLogFlags & ImGuiDebugLogFlags_EventInputRouting)IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) ++#define IMGUI_DEBUG_LOG_DOCKING(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventDocking) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) ++#define IMGUI_DEBUG_LOG_VIEWPORT(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventViewport) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) + + // Static Asserts + #define IM_STATIC_ASSERT(_COND) static_assert(_COND, "") +@@ -876,7 +887,7 @@ enum ImGuiItemStatusFlags_ + enum ImGuiHoveredFlagsPrivate_ + { + ImGuiHoveredFlags_DelayMask_ = ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay, +- ImGuiHoveredFlags_AllowedMaskForIsWindowHovered = ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary, ++ ImGuiHoveredFlags_AllowedMaskForIsWindowHovered = ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy | ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary, + ImGuiHoveredFlags_AllowedMaskForIsItemHovered = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayMask_, + }; + +@@ -1169,6 +1180,9 @@ enum ImGuiNextWindowDataFlags_ + ImGuiNextWindowDataFlags_HasScroll = 1 << 7, + ImGuiNextWindowDataFlags_HasChildFlags = 1 << 8, + ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 9, ++ ImGuiNextWindowDataFlags_HasViewport = 1 << 10, ++ ImGuiNextWindowDataFlags_HasDock = 1 << 11, ++ ImGuiNextWindowDataFlags_HasWindowClass = 1 << 12, + }; + + // Storage for SetNexWindow** functions +@@ -1178,17 +1192,22 @@ struct ImGuiNextWindowData + ImGuiCond PosCond; + ImGuiCond SizeCond; + ImGuiCond CollapsedCond; ++ ImGuiCond DockCond; + ImVec2 PosVal; + ImVec2 PosPivotVal; + ImVec2 SizeVal; + ImVec2 ContentSizeVal; + ImVec2 ScrollVal; + ImGuiChildFlags ChildFlags; ++ bool PosUndock; + bool CollapsedVal; + ImRect SizeConstraintRect; + ImGuiSizeCallback SizeCallback; + void* SizeCallbackUserData; + float BgAlphaVal; // Override background alpha ++ ImGuiID ViewportId; ++ ImGuiID DockId; ++ ImGuiWindowClass WindowClass; + ImVec2 MenuBarOffsetMinVal; // (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?) + ImGuiWindowRefreshFlags RefreshFlagsVal; + +@@ -1357,6 +1376,7 @@ enum ImGuiInputEventType + ImGuiInputEventType_MousePos, + ImGuiInputEventType_MouseWheel, + ImGuiInputEventType_MouseButton, ++ ImGuiInputEventType_MouseViewport, + ImGuiInputEventType_Key, + ImGuiInputEventType_Text, + ImGuiInputEventType_Focus, +@@ -1377,6 +1397,7 @@ enum ImGuiInputSource + struct ImGuiInputEventMousePos { float PosX, PosY; ImGuiMouseSource MouseSource; }; + struct ImGuiInputEventMouseWheel { float WheelX, WheelY; ImGuiMouseSource MouseSource; }; + struct ImGuiInputEventMouseButton { int Button; bool Down; ImGuiMouseSource MouseSource; }; ++struct ImGuiInputEventMouseViewport { ImGuiID HoveredViewportID; }; + struct ImGuiInputEventKey { ImGuiKey Key; bool Down; float AnalogValue; }; + struct ImGuiInputEventText { unsigned int Char; }; + struct ImGuiInputEventAppFocused { bool Focused; }; +@@ -1391,6 +1412,7 @@ struct ImGuiInputEvent + ImGuiInputEventMousePos MousePos; // if Type == ImGuiInputEventType_MousePos + ImGuiInputEventMouseWheel MouseWheel; // if Type == ImGuiInputEventType_MouseWheel + ImGuiInputEventMouseButton MouseButton; // if Type == ImGuiInputEventType_MouseButton ++ ImGuiInputEventMouseViewport MouseViewport; // if Type == ImGuiInputEventType_MouseViewport + ImGuiInputEventKey Key; // if Type == ImGuiInputEventType_Key + ImGuiInputEventText Text; // if Type == ImGuiInputEventType_Text + ImGuiInputEventAppFocused AppFocused; // if Type == ImGuiInputEventType_Focus +@@ -1778,8 +1800,153 @@ struct IMGUI_API ImGuiMultiSelectState + // [SECTION] Docking support + //----------------------------------------------------------------------------- + ++#define DOCKING_HOST_DRAW_CHANNEL_BG 0 // Dock host: background fill ++#define DOCKING_HOST_DRAW_CHANNEL_FG 1 // Dock host: decorations and contents ++ + #ifdef IMGUI_HAS_DOCK +-// ++ ++// Extend ImGuiDockNodeFlags_ ++enum ImGuiDockNodeFlagsPrivate_ ++{ ++ // [Internal] ++ ImGuiDockNodeFlags_DockSpace = 1 << 10, // Saved // A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. ++ ImGuiDockNodeFlags_CentralNode = 1 << 11, // Saved // The central node has 2 main properties: stay visible when empty, only use "remaining" spaces from its neighbor. ++ ImGuiDockNodeFlags_NoTabBar = 1 << 12, // Saved // Tab bar is completely unavailable. No triangle in the corner to enable it back. ++ ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, // Saved // Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) ++ ImGuiDockNodeFlags_NoWindowMenuButton = 1 << 14, // Saved // Disable window/docking menu (that one that appears instead of the collapse button) ++ ImGuiDockNodeFlags_NoCloseButton = 1 << 15, // Saved // Disable close button ++ ImGuiDockNodeFlags_NoResizeX = 1 << 16, // // ++ ImGuiDockNodeFlags_NoResizeY = 1 << 17, // // ++ ImGuiDockNodeFlags_DockedWindowsInFocusRoute= 1 << 18, // // Any docked window will be automatically be focus-route chained (window->ParentWindowForFocusRoute set to this) so Shortcut() in this window can run when any docked window is focused. ++ // Disable docking/undocking actions in this dockspace or individual node (existing docked nodes will be preserved) ++ // Those are not exposed in public because the desirable sharing/inheriting/copy-flag-on-split behaviors are quite difficult to design and understand. ++ // The two public flags ImGuiDockNodeFlags_NoDockingOverCentralNode/ImGuiDockNodeFlags_NoDockingSplit don't have those issues. ++ ImGuiDockNodeFlags_NoDockingSplitOther = 1 << 19, // // Disable this node from splitting other windows/nodes. ++ ImGuiDockNodeFlags_NoDockingOverMe = 1 << 20, // // Disable other windows/nodes from being docked over this node. ++ ImGuiDockNodeFlags_NoDockingOverOther = 1 << 21, // // Disable this node from being docked over another window or non-empty node. ++ ImGuiDockNodeFlags_NoDockingOverEmpty = 1 << 22, // // Disable this node from being docked over an empty node (e.g. DockSpace with no other windows) ++ ImGuiDockNodeFlags_NoDocking = ImGuiDockNodeFlags_NoDockingOverMe | ImGuiDockNodeFlags_NoDockingOverOther | ImGuiDockNodeFlags_NoDockingOverEmpty | ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoDockingSplitOther, ++ // Masks ++ ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, ++ ImGuiDockNodeFlags_NoResizeFlagsMask_ = (int)ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, ++ ++ // When splitting, those local flags are moved to the inheriting child, never duplicated ++ ImGuiDockNodeFlags_LocalFlagsTransferMask_ = (int)ImGuiDockNodeFlags_NoDockingSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | (int)ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, ++ ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, ++}; ++ ++// Store the source authority (dock node vs window) of a field ++enum ImGuiDataAuthority_ ++{ ++ ImGuiDataAuthority_Auto, ++ ImGuiDataAuthority_DockNode, ++ ImGuiDataAuthority_Window, ++}; ++ ++enum ImGuiDockNodeState ++{ ++ ImGuiDockNodeState_Unknown, ++ ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow, ++ ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing, ++ ImGuiDockNodeState_HostWindowVisible, ++}; ++ ++// sizeof() 156~192 ++struct IMGUI_API ImGuiDockNode ++{ ++ ImGuiID ID; ++ ImGuiDockNodeFlags SharedFlags; // (Write) Flags shared by all nodes of a same dockspace hierarchy (inherited from the root node) ++ ImGuiDockNodeFlags LocalFlags; // (Write) Flags specific to this node ++ ImGuiDockNodeFlags LocalFlagsInWindows; // (Write) Flags specific to this node, applied from windows ++ ImGuiDockNodeFlags MergedFlags; // (Read) Effective flags (== SharedFlags | LocalFlagsInNode | LocalFlagsInWindows) ++ ImGuiDockNodeState State; ++ ImGuiDockNode* ParentNode; ++ ImGuiDockNode* ChildNodes[2]; // [Split node only] Child nodes (left/right or top/bottom). Consider switching to an array. ++ ImVector Windows; // Note: unordered list! Iterate TabBar->Tabs for user-order. ++ ImGuiTabBar* TabBar; ++ ImVec2 Pos; // Current position ++ ImVec2 Size; // Current size ++ ImVec2 SizeRef; // [Split node only] Last explicitly written-to size (overridden when using a splitter affecting the node), used to calculate Size. ++ ImGuiAxis SplitAxis; // [Split node only] Split axis (X or Y) ++ ImGuiWindowClass WindowClass; // [Root node only] ++ ImU32 LastBgColor; ++ ++ ImGuiWindow* HostWindow; ++ ImGuiWindow* VisibleWindow; // Generally point to window which is ID is == SelectedTabID, but when CTRL+Tabbing this can be a different window. ++ ImGuiDockNode* CentralNode; // [Root node only] Pointer to central node. ++ ImGuiDockNode* OnlyNodeWithWindows; // [Root node only] Set when there is a single visible node within the hierarchy. ++ int CountNodeWithWindows; // [Root node only] ++ int LastFrameAlive; // Last frame number the node was updated or kept alive explicitly with DockSpace() + ImGuiDockNodeFlags_KeepAliveOnly ++ int LastFrameActive; // Last frame number the node was updated. ++ int LastFrameFocused; // Last frame number the node was focused. ++ ImGuiID LastFocusedNodeId; // [Root node only] Which of our child docking node (any ancestor in the hierarchy) was last focused. ++ ImGuiID SelectedTabId; // [Leaf node only] Which of our tab/window is selected. ++ ImGuiID WantCloseTabId; // [Leaf node only] Set when closing a specific tab/window. ++ ImGuiID RefViewportId; // Reference viewport ID from visible window when HostWindow == NULL. ++ ImGuiDataAuthority AuthorityForPos :3; ++ ImGuiDataAuthority AuthorityForSize :3; ++ ImGuiDataAuthority AuthorityForViewport :3; ++ bool IsVisible :1; // Set to false when the node is hidden (usually disabled as it has no active window) ++ bool IsFocused :1; ++ bool IsBgDrawnThisFrame :1; ++ bool HasCloseButton :1; // Provide space for a close button (if any of the docked window has one). Note that button may be hidden on window without one. ++ bool HasWindowMenuButton :1; ++ bool HasCentralNodeChild :1; ++ bool WantCloseAll :1; // Set when closing all tabs at once. ++ bool WantLockSizeOnce :1; ++ bool WantMouseMove :1; // After a node extraction we need to transition toward moving the newly created host window ++ bool WantHiddenTabBarUpdate :1; ++ bool WantHiddenTabBarToggle :1; ++ ++ ImGuiDockNode(ImGuiID id); ++ ~ImGuiDockNode(); ++ bool IsRootNode() const { return ParentNode == NULL; } ++ bool IsDockSpace() const { return (MergedFlags & ImGuiDockNodeFlags_DockSpace) != 0; } ++ bool IsFloatingNode() const { return ParentNode == NULL && (MergedFlags & ImGuiDockNodeFlags_DockSpace) == 0; } ++ bool IsCentralNode() const { return (MergedFlags & ImGuiDockNodeFlags_CentralNode) != 0; } ++ bool IsHiddenTabBar() const { return (MergedFlags & ImGuiDockNodeFlags_HiddenTabBar) != 0; } // Hidden tab bar can be shown back by clicking the small triangle ++ bool IsNoTabBar() const { return (MergedFlags & ImGuiDockNodeFlags_NoTabBar) != 0; } // Never show a tab bar ++ bool IsSplitNode() const { return ChildNodes[0] != NULL; } ++ bool IsLeafNode() const { return ChildNodes[0] == NULL; } ++ bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; } ++ ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } ++ ++ void SetLocalFlags(ImGuiDockNodeFlags flags) { LocalFlags = flags; UpdateMergedFlags(); } ++ void UpdateMergedFlags() { MergedFlags = SharedFlags | LocalFlags | LocalFlagsInWindows; } ++}; ++ ++// List of colors that are stored at the time of Begin() into Docked Windows. ++// We currently store the packed colors in a simple array window->DockStyle.Colors[]. ++// A better solution may involve appending into a log of colors in ImGuiContext + store offsets into those arrays in ImGuiWindow, ++// but it would be more complex as we'd need to double-buffer both as e.g. drop target may refer to window from last frame. ++enum ImGuiWindowDockStyleCol ++{ ++ ImGuiWindowDockStyleCol_Text, ++ ImGuiWindowDockStyleCol_TabHovered, ++ ImGuiWindowDockStyleCol_TabFocused, ++ ImGuiWindowDockStyleCol_TabSelected, ++ ImGuiWindowDockStyleCol_TabSelectedOverline, ++ ImGuiWindowDockStyleCol_TabDimmed, ++ ImGuiWindowDockStyleCol_TabDimmedSelected, ++ ImGuiWindowDockStyleCol_TabDimmedSelectedOverline, ++ ImGuiWindowDockStyleCol_COUNT ++}; ++ ++// We don't store style.Alpha: dock_node->LastBgColor embeds it and otherwise it would only affect the docking tab, which intuitively I would say we don't want to. ++struct ImGuiWindowDockStyle ++{ ++ ImU32 Colors[ImGuiWindowDockStyleCol_COUNT]; ++}; ++ ++struct ImGuiDockContext ++{ ++ ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes ++ ImVector Requests; ++ ImVector NodesSettings; ++ bool WantFullRebuild; ++ ImGuiDockContext() { memset(this, 0, sizeof(*this)); } ++}; ++ + #endif // #ifdef IMGUI_HAS_DOCK + + //----------------------------------------------------------------------------- +@@ -1790,10 +1957,24 @@ struct IMGUI_API ImGuiMultiSelectState + // Every instance of ImGuiViewport is in fact a ImGuiViewportP. + struct ImGuiViewportP : public ImGuiViewport + { ++ ImGuiWindow* Window; // Set when the viewport is owned by a window (and ImGuiViewportFlags_CanHostOtherWindows is NOT set) ++ int Idx; ++ int LastFrameActive; // Last frame number this viewport was activated by a window ++ int LastFocusedStampCount; // Last stamp number from when a window hosted by this viewport was focused (by comparing this value between two viewport we have an implicit viewport z-order we use as fallback) ++ ImGuiID LastNameHash; ++ ImVec2 LastPos; ++ ImVec2 LastSize; ++ float Alpha; // Window opacity (when dragging dockable windows/viewports we make them transparent) ++ float LastAlpha; ++ bool LastFocusedHadNavWindow;// Instead of maintaining a LastFocusedWindow (which may harder to correctly maintain), we merely store weither NavWindow != NULL last time the viewport was focused. ++ short PlatformMonitor; + int BgFgDrawListsLastFrame[2]; // Last frame number the background (0) and foreground (1) draw lists were used + ImDrawList* BgFgDrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. + ImDrawData DrawDataP; + ImDrawDataBuilder DrawDataBuilder; // Temporary data while building final ImDrawData ++ ImVec2 LastPlatformPos; ++ ImVec2 LastPlatformSize; ++ ImVec2 LastRendererSize; + + // Per-viewport work area + // - Insets are >= 0.0f values, distance from viewport corners to work area. +@@ -1804,8 +1985,9 @@ struct ImGuiViewportP : public ImGuiViewport + ImVec2 BuildWorkInsetMin; // Work Area inset accumulator for current frame, to become next frame's WorkInset + ImVec2 BuildWorkInsetMax; // " + +- ImGuiViewportP() { BgFgDrawListsLastFrame[0] = BgFgDrawListsLastFrame[1] = -1; BgFgDrawLists[0] = BgFgDrawLists[1] = NULL; } +- ~ImGuiViewportP() { if (BgFgDrawLists[0]) IM_DELETE(BgFgDrawLists[0]); if (BgFgDrawLists[1]) IM_DELETE(BgFgDrawLists[1]); } ++ ImGuiViewportP() { Window = NULL; Idx = -1; LastFrameActive = BgFgDrawListsLastFrame[0] = BgFgDrawListsLastFrame[1] = LastFocusedStampCount = -1; LastNameHash = 0; Alpha = LastAlpha = 1.0f; LastFocusedHadNavWindow = false; PlatformMonitor = -1; BgFgDrawLists[0] = BgFgDrawLists[1] = NULL; LastPlatformPos = LastPlatformSize = LastRendererSize = ImVec2(FLT_MAX, FLT_MAX); } ++ ~ImGuiViewportP() { if (BgFgDrawLists[0]) IM_DELETE(BgFgDrawLists[0]); if (BgFgDrawLists[1]) IM_DELETE(BgFgDrawLists[1]); } ++ void ClearRequestFlags() { PlatformRequestClose = PlatformRequestMove = PlatformRequestResize = false; } + + // Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect) + ImVec2 CalcWorkRectPos(const ImVec2& inset_min) const { return ImVec2(Pos.x + inset_min.x, Pos.y + inset_min.y); } +@@ -1828,14 +2010,19 @@ struct ImGuiViewportP : public ImGuiViewport + struct ImGuiWindowSettings + { + ImGuiID ID; +- ImVec2ih Pos; ++ ImVec2ih Pos; // NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions. + ImVec2ih Size; ++ ImVec2ih ViewportPos; ++ ImGuiID ViewportId; ++ ImGuiID DockId; // ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none. ++ ImGuiID ClassId; // ID of window class if specified ++ short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. + bool Collapsed; + bool IsChild; + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + bool WantDelete; // Set to invalidate/delete the settings entry + +- ImGuiWindowSettings() { memset(this, 0, sizeof(*this)); } ++ ImGuiWindowSettings() { memset(this, 0, sizeof(*this)); DockOrder = -1; } + char* GetName() { return (char*)(this + 1); } + }; + +@@ -1871,6 +2058,9 @@ enum ImGuiLocKey : int + ImGuiLocKey_WindowingUntitled, + ImGuiLocKey_OpenLink_s, + ImGuiLocKey_CopyLink, ++ ImGuiLocKey_DockingHideTabBar, ++ ImGuiLocKey_DockingHoldShiftToDock, ++ ImGuiLocKey_DockingDragToUndockOrMoveNode, + ImGuiLocKey_COUNT + }; + +@@ -1913,8 +2103,8 @@ enum ImGuiDebugLogFlags_ + ImGuiDebugLogFlags_EventSelection = 1 << 6, + ImGuiDebugLogFlags_EventIO = 1 << 7, + ImGuiDebugLogFlags_EventInputRouting = 1 << 8, +- ImGuiDebugLogFlags_EventDocking = 1 << 9, // Unused in this branch +- ImGuiDebugLogFlags_EventViewport = 1 << 10, // Unused in this branch ++ ImGuiDebugLogFlags_EventDocking = 1 << 9, ++ ImGuiDebugLogFlags_EventViewport = 1 << 10, + + ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventError | ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventInputRouting | ImGuiDebugLogFlags_EventDocking | ImGuiDebugLogFlags_EventViewport, + ImGuiDebugLogFlags_OutputToTTY = 1 << 20, // Also send output to TTY +@@ -1949,6 +2139,7 @@ struct ImGuiMetricsConfig + bool ShowDrawCmdBoundingBoxes = true; + bool ShowTextEncodingViewer = false; + bool ShowAtlasTintedWithTextColor = false; ++ bool ShowDockingNodes = false; + int ShowWindowsRectsType = -1; + int ShowTablesRectsType = -1; + int HighlightMonitorIdx = -1; +@@ -2008,15 +2199,18 @@ struct ImGuiContext + ImGuiIO IO; + ImGuiPlatformIO PlatformIO; + ImGuiStyle Style; ++ ImGuiConfigFlags ConfigFlagsCurrFrame; // = g.IO.ConfigFlags at the time of NewFrame() ++ ImGuiConfigFlags ConfigFlagsLastFrame; + ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() + float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. + float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. + float FontScale; // == FontSize / Font->FontSize +- float CurrentDpiScale; // Current window/viewport DpiScale ++ float CurrentDpiScale; // Current window/viewport DpiScale == CurrentViewport->DpiScale + ImDrawListSharedData DrawListSharedData; + double Time; + int FrameCount; + int FrameCountEnded; ++ int FrameCountPlatformEnded; + int FrameCountRendered; + bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame() + bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed +@@ -2045,7 +2239,7 @@ struct ImGuiContext + ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. + ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. + ImGuiWindow* HoveredWindowBeforeClear; // Window the mouse is hovering. Filled even with _NoMouse. This is currently useful for multi-context compositors. +- ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow. ++ ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindowDockTree. + ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. + ImVec2 WheelingWindowRefMousePos; + int WheelingWindowStartFrame; // This may be set one frame before WheelingWindow is != NULL +@@ -2123,7 +2317,16 @@ struct ImGuiContext + ImVectorTreeNodeStack; // Stack for TreeNode() + + // Viewports +- ImVector Viewports; // Active viewports (Size==1 in 'master' branch). Each viewports hold their copy of ImDrawData. ++ ImVector Viewports; // Active viewports (always 1+, and generally 1 unless multi-viewports are enabled). Each viewports hold their copy of ImDrawData. ++ ImGuiViewportP* CurrentViewport; // We track changes of viewport (happening in Begin) so we can call Platform_OnChangedViewport() ++ ImGuiViewportP* MouseViewport; ++ ImGuiViewportP* MouseLastHoveredViewport; // Last known viewport that was hovered by mouse (even if we are not hovering any viewport any more) + honoring the _NoInputs flag. ++ ImGuiID PlatformLastFocusedViewportId; ++ ImGuiPlatformMonitor FallbackMonitor; // Virtual monitor used as fallback if backend doesn't provide monitor information. ++ ImRect PlatformMonitorsFullWorkRect; // Bounding box of all platform monitors ++ int ViewportCreatedCount; // Unique sequential creation counter (mostly for testing/debugging) ++ int PlatformWindowsCreatedCount; // Unique sequential creation counter (mostly for testing/debugging) ++ int ViewportFocusedStampCount; // Every time the front-most window changes, we stamp its viewport with an incrementing counter + + // Gamepad/keyboard Navigation + ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusedWindow' +@@ -2291,6 +2494,12 @@ struct ImGuiContext + // Platform support + ImGuiPlatformImeData PlatformImeData; // Data updated by current frame + ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. ++ ImGuiID PlatformImeViewport; ++ ++ // Extensions ++ // FIXME: We could provide an API to register one slot in an array held in ImGuiContext? ++ ImGuiDockContext DockContext; ++ void (*DockNodeWindowMenuHandler)(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar); + + // Settings + bool SettingsLoaded; +@@ -2348,6 +2557,7 @@ struct ImGuiContext + ImGuiMetricsConfig DebugMetricsConfig; + ImGuiIDStackTool DebugIDStackTool; + ImGuiDebugAllocInfo DebugAllocInfo; ++ ImGuiDockNode* DebugHoveredDockNode; // Hovered dock node. + + // Misc + float FramerateSecPerFrame[60]; // Calculate estimate of framerate for user over the last 60 frames.. +@@ -2425,9 +2635,13 @@ struct IMGUI_API ImGuiWindow + ImGuiContext* Ctx; // Parent UI context (needs to be set explicitly by parent). + char* Name; // Window name, owned by the window. + ImGuiID ID; // == ImHashStr(Name) +- ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ ++ ImGuiWindowFlags Flags, FlagsPreviousFrame; // See enum ImGuiWindowFlags_ + ImGuiChildFlags ChildFlags; // Set when window is a child window. See enum ImGuiChildFlags_ ++ ImGuiWindowClass WindowClass; // Advanced users only. Set with SetNextWindowClass() + ImGuiViewportP* Viewport; // Always set in Begin(). Inactive windows may have a NULL value here if their viewport was discarded. ++ ImGuiID ViewportId; // We backup the viewport id (since the viewport may disappear or never be created if the window is inactive) ++ ImVec2 ViewportPos; // We backup the viewport position (since the viewport may disappear or never be created if the window is inactive) ++ int ViewportAllowPlatformMonitorExtend; // Reset to -1 every frame (index is guaranteed to be valid between NewFrame..EndFrame), only used in the Appearing frame of a tooltip/popup to enforce clamping to a given monitor + ImVec2 Pos; // Position (always rounded-up to nearest pixel) + ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) + ImVec2 SizeFull; // Size when non collapsed +@@ -2443,6 +2657,7 @@ struct IMGUI_API ImGuiWindow + float DecoInnerSizeX1, DecoInnerSizeY1; // Applied AFTER/OVER InnerRect. Specialized for Tables as they use specialized form of clipping and frozen rows/columns are inside InnerRect (and not part of regular decoration sizes). + int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)! + ImGuiID MoveId; // == window->GetID("#MOVE") ++ ImGuiID TabId; // == window->GetID("#TAB") + ImGuiID ChildId; // ID of corresponding item in parent window (for navigation to return from child window to parent window) + ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) + ImVec2 Scroll; +@@ -2452,6 +2667,7 @@ struct IMGUI_API ImGuiWindow + ImVec2 ScrollTargetEdgeSnapDist; // 0.0f = no snapping, >0.0f snapping threshold + ImVec2 ScrollbarSizes; // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar. + bool ScrollbarX, ScrollbarY; // Are scrollbars visible? ++ bool ViewportOwned; + bool Active; // Set to true on Begin(), unless Collapsed + bool WasActive; + bool WriteAccessed; // Set to true when any widget access the current window +@@ -2481,6 +2697,7 @@ struct IMGUI_API ImGuiWindow + ImGuiCond SetWindowPosAllowFlags : 8; // store acceptable condition flags for SetNextWindowPos() use. + ImGuiCond SetWindowSizeAllowFlags : 8; // store acceptable condition flags for SetNextWindowSize() use. + ImGuiCond SetWindowCollapsedAllowFlags : 8; // store acceptable condition flags for SetNextWindowCollapsed() use. ++ ImGuiCond SetWindowDockAllowFlags : 8; // store acceptable condition flags for SetNextWindowDock() use. + ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) + ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5f, 0.5f) for centering; ImVec2(1, 1) for bottom right. + +@@ -2500,11 +2717,13 @@ struct IMGUI_API ImGuiWindow + ImVec2ih HitTestHoleOffset; + + int LastFrameActive; // Last frame number the window was Active. ++ int LastFrameJustFocused; // Last frame number the window was made Focused. + float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there) + float ItemWidthDefault; + ImGuiStorage StateStorage; + ImVector ColumnsStorage; + float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() ++ float FontDpiScale; + int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) + + ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) +@@ -2513,6 +2732,7 @@ struct IMGUI_API ImGuiWindow + ImGuiWindow* ParentWindowInBeginStack; + ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window. Doesn't cross through popups/dock nodes. + ImGuiWindow* RootWindowPopupTree; // Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child. ++ ImGuiWindow* RootWindowDockTree; // Point to ourself or first ancestor that is not a child window. Cross through dock nodes. + ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. + ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. + ImGuiWindow* ParentWindowForFocusRoute; // Set to manual link a window to its logical parent so that Shortcut() chain are honoerd (e.g. Tool linked to Document) +@@ -2527,6 +2747,19 @@ struct IMGUI_API ImGuiWindow + int MemoryDrawListVtxCapacity; + bool MemoryCompacted; // Set when window extraneous data have been garbage collected + ++ // Docking ++ bool DockIsActive :1; // When docking artifacts are actually visible. When this is set, DockNode is guaranteed to be != NULL. ~~ (DockNode != NULL) && (DockNode->Windows.Size > 1). ++ bool DockNodeIsVisible :1; ++ bool DockTabIsVisible :1; // Is our window visible this frame? ~~ is the corresponding tab selected? ++ bool DockTabWantClose :1; ++ short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. ++ ImGuiWindowDockStyle DockStyle; ++ ImGuiDockNode* DockNode; // Which node are we docked into. Important: Prefer testing DockIsActive in many cases as this will still be set when the dock node is hidden. ++ ImGuiDockNode* DockNodeAsHost; // Which node are we owning (for parent windows) ++ ImGuiID DockId; // Backup of last valid DockNode->ID, so single window remember their dock node id even when they are not bound any more ++ ImGuiItemStatusFlags DockTabItemStatusFlags; ++ ImRect DockTabItemRect; ++ + public: + ImGuiWindow(ImGuiContext* context, const char* name); + ~ImGuiWindow(); +@@ -2539,7 +2772,7 @@ public: + + // We don't use g.FontSize because the window may be != g.CurrentWindow. + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } +- float CalcFontSize() const { ImGuiContext& g = *Ctx; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } ++ float CalcFontSize() const { ImGuiContext& g = *Ctx; float scale = g.FontBaseSize * FontWindowScale * FontDpiScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } + ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); } + ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } + }; +@@ -2562,13 +2795,15 @@ enum ImGuiTabItemFlagsPrivate_ + ImGuiTabItemFlags_SectionMask_ = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing, + ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) + ImGuiTabItemFlags_Button = 1 << 21, // Used by TabItemButton, change the tab item behavior to mimic a button ++ ImGuiTabItemFlags_Unsorted = 1 << 22, // [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window. + }; + +-// Storage for one active tab item (sizeof() 40 bytes) ++// Storage for one active tab item (sizeof() 48 bytes) + struct ImGuiTabItem + { + ImGuiID ID; + ImGuiTabItemFlags Flags; ++ ImGuiWindow* Window; // When TabItem is part of a DockNode's TabBar, we hold on to a window. + int LastFrameVisible; + int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance + float Offset; // Position relative to beginning of tab +@@ -2934,7 +3169,7 @@ namespace ImGui + IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window); + IMGUI_API void UpdateWindowSkipRefresh(ImGuiWindow* window); + IMGUI_API ImVec2 CalcWindowNextAutoFitSize(ImGuiWindow* window); +- IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy); ++ IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy); + IMGUI_API bool IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent); + IMGUI_API bool IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below); + IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); +@@ -2943,7 +3178,7 @@ namespace ImGui + IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0); + IMGUI_API void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); + IMGUI_API void SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window); +- inline void SetWindowParentWindowForFocusRoute(ImGuiWindow* window, ImGuiWindow* parent_window) { window->ParentWindowForFocusRoute = parent_window; } ++ inline void SetWindowParentWindowForFocusRoute(ImGuiWindow* window, ImGuiWindow* parent_window) { window->ParentWindowForFocusRoute = parent_window; } // You may also use SetNextWindowClass()'s FocusRouteParentWindowId field. + inline ImRect WindowRectAbsToRel(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y); } + inline ImRect WindowRectRelToAbs(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y); } + inline ImVec2 WindowPosAbsToRel(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x - off.x, p.y - off.y); } +@@ -2965,9 +3200,7 @@ namespace ImGui + // Fonts, drawing + IMGUI_API void SetCurrentFont(ImFont* font); + inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } +- inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); return GetForegroundDrawList(); } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. +- IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport); // get background draw list for the given viewport. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. +- IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport); // get foreground draw list for the given viewport. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. ++ inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { return GetForegroundDrawList(window->Viewport); } + IMGUI_API void AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector* out_list, ImDrawList* draw_list); + + // Init +@@ -2979,6 +3212,7 @@ namespace ImGui + IMGUI_API void UpdateHoveredWindowAndCaptureFlags(); + IMGUI_API void FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window); + IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window); ++ IMGUI_API void StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock); + IMGUI_API void UpdateMouseMovingWindowNewFrame(); + IMGUI_API void UpdateMouseMovingWindowEndFrame(); + +@@ -2988,7 +3222,13 @@ namespace ImGui + IMGUI_API void CallContextHooks(ImGuiContext* context, ImGuiContextHookType type); + + // Viewports ++ IMGUI_API void TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos, const ImVec2& old_size, const ImVec2& new_size); ++ IMGUI_API void ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale); ++ IMGUI_API void DestroyPlatformWindow(ImGuiViewportP* viewport); + IMGUI_API void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport); ++ IMGUI_API void SetCurrentViewport(ImGuiWindow* window, ImGuiViewportP* viewport); ++ IMGUI_API const ImGuiPlatformMonitor* GetViewportPlatformMonitor(ImGuiViewport* viewport); ++ IMGUI_API ImGuiViewportP* FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos); + + // Settings + IMGUI_API void MarkIniSettingsDirty(); +@@ -3203,6 +3443,61 @@ namespace ImGui + IMGUI_API bool TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id); + IMGUI_API ImGuiKeyRoutingData* GetShortcutRoutingData(ImGuiKeyChord key_chord); + ++ // Docking ++ // (some functions are only declared in imgui.cpp, see Docking section) ++ IMGUI_API void DockContextInitialize(ImGuiContext* ctx); ++ IMGUI_API void DockContextShutdown(ImGuiContext* ctx); ++ IMGUI_API void DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs); // Use root_id==0 to clear all ++ IMGUI_API void DockContextRebuildNodes(ImGuiContext* ctx); ++ IMGUI_API void DockContextNewFrameUpdateUndocking(ImGuiContext* ctx); ++ IMGUI_API void DockContextNewFrameUpdateDocking(ImGuiContext* ctx); ++ IMGUI_API void DockContextEndFrame(ImGuiContext* ctx); ++ IMGUI_API ImGuiID DockContextGenNodeID(ImGuiContext* ctx); ++ IMGUI_API void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer); ++ IMGUI_API void DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window); ++ IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); ++ IMGUI_API void DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true); ++ IMGUI_API void DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); ++ IMGUI_API bool DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos); ++ IMGUI_API ImGuiDockNode*DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id); ++ IMGUI_API void DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar); ++ IMGUI_API bool DockNodeBeginAmendTabBar(ImGuiDockNode* node); ++ IMGUI_API void DockNodeEndAmendTabBar(); ++ inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; } ++ inline bool DockNodeIsInHierarchyOf(ImGuiDockNode* node, ImGuiDockNode* parent) { while (node) { if (node == parent) return true; node = node->ParentNode; } return false; } ++ inline int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; } ++ inline ImGuiID DockNodeGetWindowMenuButtonId(const ImGuiDockNode* node) { return ImHashStr("#COLLAPSE", 0, node->ID); } ++ inline ImGuiDockNode* GetWindowDockNode() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DockNode; } ++ IMGUI_API bool GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window); ++ IMGUI_API void BeginDocked(ImGuiWindow* window, bool* p_open); ++ IMGUI_API void BeginDockableDragDropSource(ImGuiWindow* window); ++ IMGUI_API void BeginDockableDragDropTarget(ImGuiWindow* window); ++ IMGUI_API void SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond); ++ ++ // Docking - Builder function needs to be generally called before the node is used/submitted. ++ // - The DockBuilderXXX functions are designed to _eventually_ become a public API, but it is too early to expose it and guarantee stability. ++ // - Do not hold on ImGuiDockNode* pointers! They may be invalidated by any split/merge/remove operation and every frame. ++ // - To create a DockSpace() node, make sure to set the ImGuiDockNodeFlags_DockSpace flag when calling DockBuilderAddNode(). ++ // You can create dockspace nodes (attached to a window) _or_ floating nodes (carry its own window) with this API. ++ // - DockBuilderSplitNode() create 2 child nodes within 1 node. The initial node becomes a parent node. ++ // - If you intend to split the node immediately after creation using DockBuilderSplitNode(), make sure ++ // to call DockBuilderSetNodeSize() beforehand. If you don't, the resulting split sizes may not be reliable. ++ // - Call DockBuilderFinish() after you are done. ++ IMGUI_API void DockBuilderDockWindow(const char* window_name, ImGuiID node_id); ++ IMGUI_API ImGuiDockNode*DockBuilderGetNode(ImGuiID node_id); ++ inline ImGuiDockNode* DockBuilderGetCentralNode(ImGuiID node_id) { ImGuiDockNode* node = DockBuilderGetNode(node_id); if (!node) return NULL; return DockNodeGetRootNode(node)->CentralNode; } ++ IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id = 0, ImGuiDockNodeFlags flags = 0); ++ IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows ++ IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_settings_refs = true); ++ IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the remaining root node (node_id). ++ IMGUI_API void DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos); ++ IMGUI_API void DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size); ++ IMGUI_API ImGuiID DockBuilderSplitNode(ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir); // Create 2 child nodes in this parent node. ++ IMGUI_API void DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs); ++ IMGUI_API void DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector* out_node_remap_pairs); ++ IMGUI_API void DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name); ++ IMGUI_API void DockBuilderFinish(ImGuiID node_id); ++ + // [EXPERIMENTAL] Focus Scope + // This is generally used to identify a unique input location (for e.g. a selection set) + // There is one per window (automatically set in Begin), but: +@@ -3313,9 +3608,11 @@ namespace ImGui + IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); + IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id); + IMGUI_API ImGuiTabItem* TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order); ++ IMGUI_API ImGuiTabItem* TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar); + IMGUI_API ImGuiTabItem* TabBarGetCurrentTab(ImGuiTabBar* tab_bar); + inline int TabBarGetTabOrder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { return tab_bar->Tabs.index_from_ptr(tab); } + IMGUI_API const char* TabBarGetTabName(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); ++ IMGUI_API void TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window); + IMGUI_API void TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id); + IMGUI_API void TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); + IMGUI_API void TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); +@@ -3349,8 +3646,10 @@ namespace ImGui + IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col); + IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz); + IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); ++ IMGUI_API void RenderArrowDockMenu(ImDrawList* draw_list, ImVec2 p_min, float sz, ImU32 col); + IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); + IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); ++ IMGUI_API ImDrawFlags CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold); + + // Widgets + IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); +@@ -3364,7 +3663,7 @@ namespace ImGui + + // Widgets: Window Decorations + IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos); +- IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); ++ IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node); + IMGUI_API void Scrollbar(ImGuiAxis axis); + IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags flags); + IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis); +@@ -3456,6 +3755,7 @@ namespace ImGui + IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); + IMGUI_API void DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end); + IMGUI_API void DebugNodeColumns(ImGuiOldColumns* columns); ++ IMGUI_API void DebugNodeDockNode(ImGuiDockNode* node, const char* label); + IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label); + IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); + IMGUI_API void DebugNodeFont(ImFont* font); +@@ -3472,6 +3772,7 @@ namespace ImGui + IMGUI_API void DebugNodeWindowsList(ImVector* windows, const char* label); + IMGUI_API void DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack); + IMGUI_API void DebugNodeViewport(ImGuiViewportP* viewport); ++ IMGUI_API void DebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor, const char* label, int idx); + IMGUI_API void DebugRenderKeyboardPreview(ImDrawList* draw_list); + IMGUI_API void DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb); + +diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp +index 322c0846..837d1c64 100644 +--- a/imgui_widgets.cpp ++++ b/imgui_widgets.cpp +@@ -512,7 +512,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool + item_flags |= ImGuiItemFlags_ButtonRepeat; + + ImGuiWindow* backup_hovered_window = g.HoveredWindow; +- const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindow == window; ++ const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindowDockTree == window->RootWindowDockTree; + if (flatten_hovered_children) + g.HoveredWindow = window; + +@@ -868,7 +868,8 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) + return pressed; + } + +-bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) ++// The Collapse button also functions as a Dock Menu button. ++bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node) + { + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; +@@ -881,16 +882,21 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) + return pressed; + + // Render ++ //bool is_dock_menu = (window->DockNodeAsHost && !window->Collapsed); + ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImU32 text_col = GetColorU32(ImGuiCol_Text); + if (hovered || held) + window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_Compact); +- RenderArrow(window->DrawList, bb.Min, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); ++ ++ if (dock_node) ++ RenderArrowDockMenu(window->DrawList, bb.Min, g.FontSize, text_col); ++ else ++ RenderArrow(window->DrawList, bb.Min, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); + + // Switch to moving the window after mouse is moved beyond the initial drag threshold + if (IsItemActive() && IsMouseDragging(0)) +- StartMouseMovingWindow(window); ++ StartMouseMovingWindowOrNode(window, dock_node, true); // Undock from window/collapse menu button + + return pressed; + } +@@ -1633,7 +1639,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end + const float separator_thickness = style.SeparatorTextBorderSize; + const ImVec2 min_size(label_size.x + extra_w + padding.x * 2.0f, ImMax(label_size.y + padding.y * 2.0f, separator_thickness)); + const ImRect bb(pos, ImVec2(window->WorkRect.Max.x, pos.y + min_size.y)); +- const float text_baseline_y = ImTrunc((bb.GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.99999f); //ImMax(padding.y, ImFloor((style.SeparatorTextSize - label_size.y) * 0.5f)); ++ const float text_baseline_y = ImTrunc((bb.GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.99999f); //ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f)); + ItemSize(min_size, text_baseline_y); + if (!ItemAdd(bb, id)) + return; +@@ -5254,6 +5260,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ + g.PlatformImeData.WantVisible = true; + g.PlatformImeData.InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); + g.PlatformImeData.InputLineHeight = g.FontSize; ++ g.PlatformImeViewport = window->Viewport->ID; + } + } + } +@@ -8569,7 +8576,7 @@ bool ImGui::BeginMenuBar() + // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. + // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy. + ImRect bar_rect = window->MenuBarRect(); +- ImRect clip_rect(IM_ROUND(bar_rect.Min.x + window->WindowBorderSize), IM_ROUND(bar_rect.Min.y + window->WindowBorderSize), IM_ROUND(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, window->WindowBorderSize))), IM_ROUND(bar_rect.Max.y)); ++ ImRect clip_rect(ImFloor(bar_rect.Min.x + window->WindowBorderSize), ImFloor(bar_rect.Min.y + window->WindowBorderSize), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, window->WindowBorderSize))), ImFloor(bar_rect.Max.y)); + clip_rect.ClipWith(window->OuterRectClipped); + PushClipRect(clip_rect.Min, clip_rect.Max, false); + +@@ -8639,10 +8646,10 @@ bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, Im + IM_ASSERT(dir != ImGuiDir_None); + + ImGuiWindow* bar_window = FindWindowByName(name); ++ ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)(viewport_p ? viewport_p : GetMainViewport()); + if (bar_window == NULL || bar_window->BeginCount == 0) + { + // Calculate and set window size/position +- ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)(viewport_p ? viewport_p : GetMainViewport()); + ImRect avail_rect = viewport->GetBuildWorkRect(); + ImGuiAxis axis = (dir == ImGuiDir_Up || dir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X; + ImVec2 pos = avail_rect.Min; +@@ -8660,7 +8667,8 @@ bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, Im + viewport->BuildWorkInsetMax[axis] += axis_size; + } + +- window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; ++ window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking; ++ SetNextWindowViewport(viewport->ID); // Enforce viewport so we don't create our own viewport when ImGuiConfigFlags_ViewportsNoMerge is set. + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0)); // Lift normal size constraint + bool is_open = Begin(name, NULL, window_flags); +@@ -8674,6 +8682,9 @@ bool ImGui::BeginMainMenuBar() + ImGuiContext& g = *GImGui; + ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport(); + ++ // Notify of viewport change so GetFrameHeight() can be accurate in case of DPI change ++ SetCurrentViewport(NULL, viewport); ++ + // For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set. + // FIXME: This could be generalized as an opt-in way to clamp window->DC.CursorStartPos to avoid SafeArea? + // FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings. +@@ -8724,7 +8735,7 @@ static bool IsRootOfOpenMenuSet() + const ImGuiPopupData* upper_popup = &g.OpenPopupStack[g.BeginPopupStack.Size]; + if (window->DC.NavLayerCurrent != upper_popup->ParentNavLayer) + return false; +- return upper_popup->Window && (upper_popup->Window->Flags & ImGuiWindowFlags_ChildMenu) && ImGui::IsWindowChildOf(upper_popup->Window, window, true); ++ return upper_popup->Window && (upper_popup->Window->Flags & ImGuiWindowFlags_ChildMenu) && ImGui::IsWindowChildOf(upper_popup->Window, window, true, false); + } + + bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) +@@ -9063,8 +9074,10 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, + // - TabBarCalcMaxTabWidth() [Internal] + // - TabBarFindTabById() [Internal] + // - TabBarFindTabByOrder() [Internal] ++// - TabBarFindMostRecentlySelectedTabForActiveWindow() [Internal] + // - TabBarGetCurrentTab() [Internal] + // - TabBarGetTabName() [Internal] ++// - TabBarAddTab() [Internal] + // - TabBarRemoveTab() [Internal] + // - TabBarCloseTab() [Internal] + // - TabBarScrollClamp() [Internal] +@@ -9186,7 +9199,8 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG + + // Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable + if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (tab_bar->TabsAddedNew && !(flags & ImGuiTabBarFlags_Reorderable))) +- ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); ++ if ((flags & ImGuiTabBarFlags_DockNode) == 0) // FIXME: TabBar with DockNode can now be hybrid ++ ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); + tab_bar->TabsAddedNew = false; + + // Flags +@@ -9468,6 +9482,10 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) + tab_bar->VisibleTabId = tab_bar->SelectedTabId; + tab_bar->VisibleTabWasSubmitted = false; + ++ // CTRL+TAB can override visible tab temporarily ++ if (g.NavWindowingTarget != NULL && g.NavWindowingTarget->DockNode && g.NavWindowingTarget->DockNode->TabBar == tab_bar) ++ tab_bar->VisibleTabId = scroll_to_tab_id = g.NavWindowingTarget->TabId; ++ + // Apply request requests + if (scroll_to_tab_id != 0) + TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections); +@@ -9513,11 +9531,11 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) + // Dockable windows uses Name/ID in the global namespace. Non-dockable items use the ID stack. + static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window) + { +- IM_ASSERT(docked_window == NULL); // master branch only +- IM_UNUSED(docked_window); +- if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) ++ if (docked_window != NULL) + { +- ImGuiID id = ImHashStr(label); ++ IM_UNUSED(tab_bar); ++ IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode); ++ ImGuiID id = docked_window->TabId; + KeepAliveID(id); + return id; + } +@@ -9551,6 +9569,20 @@ ImGuiTabItem* ImGui::TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order) + return &tab_bar->Tabs[order]; + } + ++// FIXME: See references to #2304 in TODO.txt ++ImGuiTabItem* ImGui::TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar) ++{ ++ ImGuiTabItem* most_recently_selected_tab = NULL; ++ for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) ++ { ++ ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; ++ if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) ++ if (tab->Window && tab->Window->WasActive) ++ most_recently_selected_tab = tab; ++ } ++ return most_recently_selected_tab; ++} ++ + ImGuiTabItem* ImGui::TabBarGetCurrentTab(ImGuiTabBar* tab_bar) + { + if (tab_bar->LastTabItemIdx < 0 || tab_bar->LastTabItemIdx >= tab_bar->Tabs.Size) +@@ -9560,12 +9592,35 @@ ImGuiTabItem* ImGui::TabBarGetCurrentTab(ImGuiTabBar* tab_bar) + + const char* ImGui::TabBarGetTabName(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) + { ++ if (tab->Window) ++ return tab->Window->Name; + if (tab->NameOffset == -1) + return "N/A"; + IM_ASSERT(tab->NameOffset < tab_bar->TabsNames.Buf.Size); + return tab_bar->TabsNames.Buf.Data + tab->NameOffset; + } + ++// The purpose of this call is to register tab in advance so we can control their order at the time they appear. ++// Otherwise calling this is unnecessary as tabs are appending as needed by the BeginTabItem() function. ++void ImGui::TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window) ++{ ++ ImGuiContext& g = *GImGui; ++ IM_ASSERT(TabBarFindTabByID(tab_bar, window->TabId) == NULL); ++ IM_ASSERT(g.CurrentTabBar != tab_bar); // Can't work while the tab bar is active as our tab doesn't have an X offset yet, in theory we could/should test something like (tab_bar->CurrFrameVisible < g.FrameCount) but we'd need to solve why triggers the commented early-out assert in BeginTabBarEx() (probably dock node going from implicit to explicit in same frame) ++ ++ if (!window->HasCloseButton) ++ tab_flags |= ImGuiTabItemFlags_NoCloseButton; // Set _NoCloseButton immediately because it will be used for first-frame width calculation. ++ ++ ImGuiTabItem new_tab; ++ new_tab.ID = window->TabId; ++ new_tab.Flags = tab_flags; ++ new_tab.LastFrameVisible = tab_bar->CurrFrameVisible; // Required so BeginTabBar() doesn't ditch the tab ++ if (new_tab.LastFrameVisible == -1) ++ new_tab.LastFrameVisible = g.FrameCount - 1; ++ new_tab.Window = window; // Required so tab bar layout can compute the tab width before tab submission ++ tab_bar->Tabs.push_back(new_tab); ++} ++ + // The *TabId fields are already set by the docking system _before_ the actual TabItem was created, so we clear them regardless. + void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) + { +@@ -9853,7 +9908,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f + IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!"); + return false; + } +- IM_ASSERT(!(flags & ImGuiTabItemFlags_Button)); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! ++ IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! + + bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL); + if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) +@@ -9963,11 +10018,14 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, + const bool is_tab_button = (flags & ImGuiTabItemFlags_Button) != 0; + tab->LastFrameVisible = g.FrameCount; + tab->Flags = flags; ++ tab->Window = docked_window; + + // Append name _WITH_ the zero-terminator ++ // (regular tabs are permitted in a DockNode tab bar, but window tabs not permitted in a non-DockNode tab bar) + if (docked_window != NULL) + { +- IM_ASSERT(docked_window == NULL); // master branch only ++ IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode); ++ tab->NameOffset = -1; + } + else + { +@@ -9992,7 +10050,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, + tab_bar->VisibleTabWasSubmitted = true; + + // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches +- if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing) ++ if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing && docked_window == NULL) + if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) + tab_contents_visible = true; + +@@ -10040,30 +10098,82 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, + } + + // Click to Select a tab +- // Allow the close button to overlap + ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowOverlap); +- if (g.DragDropActive) ++ if (g.DragDropActive && !g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW)) // FIXME: May be an opt-in property of the payload to disable this + button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + if (pressed && !is_tab_button) + TabBarQueueFocus(tab_bar, tab); + +- // Drag and drop: re-order tabs +- if (held && !tab_appearing && IsMouseDragging(0)) ++ // Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow() ++ // will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id. ++ if (held && docked_window && g.ActiveId == id && g.ActiveIdIsJustActivated) ++ g.ActiveIdWindow = docked_window; ++ ++ // Drag and drop a single floating window node moves it ++ ImGuiDockNode* node = docked_window ? docked_window->DockNode : NULL; ++ const bool single_floating_window_node = node && node->IsFloatingNode() && (node->Windows.Size == 1); ++ if (held && single_floating_window_node && IsMouseDragging(0, 0.0f)) + { +- if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) ++ // Move ++ StartMouseMovingWindow(docked_window); ++ } ++ else if (held && !tab_appearing && IsMouseDragging(0)) ++ { ++ // Drag and drop: re-order tabs ++ int drag_dir = 0; ++ float drag_distance_from_edge_x = 0.0f; ++ if (!g.DragDropActive && ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (docked_window != NULL))) + { + // While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x + if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x) + { ++ drag_dir = -1; ++ drag_distance_from_edge_x = bb.Min.x - g.IO.MousePos.x; + TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos); + } + else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x) + { ++ drag_dir = +1; ++ drag_distance_from_edge_x = g.IO.MousePos.x - bb.Max.x; + TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos); + } + } ++ ++ // Extract a Dockable window out of it's tab bar ++ const bool can_undock = docked_window != NULL && !(docked_window->Flags & ImGuiWindowFlags_NoMove) && !(node->MergedFlags & ImGuiDockNodeFlags_NoUndocking); ++ if (can_undock) ++ { ++ // We use a variable threshold to distinguish dragging tabs within a tab bar and extracting them out of the tab bar ++ bool undocking_tab = (g.DragDropActive && g.DragDropPayload.SourceId == id); ++ if (!undocking_tab) //&& (!g.IO.ConfigDockingWithShift || g.IO.KeyShift) ++ { ++ float threshold_base = g.FontSize; ++ float threshold_x = (threshold_base * 2.2f); ++ float threshold_y = (threshold_base * 1.5f) + ImClamp((ImFabs(g.IO.MouseDragMaxDistanceAbs[0].x) - threshold_base * 2.0f) * 0.20f, 0.0f, threshold_base * 4.0f); ++ //GetForegroundDrawList()->AddRect(ImVec2(bb.Min.x - threshold_x, bb.Min.y - threshold_y), ImVec2(bb.Max.x + threshold_x, bb.Max.y + threshold_y), IM_COL32_WHITE); // [DEBUG] ++ ++ float distance_from_edge_y = ImMax(bb.Min.y - g.IO.MousePos.y, g.IO.MousePos.y - bb.Max.y); ++ if (distance_from_edge_y >= threshold_y) ++ undocking_tab = true; ++ if (drag_distance_from_edge_x > threshold_x) ++ if ((drag_dir < 0 && TabBarGetTabOrder(tab_bar, tab) == 0) || (drag_dir > 0 && TabBarGetTabOrder(tab_bar, tab) == tab_bar->Tabs.Size - 1)) ++ undocking_tab = true; ++ } ++ ++ if (undocking_tab) ++ { ++ // Undock ++ // FIXME: refactor to share more code with e.g. StartMouseMovingWindow ++ DockContextQueueUndockWindow(&g, docked_window); ++ g.MovingWindow = docked_window; ++ SetActiveID(g.MovingWindow->MoveId, g.MovingWindow); ++ g.ActiveIdClickOffset -= g.MovingWindow->Pos - bb.Min; ++ g.ActiveIdNoClearOnFocusLoss = true; ++ SetActiveIdUsingAllKeyboardKeys(); ++ } ++ } + } + + #if 0 +@@ -10099,7 +10209,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, + flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; + + // Render tab label, process close button +- const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, id) : 0; ++ const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, docked_window ? docked_window->ID : id) : 0; + bool just_closed; + bool text_clipped; + TabItemLabelAndCloseButton(display_draw_list, bb, tab_just_unsaved ? (flags & ~ImGuiTabItemFlags_UnsavedDocument) : flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped); +@@ -10109,6 +10219,11 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, + TabBarCloseTab(tab_bar, tab); + } + ++ // Forward Hovered state so IsItemHovered() after Begin() can work (even though we are technically hovering our parent) ++ // That state is copied to window->DockTabItemStatusFlags by our caller. ++ if (docked_window && (hovered || g.HoveredId == close_button_id)) ++ g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; ++ + // Restore main window position so user can draw there + if (want_clip_rect) + PopClipRect(); +@@ -10143,6 +10258,16 @@ void ImGui::SetTabItemClosed(const char* label) + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) + tab->WantClose = true; // Will be processed by next call to TabBarLayout() + } ++ else if (ImGuiWindow* window = FindWindowByName(label)) ++ { ++ if (window->DockIsActive) ++ if (ImGuiDockNode* node = window->DockNode) ++ { ++ ImGuiID tab_id = TabBarCalcTabID(node->TabBar, label, window); ++ TabBarRemoveTab(node->TabBar, tab_id); ++ window->DockTabWantClose = true; ++ } ++ } + } + + ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker) +@@ -10157,10 +10282,9 @@ ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button_or_unsave + return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y); + } + +-ImVec2 ImGui::TabItemCalcSize(ImGuiWindow*) ++ImVec2 ImGui::TabItemCalcSize(ImGuiWindow* window) + { +- IM_ASSERT(0); // This function exists to facilitate merge with 'docking' branch. +- return ImVec2(0.0f, 0.0f); ++ return TabItemCalcSize(window->Name, window->HasCloseButton || (window->Flags & ImGuiWindowFlags_UnsavedDocument)); + } + + void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col) +diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp +index d97605b2..d7256ce9 100644 +--- a/misc/freetype/imgui_freetype.cpp ++++ b/misc/freetype/imgui_freetype.cpp @@ -34,10 +34,10 @@ // FIXME: cfg.OversampleH, OversampleV are not supported (but perhaps not so necessary with this rasterizer). @@ -198,7 +11127,7 @@ diff --color -rbu ./misc/freetype/imgui_freetype.cpp ../scummvm/scummvm/backends #include #include #include FT_FREETYPE_H // -@@ -396,7 +396,7 @@ +@@ -396,7 +396,7 @@ namespace #ifdef IMGUI_STB_RECT_PACK_FILENAME #include IMGUI_STB_RECT_PACK_FILENAME #else @@ -207,9 +11136,10 @@ diff --color -rbu ./misc/freetype/imgui_freetype.cpp ../scummvm/scummvm/backends #endif #endif -diff --color -rbu ./misc/freetype/imgui_freetype.h ../scummvm/scummvm/backends/imgui/misc/freetype/imgui_freetype.h ---- ./misc/freetype/imgui_freetype.h 2024-05-13 22:08:39 -+++ ../scummvm/scummvm/backends/imgui/misc/freetype/imgui_freetype.h 2024-10-07 18:32:44 +diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h +index b4e1d489..4f537f62 100644 +--- a/misc/freetype/imgui_freetype.h ++++ b/misc/freetype/imgui_freetype.h @@ -2,7 +2,7 @@ // (headers) diff --git a/backends/mixer/sdl/sdl-mixer.cpp b/backends/mixer/sdl/sdl-mixer.cpp index 022d50e05988..cff19f84edeb 100644 --- a/backends/mixer/sdl/sdl-mixer.cpp +++ b/backends/mixer/sdl/sdl-mixer.cpp @@ -44,8 +44,13 @@ SdlMixerManager::~SdlMixerManager() { if (_mixer) _mixer->setReady(false); +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_CloseAudioDevice(SDL_GetAudioStreamDevice(_stream)); + SDL_DestroyAudioStream(_stream); +#else if (_isAudioOpen) SDL_CloseAudio(); +#endif if (_isSubsystemInitialized) SDL_QuitSubSystem(SDL_INIT_AUDIO); @@ -63,7 +68,11 @@ void SdlMixerManager::init() { SDL_AudioSpec desired = getAudioSpec(SAMPLES_PER_SEC); // Start SDL Audio subsystem +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (!SDL_InitSubSystem(SDL_INIT_AUDIO)) { +#else if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) { +#endif warning("Could not initialize SDL audio subsystem: %s", SDL_GetError()); return; } @@ -80,6 +89,10 @@ void SdlMixerManager::init() { #endif debug(1, "Using SDL Audio Driver \"%s\"", sdlDriverName); +#if SDL_VERSION_ATLEAST(3, 0, 0) + _isAudioOpen = true; + _obtained = desired; +#else // Needed as SDL_OpenAudio as of SDL-1.2.14 mutates fields in // "desired" if used directly. SDL_AudioSpec fmt = desired; @@ -106,11 +119,13 @@ void SdlMixerManager::init() { _obtained = desired; } +#endif debug(1, "Output sample rate: %d Hz", _obtained.freq); if (_obtained.freq != desired.freq) warning("SDL mixer output sample rate: %d differs from desired: %d", _obtained.freq, desired.freq); +#if !SDL_VERSION_ATLEAST(3, 0, 0) debug(1, "Output buffer size: %d samples", _obtained.samples); if (_obtained.samples != desired.samples) warning("SDL mixer output buffer size: %d differs from desired: %d", _obtained.samples, desired.samples); @@ -118,14 +133,23 @@ void SdlMixerManager::init() { debug(1, "Output channels: %d", _obtained.channels); if (_obtained.channels != 1 && _obtained.channels != 2) error("SDL mixer output requires mono or stereo output device"); +#endif - _mixer = new Audio::MixerImpl(_obtained.freq, _obtained.channels >= 2, desired.samples); + int desiredSamples = 0; +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_GetAudioDeviceFormat(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &_obtained, &desiredSamples); +#else + desiredSamples = desired.samples; +#endif + + _mixer = new Audio::MixerImpl(_obtained.freq, _obtained.channels >= 2, desiredSamples); assert(_mixer); _mixer->setReady(true); startAudio(); } +#if !SDL_VERSION_ATLEAST(3, 0, 0) static uint32 roundDownPowerOfTwo(uint32 samples) { // Public domain code from Sean Eron Anderson // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 @@ -143,6 +167,7 @@ static uint32 roundDownPowerOfTwo(uint32 samples) { return rounded; } +#endif SDL_AudioSpec SdlMixerManager::getAudioSpec(uint32 outputRate) { SDL_AudioSpec desired; @@ -184,18 +209,28 @@ SDL_AudioSpec SdlMixerManager::getAudioSpec(uint32 outputRate) { memset(&desired, 0, sizeof(desired)); desired.freq = freq; - desired.format = AUDIO_S16SYS; desired.channels = channels; +#if SDL_VERSION_ATLEAST(3, 0, 0) + desired.format = SDL_AUDIO_S16; +#else + desired.format = AUDIO_S16SYS; desired.samples = roundDownPowerOfTwo(samples); desired.callback = sdlCallback; desired.userdata = this; +#endif return desired; } void SdlMixerManager::startAudio() { // Start the sound system +#if SDL_VERSION_ATLEAST(3, 0, 0) + _stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &_obtained, sdl3Callback, this); + if (_stream) + SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(_stream)); +#else SDL_PauseAudio(0); +#endif } void SdlMixerManager::callbackHandler(byte *samples, int len) { @@ -210,18 +245,46 @@ void SdlMixerManager::sdlCallback(void *this_, byte *samples, int len) { manager->callbackHandler(samples, len); } +#if SDL_VERSION_ATLEAST(3, 0, 0) +void SdlMixerManager::sdl3Callback(void *userdata, SDL_AudioStream *stream, int additional_amount, int total_amount) +{ + if (additional_amount > 0) { + Uint8 *data = SDL_stack_alloc(Uint8, additional_amount); + if (data) { + SdlMixerManager *manager = (SdlMixerManager *)userdata; + manager->sdlCallback(userdata, data, additional_amount); + SDL_PutAudioStreamData(stream, data, additional_amount); + SDL_stack_free(data); + } + } +} +#endif + void SdlMixerManager::suspendAudio() { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_CloseAudioDevice(SDL_GetAudioStreamDevice(_stream)); + SDL_DestroyAudioStream(_stream); +#else SDL_CloseAudio(); +#endif _audioSuspended = true; } int SdlMixerManager::resumeAudio() { if (!_audioSuspended) return -2; +#if SDL_VERSION_ATLEAST(3, 0, 0) + _stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &_obtained, sdl3Callback, this); + if(!_stream) + return -1; + if (SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(_stream))) + return -1; +#else if (SDL_OpenAudio(&_obtained, nullptr) < 0) { return -1; } SDL_PauseAudio(0); +#endif _audioSuspended = false; return 0; } diff --git a/backends/mixer/sdl/sdl-mixer.h b/backends/mixer/sdl/sdl-mixer.h index 2c8ea2232b8e..3dd0670396fa 100644 --- a/backends/mixer/sdl/sdl-mixer.h +++ b/backends/mixer/sdl/sdl-mixer.h @@ -80,9 +80,16 @@ class SdlMixerManager : public MixerManager { * by subclasses, so it invokes the non-static function callbackHandler() */ static void sdlCallback(void *this_, byte *samples, int len); +#if SDL_VERSION_ATLEAST(3, 0, 0) + static void sdl3Callback(void *userdata, SDL_AudioStream *stream, int additional_amount, int total_amount); +#endif bool _isSubsystemInitialized; bool _isAudioOpen; + +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_AudioStream *_stream = nullptr; +#endif }; #endif diff --git a/backends/module.mk b/backends/module.mk index d1acc3d8d547..5d4d8f130bd4 100644 --- a/backends/module.mk +++ b/backends/module.mk @@ -510,5 +510,20 @@ MODULE_OBJS += \ endif endif +ifdef USE_SDL3 +ifdef USE_IMGUI +ifdef USE_OPENGL +MODULE_OBJS += \ + imgui/backends/imgui_impl_opengl3.o +endif +ifdef USE_IMGUI_SDLRENDERER3 +MODULE_OBJS += \ + imgui/backends/imgui_impl_sdlrenderer3.o +endif +MODULE_OBJS += \ + imgui/backends/imgui_impl_sdl3.o +endif +endif + # Include common rules include $(srcdir)/rules.mk diff --git a/backends/mutex/sdl/sdl-mutex.cpp b/backends/mutex/sdl/sdl-mutex.cpp index 3ada8e5ecd07..11e951b4845a 100644 --- a/backends/mutex/sdl/sdl-mutex.cpp +++ b/backends/mutex/sdl/sdl-mutex.cpp @@ -34,11 +34,29 @@ class SdlMutexInternal final : public Common::MutexInternal { SdlMutexInternal() { _mutex = SDL_CreateMutex(); } ~SdlMutexInternal() override { SDL_DestroyMutex(_mutex); } - bool lock() override { return (SDL_mutexP(_mutex) == 0); } - bool unlock() override { return (SDL_mutexV(_mutex) == 0); } + bool lock() override { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_LockMutex(_mutex); + return true; +#else + return (SDL_mutexP(_mutex) == 0); +#endif + } + bool unlock() override { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_UnlockMutex(_mutex); + return true; +#else + return (SDL_mutexV(_mutex) == 0); +#endif + } private: +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Mutex *_mutex; +#else SDL_mutex *_mutex; +#endif }; Common::MutexInternal *createSdlMutexInternal() { diff --git a/backends/platform/sdl/macosx/macosx-window.mm b/backends/platform/sdl/macosx/macosx-window.mm index d8481eaee465..59e194d529f0 100644 --- a/backends/platform/sdl/macosx/macosx-window.mm +++ b/backends/platform/sdl/macosx/macosx-window.mm @@ -27,7 +27,7 @@ #include float SdlWindow_MacOSX::getDpiScalingFactor() const { -#if SDL_VERSION_ATLEAST(2, 0, 0) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7 +#if !SDL_VERSION_ATLEAST(3, 0, 0) && SDL_VERSION_ATLEAST(2, 0, 0) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7 SDL_SysWMinfo wmInfo; if (getSDLWMInformation(&wmInfo)) { NSWindow *nswindow = wmInfo.info.cocoa.window; diff --git a/backends/platform/sdl/sdl-sys.h b/backends/platform/sdl/sdl-sys.h index 87bd6cabfab3..1eb5129887f0 100644 --- a/backends/platform/sdl/sdl-sys.h +++ b/backends/platform/sdl/sdl-sys.h @@ -187,12 +187,18 @@ #endif +#ifdef USE_SDL3 +#include +#else #include +#endif // Ignore warnings from system headers pulled by SDL #pragma warning(push) #pragma warning(disable:4121) // alignment of a member was sensitive to packing +#if !SDL_VERSION_ATLEAST(3, 0, 0) #include +#endif #pragma warning(pop) // Restore the forbidden exceptions from the hack above diff --git a/backends/platform/sdl/sdl-window.cpp b/backends/platform/sdl/sdl-window.cpp index 508ffe8a6c82..0afe7a407b86 100644 --- a/backends/platform/sdl/sdl-window.cpp +++ b/backends/platform/sdl/sdl-window.cpp @@ -29,7 +29,9 @@ #include "icons/scummvm.xpm" -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) +static const uint32 fullscreenMask = SDL_WINDOW_FULLSCREEN; +#elif SDL_VERSION_ATLEAST(2, 0, 0) static const uint32 fullscreenMask = SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_FULLSCREEN; #endif @@ -122,7 +124,11 @@ void SdlWindow::setupIcon() { } } +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Surface *sdl_surf = SDL_CreateSurfaceFrom(w, h, SDL_GetPixelFormatForMasks(32, 0xFF0000, 0x00FF00, 0x0000FF, 0xFF000000), icon, w * 4); +#else SDL_Surface *sdl_surf = SDL_CreateRGBSurfaceFrom(icon, w, h, 32, w * 4, 0xFF0000, 0x00FF00, 0x0000FF, 0xFF000000); +#endif if (!sdl_surf) { warning("SDL_CreateRGBSurfaceFrom(icon) failed"); } @@ -135,7 +141,11 @@ void SdlWindow::setupIcon() { SDL_WM_SetIcon(sdl_surf, NULL); #endif +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_DestroySurface(sdl_surf); +#else SDL_FreeSurface(sdl_surf); +#endif free(icon); #endif } @@ -154,7 +164,11 @@ void SdlWindow::setWindowCaption(const Common::String &caption) { void SdlWindow::grabMouse(bool grab) { #if SDL_VERSION_ATLEAST(2, 0, 0) if (_window) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_SetWindowMouseGrab(_window, grab); +#else SDL_SetWindowGrab(_window, grab ? SDL_TRUE : SDL_FALSE); +#endif #if SDL_VERSION_ATLEAST(2, 0, 18) SDL_SetWindowMouseRect(_window, grab ? &grabRect : NULL); #endif @@ -187,7 +201,10 @@ void SdlWindow::setMouseRect(const Common::Rect &rect) { } bool SdlWindow::lockMouse(bool lock) { -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_SetWindowRelativeMouseMode(_window, lock); + _inputLockState = lock; +#elif SDL_VERSION_ATLEAST(2, 0, 0) SDL_SetRelativeMouseMode(lock ? SDL_TRUE : SDL_FALSE); _inputLockState = lock; #else @@ -244,6 +261,7 @@ void SdlWindow::iconifyWindow() { #endif } +#if !SDL_VERSION_ATLEAST(3, 0, 0) bool SdlWindow::getSDLWMInformation(SDL_SysWMinfo *info) const { SDL_VERSION(&info->version); #if SDL_VERSION_ATLEAST(2, 0, 0) @@ -254,9 +272,17 @@ bool SdlWindow::getSDLWMInformation(SDL_SysWMinfo *info) const { return false; #endif } +#endif Common::Rect SdlWindow::getDesktopResolution() { -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + const SDL_DisplayMode* pDisplayMode = SDL_GetDesktopDisplayMode(getDisplayIndex()); + if (pDisplayMode) { + _desktopRes = Common::Rect(pDisplayMode->w, pDisplayMode->h); + } else { + warning("SDL_GetDesktopDisplayMode failed: %s", SDL_GetError()); + } +#elif SDL_VERSION_ATLEAST(2, 0, 0) SDL_DisplayMode displayMode; if (!SDL_GetDesktopDisplayMode(getDisplayIndex(), &displayMode)) { _desktopRes = Common::Rect(displayMode.w, displayMode.h); @@ -279,7 +305,9 @@ void SdlWindow::getDisplayDpi(float *dpi, float *defaultDpi) const { *defaultDpi = systemDpi; if (dpi) { -#if SDL_VERSION_ATLEAST(2, 0, 4) +#if SDL_VERSION_ATLEAST(3, 0, 0) + *dpi = SDL_GetWindowDisplayScale(_window) * systemDpi; +#elif SDL_VERSION_ATLEAST(2, 0, 4) if (SDL_GetDisplayDPI(getDisplayIndex(), nullptr, dpi, nullptr) != 0) { *dpi = systemDpi; } @@ -303,7 +331,9 @@ float SdlWindow::getDpiScalingFactor() const { } float SdlWindow::getSdlDpiScalingFactor() const { -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + return SDL_GetWindowDisplayScale(getSDLWindow()); +#elif SDL_VERSION_ATLEAST(2, 0, 0) int windowWidth, windowHeight; SDL_GetWindowSize(getSDLWindow(), &windowWidth, &windowHeight); int realWidth, realHeight; @@ -316,7 +346,11 @@ float SdlWindow::getSdlDpiScalingFactor() const { #if SDL_VERSION_ATLEAST(2, 0, 0) SDL_Surface *copySDLSurface(SDL_Surface *src) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + const bool locked = SDL_MUSTLOCK(src); +#else const bool locked = SDL_MUSTLOCK(src) == SDL_TRUE; +#endif if (locked) { if (SDL_LockSurface(src) != 0) { @@ -324,10 +358,15 @@ SDL_Surface *copySDLSurface(SDL_Surface *src) { } } +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_Surface *res = SDL_CreateSurfaceFrom(src->w, src->h, src->format, + src->pixels, src->pitch); +#else SDL_Surface *res = SDL_CreateRGBSurfaceFrom(src->pixels, src->w, src->h, src->format->BitsPerPixel, src->pitch, src->format->Rmask, src->format->Gmask, src->format->Bmask, src->format->Amask); +#endif if (locked) { SDL_UnlockSurface(src); @@ -337,6 +376,16 @@ SDL_Surface *copySDLSurface(SDL_Surface *src) { } int SdlWindow::getDisplayIndex() const { +#if SDL_VERSION_ATLEAST(3, 0, 0) + int display = 0; + int num_displays; + SDL_DisplayID *displays = SDL_GetDisplays(&num_displays); + if (num_displays > 0) { + display = static_cast(displays[0]); + } + SDL_free(displays); + return display; +#else if (_window) { int displayIndex = SDL_GetWindowDisplayIndex(_window); if (displayIndex >= 0) @@ -344,12 +393,19 @@ int SdlWindow::getDisplayIndex() const { } // Default to primary display return 0; +#endif } bool SdlWindow::createOrUpdateWindow(int width, int height, uint32 flags) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (_inputGrabState) { + flags |= SDL_WINDOW_MOUSE_GRABBED; + } +#else if (_inputGrabState) { flags |= SDL_WINDOW_INPUT_GRABBED; } +#endif // SDL_WINDOW_RESIZABLE can also be updated without recreating the window // starting with SDL 2.0.5, but it is not treated as updateable here @@ -360,7 +416,11 @@ bool SdlWindow::createOrUpdateWindow(int width, int height, uint32 flags) { // 2. Users (particularly on Windows) will sometimes swap older SDL DLLs // to avoid bugs, which would be impossible if the feature was enabled // at compile time using SDL_VERSION_ATLEAST. +#if SDL_VERSION_ATLEAST(3, 0, 0) + const uint32 updateableFlagsMask = fullscreenMask | SDL_WINDOW_MOUSE_GRABBED; +#else const uint32 updateableFlagsMask = fullscreenMask | SDL_WINDOW_INPUT_GRABBED; +#endif const uint32 oldNonUpdateableFlags = _lastFlags & ~updateableFlagsMask; const uint32 newNonUpdateableFlags = flags & ~updateableFlagsMask; @@ -387,7 +447,9 @@ bool SdlWindow::createOrUpdateWindow(int width, int height, uint32 flags) { ) { int top, left, bottom, right; -#if SDL_VERSION_ATLEAST(2, 0, 5) +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (!_window || !SDL_GetWindowBordersSize(_window, &top, &left, &bottom, &right)) +#elif SDL_VERSION_ATLEAST(2, 0, 5) if (!_window || SDL_GetWindowBordersSize(_window, &top, &left, &bottom, &right) < 0) #endif { @@ -408,13 +470,31 @@ bool SdlWindow::createOrUpdateWindow(int width, int height, uint32 flags) { if (!_window || oldNonUpdateableFlags != newNonUpdateableFlags) { destroyWindow(); +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_PropertiesID props = SDL_CreateProperties(); + SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, _windowCaption.c_str()); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, _lastX); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, _lastY); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, width); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, height); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_FLAGS_NUMBER, flags); + _window = SDL_CreateWindowWithProperties(props); + SDL_DestroyProperties(props); +#else _window = SDL_CreateWindow(_windowCaption.c_str(), _lastX, _lastY, width, height, flags); +#endif if (_window) { setupIcon(); } } else { if (fullscreenFlags) { +#if SDL_VERSION_ATLEAST(3, 0, 0) + if(!SDL_SetWindowFullscreenMode(_window, NULL)) + warning("SDL_SetWindowFullscreenMode failed: %s", SDL_GetError()); + if(!SDL_SyncWindow(_window)) + warning("SDL_SyncWindow failed: %s", SDL_GetError()); +#else SDL_DisplayMode fullscreenMode; fullscreenMode.w = width; fullscreenMode.h = height; @@ -422,6 +502,7 @@ bool SdlWindow::createOrUpdateWindow(int width, int height, uint32 flags) { fullscreenMode.format = 0; fullscreenMode.refresh_rate = 0; SDL_SetWindowDisplayMode(_window, &fullscreenMode); +#endif } else { SDL_SetWindowSize(_window, width, height); } @@ -429,8 +510,13 @@ bool SdlWindow::createOrUpdateWindow(int width, int height, uint32 flags) { SDL_SetWindowFullscreen(_window, fullscreenFlags); } +#if SDL_VERSION_ATLEAST(3, 0, 0) + const bool shouldGrab = (flags & SDL_WINDOW_MOUSE_GRABBED) || fullscreenFlags; + SDL_SetWindowMouseGrab(_window, shouldGrab); +#else const bool shouldGrab = (flags & SDL_WINDOW_INPUT_GRABBED) || fullscreenFlags; SDL_SetWindowGrab(_window, shouldGrab ? SDL_TRUE : SDL_FALSE); +#endif #if SDL_VERSION_ATLEAST(2, 0, 18) SDL_SetWindowMouseRect(_window, shouldGrab ? &grabRect : NULL); #endif diff --git a/backends/platform/sdl/sdl-window.h b/backends/platform/sdl/sdl-window.h index b3e4933874c0..1aabe99df902 100644 --- a/backends/platform/sdl/sdl-window.h +++ b/backends/platform/sdl/sdl-window.h @@ -78,6 +78,7 @@ class SdlWindow { */ void iconifyWindow(); +#if !SDL_VERSION_ATLEAST(3, 0, 0) /** * Query platform specific SDL window manager information. * @@ -85,6 +86,7 @@ class SdlWindow { * for accessing it in a version safe manner. */ bool getSDLWMInformation(SDL_SysWMinfo *info) const; +#endif /* * Retrieve the current desktop resolution. @@ -109,7 +111,11 @@ class SdlWindow { virtual float getDpiScalingFactor() const; bool mouseIsGrabbed() const { -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (_window) { + return SDL_GetWindowMouseGrab(_window); + } +#elif SDL_VERSION_ATLEAST(2, 0, 0) if (_window) { return SDL_GetWindowGrab(_window) == SDL_TRUE; } @@ -118,7 +124,9 @@ class SdlWindow { } bool mouseIsLocked() const { -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + return SDL_GetWindowRelativeMouseMode(_window); +#elif SDL_VERSION_ATLEAST(2, 0, 0) return SDL_GetRelativeMouseMode() == SDL_TRUE; #else return _inputLockState; diff --git a/backends/platform/sdl/sdl.cpp b/backends/platform/sdl/sdl.cpp index 3fc1f20b3053..3d93c49add95 100644 --- a/backends/platform/sdl/sdl.cpp +++ b/backends/platform/sdl/sdl.cpp @@ -20,6 +20,7 @@ */ #define FORBIDDEN_SYMBOL_ALLOW_ALL +#define SDL_FUNCTION_POINTER_IS_VOID_POINTER #include "backends/platform/sdl/sdl.h" #include "common/config-manager.h" @@ -72,8 +73,10 @@ #include #endif -#if SDL_VERSION_ATLEAST(2, 0, 0) -#include +#if SDL_VERSION_ATLEAST(3, 0, 0) + #include +#elif SDL_VERSION_ATLEAST(2, 0, 0) + #include #endif OSystem_SDL::OSystem_SDL() @@ -97,7 +100,11 @@ OSystem_SDL::OSystem_SDL() } OSystem_SDL::~OSystem_SDL() { +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_ShowCursor(); +#else SDL_ShowCursor(SDL_ENABLE); +#endif #ifdef USE_MULTIPLE_RENDERERS clearGraphicsModes(); @@ -162,8 +169,12 @@ void OSystem_SDL::init() { #endif #if !defined(OPENPANDORA) +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_HideCursor(); +#else // Disable OS cursor SDL_ShowCursor(SDL_DISABLE); +#endif #endif if (_window == nullptr) @@ -206,7 +217,13 @@ bool OSystem_SDL::hasFeature(Feature f) { #if defined(USE_SCUMMVMDLC) && defined(USE_LIBCURL) if (f == kFeatureDLC) return true; #endif -#if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (f == kFeatureTouchpadMode) { + int count = 0; + SDL_free(SDL_GetTouchDevices(&count)); + return count > 0; + } +#elif SDL_VERSION_ATLEAST(2, 0, 0) if (f == kFeatureTouchpadMode) { return SDL_GetNumTouchDevices() > 0; } @@ -383,7 +400,17 @@ void OSystem_SDL::detectOpenGLFeaturesSupport() { #else // Spawn a 32x32 window off-screen with a GL context to test if framebuffers are supported #if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_PropertiesID props = SDL_CreateProperties(); + SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, ""); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, 32); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, 32); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_FLAGS_NUMBER, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN); + SDL_Window *window = SDL_CreateWindowWithProperties(props); + SDL_DestroyProperties(props); +#else SDL_Window *window = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 32, 32, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN); +#endif if (!window) { return; } @@ -417,7 +444,11 @@ void OSystem_SDL::detectOpenGLFeaturesSupport() { _supportsFrameBuffer = OpenGLContext.framebufferObjectSupported; _supportsShaders = OpenGLContext.enginesShadersSupported; OpenGLContext.reset(); +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_GL_DestroyContext(glContext); +#else SDL_GL_DeleteContext(glContext); +#endif SDL_DestroyWindow(window); #else SDL_putenv(const_cast("SDL_VIDEO_WINDOW_POS=9000,9000")); @@ -443,7 +474,17 @@ void OSystem_SDL::detectAntiAliasingSupport() { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, requestedSamples); #if SDL_VERSION_ATLEAST(2, 0, 0) +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_PropertiesID props = SDL_CreateProperties(); + SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, ""); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, 32); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, 32); + SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_FLAGS_NUMBER, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN); + SDL_Window *window = SDL_CreateWindowWithProperties(props); + SDL_DestroyProperties(props); +#else SDL_Window *window = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 32, 32, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN); +#endif if (window) { SDL_GLContext glContext = SDL_GL_CreateContext(window); if (glContext) { @@ -454,7 +495,11 @@ void OSystem_SDL::detectAntiAliasingSupport() { _antiAliasLevels.push_back(requestedSamples); } +#if SDL_VERSION_ATLEAST(3, 0, 0) + SDL_GL_DestroyContext(glContext); +#else SDL_GL_DeleteContext(glContext); +#endif } SDL_DestroyWindow(window); @@ -533,11 +578,17 @@ void OSystem_SDL::initSDL() { // or otherwise the application won't start. uint32 sdlFlags = SDL_INIT_VIDEO; +#if !SDL_VERSION_ATLEAST(3, 0, 0) if (ConfMan.hasKey("disable_sdl_parachute")) sdlFlags |= SDL_INIT_NOPARACHUTE; +#endif // Initialize SDL (SDL Subsystems are initialized in the corresponding sdl managers) +#if SDL_VERSION_ATLEAST(3, 0, 0) + if (!SDL_Init(sdlFlags)) +#else if (SDL_Init(sdlFlags) == -1) +#endif error("Could not initialize SDL: %s", SDL_GetError()); _initedSDL = true; @@ -657,7 +708,19 @@ Common::WriteStream *OSystem_SDL::createLogFile() { Common::String OSystem_SDL::getSystemLanguage() const { -#if SDL_VERSION_ATLEAST(2, 0, 14) +#if SDL_VERSION_ATLEAST(3, 0, 0) + int count = 0; + SDL_Locale **pLocales = SDL_GetPreferredLocales(&count); + if (pLocales) { + SDL_Locale *locales = *pLocales; + if (locales[0].language != NULL) { + Common::String str = Common::String::format("%s_%s", locales[0].country, locales[0].language); + SDL_free(locales); + return str; + } + SDL_free(pLocales); + } +#elif SDL_VERSION_ATLEAST(2, 0, 14) SDL_Locale *locales = SDL_GetPreferredLocales(); if (locales) { if (locales[0].language != NULL) { @@ -667,7 +730,7 @@ Common::String OSystem_SDL::getSystemLanguage() const { } SDL_free(locales); } -#endif // SDL_VERSION_ATLEAST(2, 0, 14) +#endif #if defined(USE_DETECTLANG) && !defined(WIN32) // Activating current locale settings const Common::String locale = setlocale(LC_ALL, ""); @@ -704,7 +767,11 @@ Common::String OSystem_SDL::getSystemLanguage() const { #if SDL_VERSION_ATLEAST(2, 0, 0) bool OSystem_SDL::hasTextInClipboard() { +#if SDL_VERSION_ATLEAST(3, 0, 0) + return SDL_HasClipboardText(); +#else return SDL_HasClipboardText() == SDL_TRUE; +#endif } Common::U32String OSystem_SDL::getTextFromClipboard() { diff --git a/backends/timer/sdl/sdl-timer.cpp b/backends/timer/sdl/sdl-timer.cpp index 81812888f8ce..cda5923c3a7d 100644 --- a/backends/timer/sdl/sdl-timer.cpp +++ b/backends/timer/sdl/sdl-timer.cpp @@ -28,16 +28,25 @@ #include "common/textconsole.h" +#if SDL_VERSION_ATLEAST(3, 0, 0) +static Uint32 timer_handler(void *userdata, SDL_TimerID timerID, Uint32 interval) { + ((DefaultTimerManager *)userdata)->handler(); + return interval; +} +#else static Uint32 timer_handler(Uint32 interval, void *param) { ((DefaultTimerManager *)param)->handler(); return interval; } +#endif SdlTimerManager::SdlTimerManager() { +#if !SDL_VERSION_ATLEAST(3, 0, 0) // Initializes the SDL timer subsystem if (SDL_InitSubSystem(SDL_INIT_TIMER) == -1) { error("Could not initialize SDL: %s", SDL_GetError()); } +#endif // Creates the timer callback _timerID = SDL_AddTimer(10, &timer_handler, this); @@ -47,7 +56,9 @@ SdlTimerManager::~SdlTimerManager() { // Removes the timer callback SDL_RemoveTimer(_timerID); +#if !SDL_VERSION_ATLEAST(3, 0, 0) SDL_QuitSubSystem(SDL_INIT_TIMER); +#endif } #endif diff --git a/base/commandLine.cpp b/base/commandLine.cpp index 234ab0b51fb2..bdb3174be336 100644 --- a/base/commandLine.cpp +++ b/base/commandLine.cpp @@ -1933,7 +1933,10 @@ bool processSettings(Common::String &command, Common::StringMap &settings, Commo } else if (command == "version") { printf("%s\n", gScummVMFullVersion); #ifdef SDL_BACKEND -#ifdef USE_SDL2 +#ifdef USE_SDL3 + int sdlLinkedVersion = SDL_GetVersion(); + printf("Using SDL backend with SDL %d.%d.%d\n", SDL_VERSIONNUM_MAJOR(sdlLinkedVersion), SDL_VERSIONNUM_MINOR(sdlLinkedVersion), SDL_VERSIONNUM_MICRO(sdlLinkedVersion)); +#elif defined(USE_SDL2) SDL_version sdlLinkedVersion; SDL_GetVersion(&sdlLinkedVersion); printf("Using SDL backend with SDL %d.%d.%d\n", sdlLinkedVersion.major, sdlLinkedVersion.minor, sdlLinkedVersion.patch); diff --git a/configure b/configure index b490265b5b96..7f7c4ee274bc 100755 --- a/configure +++ b/configure @@ -248,7 +248,7 @@ _staticlibpath= _xcodetoolspath= _sparklepath= _pkgconfig=pkg-config -_sdlconfig=sdl2-config +_sdlconfig="pkg-config sdl3" _libcurlconfig=curl-config _libmikmodconfig=libmikmod-config _freetypeconfig=freetype-config @@ -4144,21 +4144,31 @@ fi # Setup SDL specifics for SDL based backends # if test "$_sdl" = auto ; then - find_sdlconfig + if test "$_pkg_config" = "yes" && $_pkgconfig --exists sdl3; then + _sdlconfig="pkg-config sdl3" + _sdlversion=`$_sdlconfig --modversion` + cat > $TMPC << EOF +#include "SDL3/SDL.h" +int main(int argc, char *argv[]) { SDL_Init(0); return 0; } +EOF + else + find_sdlconfig + _sdlversion=`$_sdlconfig --version` + cat > $TMPC << EOF +#include "SDL.h" +int main(int argc, char *argv[]) { SDL_Init(0); return 0; } +EOF + fi + append_var SDL_CFLAGS "`$_sdlconfig --cflags | sed 's/[[:space:]]*-Dmain=SDL_main//g'`" if test "$_static_build" = yes ; then append_var SDL_LIBS "`$_sdlconfig --static-libs`" else append_var SDL_LIBS "`$_sdlconfig --libs`" fi - _sdlversion=`$_sdlconfig --version` echocheck "SDL" _sdl=no - cat > $TMPC << EOF -#include "SDL.h" -int main(int argc, char *argv[]) { SDL_Init(0); return 0; } -EOF cc_check $LIBS $SDL_LIBS $INCLUDES $SDL_CFLAGS && _sdl=yes echo "$_sdl" if test "$_sdl" = no ; then @@ -4173,6 +4183,11 @@ if test "$_sdl" = yes ; then append_var INCLUDES "$SDL_CFLAGS" append_var LIBS "$SDL_LIBS" case $_sdlversion in + 3.*.*) + append_var DEFINES "-DUSE_SDL3" + add_line_to_config_mk "USE_SDL3 = 1" + _sdlMajorVersionNumber=3 + ;; 2.*.*) append_var DEFINES "-DUSE_SDL2" add_line_to_config_mk "USE_SDL2 = 1" @@ -4193,14 +4208,26 @@ fi # of SDL-net or SDL2-net that does not require SDL or SDL2 respectively # if test "$_sdlnet" = auto ; then + # If SDL3 was detected, then test for SDL3_net exclusively # If SDL2 was detected, then test for SDL2_net exclusively # If SDL was detected, then test for SDL_net exclusively - # If neither SDL nor SDL2 detected, then test for both (SDL2_net success takes priority) + # If neither SDL nor SDL2 detected nor SDL3 detected, then test for both (SDL3_net success takes priority) + set_var SDL3_NET_LIBS "$SDL_NET_LIBS" + set_var SDL3_NET_CFLAGS "$SDL_NET_CFLAGS" set_var SDL2_NET_LIBS "$SDL_NET_LIBS" set_var SDL2_NET_CFLAGS "$SDL_NET_CFLAGS" set_var SDL1_NET_LIBS "$SDL_NET_LIBS" set_var SDL1_NET_CFLAGS "$SDL_NET_CFLAGS" + if test "$_sdl" = no || test "$_sdlMajorVersionNumber" = 3; then + if test "$_pkg_config" = "yes" && $_pkgconfig --exists SDL3_net; then + append_var SDL3_NET_LIBS "`$_pkgconfig --libs SDL3_net`" + append_var SDL3_NET_CFLAGS "`$_pkgconfig --cflags SDL3_net | sed 's/[[:space:]]*-Dmain=SDL_main//g'`" + else + append_var SDL3_NET_LIBS "-lSDL3_net" + fi + fi + if test "$_sdl" = no || test "$_sdlMajorVersionNumber" = 2; then if test "$_pkg_config" = "yes" && $_pkgconfig --exists SDL2_net; then append_var SDL2_NET_LIBS "`$_pkgconfig --libs SDL2_net`" @@ -4222,26 +4249,39 @@ if test "$_sdlnet" = auto ; then # Check for SDL_Net echocheck "SDL_Net" _sdlnet=no - cat > $TMPC << EOF -#include "SDL_net.h" + +cat > $TMPC << EOF +#include "SDL3/SDL_net.h" int main(int argc, char *argv[]) { SDLNet_Init(); return 0; } EOF - cc_check $SDL2_NET_LIBS $LIBS $INCLUDES $SDL2_NET_CFLAGS && _sdlnet=yes + cc_check $SDL3_NET_LIBS $LIBS $INCLUDES $SDL3_NET_CFLAGS && _sdlnet=yes if test "$_sdlnet" = yes ; then set_var SDL_NET_LIBS "$SDL2_NET_LIBS" set_var SDL_NET_CFLAGS "$SDL2_NET_CFLAGS" add_line_to_config_mk "SDL_NET_MAJOR = 2" else cat > $TMPC << EOF -#include "SDL_net.h" +#include "SDL3/SDL_net.h" int main(int argc, char *argv[]) { SDLNet_Init(); return 0; } EOF - cc_check $SDL1_NET_LIBS $LIBS $INCLUDES $SDL1_NET_CFLAGS && _sdlnet=yes + + cc_check $SDL2_NET_LIBS $LIBS $INCLUDES $SDL2_NET_CFLAGS && _sdlnet=yes if test "$_sdlnet" = yes ; then - set_var SDL_NET_LIBS "$SDL1_NET_LIBS" - set_var SDL_NET_CFLAGS "$SDL1_NET_CFLAGS" - add_line_to_config_mk "SDL_NET_MAJOR = 1" + set_var SDL_NET_LIBS "$SDL2_NET_LIBS" + set_var SDL_NET_CFLAGS "$SDL2_NET_CFLAGS" + add_line_to_config_mk "SDL_NET_MAJOR = 2" + else + cat > $TMPC << EOF +#include "SDL_net.h" +int main(int argc, char *argv[]) { SDLNet_Init(); return 0; } +EOF + cc_check $SDL1_NET_LIBS $LIBS $INCLUDES $SDL1_NET_CFLAGS && _sdlnet=yes + if test "$_sdlnet" = yes ; then + set_var SDL_NET_LIBS "$SDL1_NET_LIBS" + set_var SDL_NET_CFLAGS "$SDL1_NET_CFLAGS" + add_line_to_config_mk "SDL_NET_MAJOR = 1" + fi fi fi @@ -6745,7 +6785,26 @@ if test "$_imgui" != no ; then if test "$_freetype2" = yes ; then case $_backend in sdl | sailfish) - if test "$_sdlMajorVersionNumber" -ge 2 ; then + if test "$_sdlMajorVersionNumber" -ge 3 ; then + cat > $TMPC << EOF +#include +#if !SDL_VERSION_ATLEAST(3,0,0) +#error Missing SDL_RenderGeometryRaw() function +#endif +int main(int argc, char *argv[]) { return 0; } +EOF + if cc_check $LIBS $SDL_LIBS $INCLUDES $SDL_CFLAGS; then + define_in_config_if_yes yes 'USE_IMGUI_SDLRENDERER3' + _imgui=yes + echo "yes" + elif test "$_opengl" = yes; then + _imgui=yes + echo "yes" + else + _imgui=no + echo "no (requires OpenGL or recent SDL)" + fi + elif test "$_sdlMajorVersionNumber" -ge 2 ; then cat > $TMPC << EOF #include "SDL.h" #if !SDL_VERSION_ATLEAST(2,0,18)