mirror of
https://github.com/ocornut/imgui.git
synced 2026-09-26 16:05:45 +03:00
Backend improvements (imgui_impl_android.h/.cpp): - Moved JNI soft-keyboard and Unicode char polling from the example into the backend. The application no longer needs any JNI boilerplate. - Added clipboard support via JNI to Android ClipboardManager. (#7259) - Added display metrics (DPI, density, refresh rate, orientation) via JNI. Used by the example to set main_scale from actual device density instead of hardcoded 2.0f. - BREAKING CHANGE: ImGui_ImplAndroid_Init() now takes additional asset_manager and native_activity parameters. See before/after in header. Example (main.cpp): - Removed ShowSoftKeyboardInput() and PollUnicodeChars() JNI helpers (~120 lines). - Removed their forward declarations and per-frame calls. - Updated Init() call to new signature. - Use ImGui_ImplAndroid_GetDisplayMetrics() for main_scale. - All other comments, EGL block, GetAssetData, APP_CMD cases unchanged. MainActivity.kt: unchanged (same 3 JNI bridge methods, now called by backend). docs/CHANGELOG.txt: Added entries for backend and example changes.
304 lines
12 KiB
C++
304 lines
12 KiB
C++
// dear imgui: standalone example application for Android + OpenGL ES 3
|
|
|
|
// 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
|
|
|
|
#include "imgui.h"
|
|
#include "imgui_impl_android.h"
|
|
#include "imgui_impl_opengl3.h"
|
|
#include <android/log.h>
|
|
#include <android_native_app_glue.h>
|
|
#include <android/asset_manager.h>
|
|
#include <EGL/egl.h>
|
|
#include <GLES3/gl3.h>
|
|
#include <string>
|
|
|
|
// Data
|
|
static EGLDisplay g_EglDisplay = EGL_NO_DISPLAY;
|
|
static EGLSurface g_EglSurface = EGL_NO_SURFACE;
|
|
static EGLContext g_EglContext = EGL_NO_CONTEXT;
|
|
static struct android_app* g_App = nullptr;
|
|
static bool g_Initialized = false;
|
|
static char g_LogTag[] = "ImGuiExample";
|
|
static std::string g_IniFilename = "";
|
|
|
|
// Forward declarations of helper functions
|
|
static void Init(struct android_app* app);
|
|
static void Shutdown();
|
|
static void MainLoopStep();
|
|
static int GetAssetData(const char* filename, void** out_data);
|
|
|
|
// Main code
|
|
static void handleAppCmd(struct android_app* app, int32_t appCmd)
|
|
{
|
|
switch (appCmd)
|
|
{
|
|
case APP_CMD_SAVE_STATE:
|
|
break;
|
|
case APP_CMD_INIT_WINDOW:
|
|
Init(app);
|
|
break;
|
|
case APP_CMD_TERM_WINDOW:
|
|
Shutdown();
|
|
break;
|
|
case APP_CMD_GAINED_FOCUS:
|
|
case APP_CMD_LOST_FOCUS:
|
|
break;
|
|
}
|
|
}
|
|
|
|
static int32_t handleInputEvent(struct android_app* app, AInputEvent* inputEvent)
|
|
{
|
|
return ImGui_ImplAndroid_HandleInputEvent(inputEvent);
|
|
}
|
|
|
|
void android_main(struct android_app* app)
|
|
{
|
|
app->onAppCmd = handleAppCmd;
|
|
app->onInputEvent = handleInputEvent;
|
|
|
|
while (true)
|
|
{
|
|
int out_events;
|
|
struct android_poll_source* out_data;
|
|
|
|
// Poll all events. If the app is not visible, this loop blocks until g_Initialized == true.
|
|
while (ALooper_pollOnce(g_Initialized ? 0 : -1, nullptr, &out_events, (void**)&out_data) >= 0)
|
|
{
|
|
// Process one event
|
|
if (out_data != nullptr)
|
|
out_data->process(app, out_data);
|
|
|
|
// Exit the app by returning from within the infinite loop
|
|
if (app->destroyRequested != 0)
|
|
{
|
|
// shutdown() should have been called already while processing the
|
|
// app command APP_CMD_TERM_WINDOW. But we play save here
|
|
if (!g_Initialized)
|
|
Shutdown();
|
|
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Initiate a new frame
|
|
MainLoopStep();
|
|
}
|
|
}
|
|
|
|
void Init(struct android_app* app)
|
|
{
|
|
if (g_Initialized)
|
|
return;
|
|
|
|
g_App = app;
|
|
ANativeWindow_acquire(g_App->window);
|
|
|
|
// Initialize EGL
|
|
// This is mostly boilerplate code for EGL...
|
|
{
|
|
g_EglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
|
|
if (g_EglDisplay == EGL_NO_DISPLAY)
|
|
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglGetDisplay(EGL_DEFAULT_DISPLAY) returned EGL_NO_DISPLAY");
|
|
|
|
if (eglInitialize(g_EglDisplay, 0, 0) != EGL_TRUE)
|
|
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglInitialize() returned with an error");
|
|
|
|
const EGLint egl_attributes[] = { EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
|
|
EGLint num_configs = 0;
|
|
if (eglChooseConfig(g_EglDisplay, egl_attributes, nullptr, 0, &num_configs) != EGL_TRUE)
|
|
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned with an error");
|
|
if (num_configs == 0)
|
|
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned 0 matching config");
|
|
|
|
// Get the first matching config
|
|
EGLConfig egl_config;
|
|
eglChooseConfig(g_EglDisplay, egl_attributes, &egl_config, 1, &num_configs);
|
|
EGLint egl_format;
|
|
eglGetConfigAttrib(g_EglDisplay, egl_config, EGL_NATIVE_VISUAL_ID, &egl_format);
|
|
ANativeWindow_setBuffersGeometry(g_App->window, 0, 0, egl_format);
|
|
|
|
const EGLint egl_context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE };
|
|
g_EglContext = eglCreateContext(g_EglDisplay, egl_config, EGL_NO_CONTEXT, egl_context_attributes);
|
|
|
|
if (g_EglContext == EGL_NO_CONTEXT)
|
|
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglCreateContext() returned EGL_NO_CONTEXT");
|
|
|
|
g_EglSurface = eglCreateWindowSurface(g_EglDisplay, egl_config, g_App->window, nullptr);
|
|
eglMakeCurrent(g_EglDisplay, g_EglSurface, g_EglSurface, g_EglContext);
|
|
}
|
|
|
|
// Setup Dear ImGui context
|
|
IMGUI_CHECKVERSION();
|
|
ImGui::CreateContext();
|
|
ImGuiIO& io = ImGui::GetIO();
|
|
|
|
// Redirect loading/saving of .ini file to our location.
|
|
// Make sure 'g_IniFilename' persists while we use Dear ImGui.
|
|
g_IniFilename = std::string(app->activity->internalDataPath) + "/imgui.ini";
|
|
io.IniFilename = g_IniFilename.c_str();;
|
|
|
|
// Setup Dear ImGui style
|
|
ImGui::StyleColorsDark();
|
|
//ImGui::StyleColorsLight();
|
|
|
|
// Setup Platform/Renderer backends
|
|
ImGui_ImplAndroid_Init(g_App->window, app->activity->assetManager, app->activity->clazz);
|
|
ImGui_ImplOpenGL3_Init("#version 300 es");
|
|
|
|
// Setup scaling
|
|
ImGui_ImplAndroid_DisplayMetrics display_metrics;
|
|
ImGui_ImplAndroid_GetDisplayMetrics(&display_metrics);
|
|
float main_scale = display_metrics.Density > 0.0f ? display_metrics.Density : 2.0f;
|
|
ImGuiStyle& style = ImGui::GetStyle();
|
|
style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
|
|
style.FontScaleDpi = main_scale; // Set initial font scale.
|
|
|
|
// Load Fonts
|
|
// - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
|
|
// This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
|
|
// - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
|
|
// - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit).
|
|
// - Read 'docs/FONTS.md' for more instructions and details.
|
|
// - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
|
|
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
|
|
// - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them.
|
|
//style.FontSizeBase = 20.0f;
|
|
//io.Fonts->AddFontDefaultVector();
|
|
//io.Fonts->AddFontDefaultBitmap();
|
|
|
|
// Important: when calling AddFontFromMemoryTTF(), ownership of font_data is transferred by Dear ImGui by default (deleted is handled by Dear ImGui), unless we set FontDataOwnedByAtlas=false in ImFontConfig
|
|
//void* font_data;
|
|
//int font_data_size;
|
|
//ImFont* font;
|
|
//font_data_size = GetAssetData("segoeui.ttf", &font_data);
|
|
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
|
|
//IM_ASSERT(font != nullptr);
|
|
//font_data_size = GetAssetData("DroidSans.ttf", &font_data);
|
|
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
|
|
//IM_ASSERT(font != nullptr);
|
|
//font_data_size = GetAssetData("Roboto-Medium.ttf", &font_data);
|
|
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
|
|
//IM_ASSERT(font != nullptr);
|
|
//font_data_size = GetAssetData("Cousine-Regular.ttf", &font_data);
|
|
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
|
|
//IM_ASSERT(font != nullptr);
|
|
//font_data_size = GetAssetData("ArialUni.ttf", &font_data);
|
|
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
|
|
//IM_ASSERT(font != nullptr);
|
|
|
|
g_Initialized = true;
|
|
}
|
|
|
|
void MainLoopStep()
|
|
{
|
|
ImGuiIO& io = ImGui::GetIO();
|
|
if (g_EglDisplay == EGL_NO_DISPLAY)
|
|
return;
|
|
|
|
// Our state
|
|
// (we use static, which essentially makes the variable globals, as a convenience to keep the example code easy to follow)
|
|
static bool show_demo_window = true;
|
|
static bool show_another_window = false;
|
|
static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
|
|
|
|
// Start the Dear ImGui frame
|
|
ImGui_ImplOpenGL3_NewFrame();
|
|
ImGui_ImplAndroid_NewFrame();
|
|
ImGui::NewFrame();
|
|
|
|
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
|
|
if (show_demo_window)
|
|
ImGui::ShowDemoWindow(&show_demo_window);
|
|
|
|
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
|
|
{
|
|
static float f = 0.0f;
|
|
static int counter = 0;
|
|
|
|
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
|
|
|
|
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
|
|
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
|
|
ImGui::Checkbox("Another Window", &show_another_window);
|
|
|
|
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
|
|
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
|
|
|
|
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
|
|
counter++;
|
|
ImGui::SameLine();
|
|
ImGui::Text("counter = %d", counter);
|
|
|
|
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
|
|
ImGui::End();
|
|
}
|
|
|
|
// 3. Show another simple window.
|
|
if (show_another_window)
|
|
{
|
|
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
|
|
ImGui::Text("Hello from another window!");
|
|
if (ImGui::Button("Close Me"))
|
|
show_another_window = false;
|
|
ImGui::End();
|
|
}
|
|
|
|
// Rendering
|
|
ImGui::Render();
|
|
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
|
|
glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
|
|
glClear(GL_COLOR_BUFFER_BIT);
|
|
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
|
|
eglSwapBuffers(g_EglDisplay, g_EglSurface);
|
|
}
|
|
|
|
void Shutdown()
|
|
{
|
|
if (!g_Initialized)
|
|
return;
|
|
|
|
// Cleanup
|
|
ImGui_ImplOpenGL3_Shutdown();
|
|
ImGui_ImplAndroid_Shutdown();
|
|
ImGui::DestroyContext();
|
|
|
|
if (g_EglDisplay != EGL_NO_DISPLAY)
|
|
{
|
|
eglMakeCurrent(g_EglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
|
|
|
if (g_EglContext != EGL_NO_CONTEXT)
|
|
eglDestroyContext(g_EglDisplay, g_EglContext);
|
|
|
|
if (g_EglSurface != EGL_NO_SURFACE)
|
|
eglDestroySurface(g_EglDisplay, g_EglSurface);
|
|
|
|
eglTerminate(g_EglDisplay);
|
|
}
|
|
|
|
g_EglDisplay = EGL_NO_DISPLAY;
|
|
g_EglContext = EGL_NO_CONTEXT;
|
|
g_EglSurface = EGL_NO_SURFACE;
|
|
ANativeWindow_release(g_App->window);
|
|
|
|
g_Initialized = false;
|
|
}
|
|
|
|
// Helper to retrieve data placed into the assets/ directory (android/app/src/main/assets)
|
|
static int GetAssetData(const char* filename, void** outData)
|
|
{
|
|
int num_bytes = 0;
|
|
AAsset* asset_descriptor = AAssetManager_open(g_App->activity->assetManager, filename, AASSET_MODE_BUFFER);
|
|
if (asset_descriptor)
|
|
{
|
|
num_bytes = AAsset_getLength(asset_descriptor);
|
|
*outData = IM_ALLOC(num_bytes);
|
|
int64_t num_bytes_read = AAsset_read(asset_descriptor, *outData, num_bytes);
|
|
AAsset_close(asset_descriptor);
|
|
IM_ASSERT(num_bytes_read == num_bytes);
|
|
}
|
|
return num_bytes;
|
|
}
|