Imgui: How to get a correct CursorPos in an InputText callback

Created on 7 Sep 2016  路  4Comments  路  Source: ocornut/imgui

I want to implement [a-zA-Z][a-zA-Z0-9_]* pattern filter in ImGui::TextInput. But, data->CursorPos returns 0 every time.

my callback body:

{
  ImWchar c = data->EventChar;

  if ( c >= 'a' and c < 'z' )
    return 0;
  if ( c >= 'A' and c < 'Z' )
    return 0;

  // for debug
  std::cerr << data->CursorPos;

  // false every time
  if ( data->CursorPos > 0 )
  {
    if ( c == '_' )
      return 0;
    if ( c >= '0' and c <= '9' )
      return 0;
  }
}

How can I get a correct CursorPos?

enhancement

All 4 comments

It is a little awkward but the current system doesn't pass the CursorPos for the CharFilter event because it is a costly operation to calculate it (as we have to do a wchar_t->utf-8 conversion pass).
This is will be fixed when we rewrite stb_textedit.h to allow for utf-8 processing.

Also there's another issue to work-around from because clipboard pasting apply the filter because pasting as one operation and therefore you wouldn't have a valid cursor position in the preprocessing loop.

For now a hacky workaround (but position won't be correct when pasting multiple characters from clipboard)

#include <imgui_internal.h>
ImGuiTextEditState& edit_state = GImGui->InputTextState;
callback_data.CursorPos = ImTextCountUtf8BytesFromStr(edit_state.Text.Data, edit_state.Text.Data + edit_state.StbState.cursor);

Or, you can get CursorPos by setting the ImGuiInputTextFlags_CallbackAlways flag but you will get it after the filtering callback. You might cache it from previous frame.

Thank you for tricks and commentary of the situation. :+1:

Thanks, kept note and will add it when InputText gets reworked.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bizehao picture bizehao  路  3Comments

spaderthomas picture spaderthomas  路  3Comments

DarkLinux picture DarkLinux  路  3Comments

BlackWatersInc picture BlackWatersInc  路  3Comments

NPatch picture NPatch  路  3Comments