/ deps / AImGUI / modules / ANativeWindowCreator.h
ANativeWindowCreator.h
   1  /*
   2   * MIT License
   3   *
   4   * Copyright (c) 2023 Bzi-Han
   5   * Project: https://github.com/Bzi-Han/AndroidSurfaceImgui
   6   *
   7   * Permission is hereby granted, free of charge, to any person obtaining a copy
   8   * of this software and associated documentation files (the "Software"), to deal
   9   * in the Software without restriction, including without limitation the rights
  10   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11   * copies of the Software, and to permit persons to whom the Software is
  12   * furnished to do so, subject to the following conditions:
  13   *
  14   * The above copyright notice and this permission notice shall be included in
  15   * all copies or substantial portions of the Software.
  16   *
  17   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23   * SOFTWARE.
  24   */
  25  
  26  #ifndef A_NATIVE_WINDOW_CREATOR_H // !A_NATIVE_WINDOW_CREATOR_H
  27  #define A_NATIVE_WINDOW_CREATOR_H
  28  
  29  #include <dlfcn.h>
  30  #include <sys/system_properties.h>
  31  
  32  #include <android/log.h>
  33  #include <android/native_window.h>
  34  
  35  #include <cstdint>
  36  #include <memory>
  37  #include <string>
  38  #include <string_view>
  39  #include <array>
  40  #include <vector>
  41  #include <unordered_map>
  42  #include <unordered_set>
  43  
  44  #ifndef LOGTAG
  45  #define LOGTAG "AImGui"
  46  
  47  #define LOGTAG_DEFINED 1
  48  #endif // !TAG
  49  
  50  #ifndef LogInfo
  51  #define LogInfo(formatter, ...) __android_log_print(ANDROID_LOG_INFO, LOGTAG, formatter __VA_OPT__(, ) __VA_ARGS__)
  52  #define LogDebug(formatter, ...) __android_log_print(ANDROID_LOG_DEBUG, LOGTAG, formatter __VA_OPT__(, ) __VA_ARGS__)
  53  #define LogError(formatter, ...) __android_log_print(ANDROID_LOG_ERROR, LOGTAG, formatter __VA_OPT__(, ) __VA_ARGS__)
  54  
  55  #define LogInfo_DEFINED 1
  56  #endif // !LogInfo
  57  
  58  namespace android::anative_window_creator::detail::types
  59  {
  60      /**
  61       * The following types and structures are adapted from AOSP.
  62       */
  63  
  64      enum class PixelFormat
  65      {
  66          UNKNOWN = 0,
  67          CUSTOM = -4,
  68          TRANSLUCENT = -3,
  69          TRANSPARENT = -2,
  70          OPAQUE = -1,
  71          RGBA_8888 = 1,
  72          RGBX_8888 = 2,
  73          RGB_888 = 3,
  74          RGB_565 = 4,
  75          BGRA_8888 = 5,
  76          RGBA_5551 = 6,
  77          RGBA_4444 = 7,
  78          RGBA_FP16 = 22,
  79          RGBA_1010102 = 43,
  80          R_8 = 0x38,
  81      };
  82  
  83      enum class WindowFlags : uint32_t
  84      { // (keep in sync with SurfaceControl.java)
  85          eHidden = 0x00000004,
  86          eDestroyBackbuffer = 0x00000020,
  87          eSkipScreenshot = 0x00000040,
  88          eSecure = 0x00000080,
  89          eNonPremultiplied = 0x00000100,
  90          eOpaque = 0x00000400,
  91          eProtectedByApp = 0x00000800,
  92          eProtectedByDRM = 0x00001000,
  93          eCursorWindow = 0x00002000,
  94          eNoColorFill = 0x00004000,
  95  
  96          eFXSurfaceBufferQueue = 0x00000000,
  97          eFXSurfaceEffect = 0x00020000,
  98          eFXSurfaceBufferState = 0x00040000,
  99          eFXSurfaceContainer = 0x00080000,
 100          eFXSurfaceMask = 0x000F0000,
 101      };
 102  
 103      enum class MetadataType : uint32_t
 104      {
 105          OWNER_UID = 1,
 106          WINDOW_TYPE = 2,
 107          TASK_ID = 3,
 108          MOUSE_CURSOR = 4,
 109          ACCESSIBILITY_ID = 5,
 110          OWNER_PID = 6,
 111          DEQUEUE_TIME = 7,
 112          GAME_MODE = 8
 113      };
 114  
 115      enum
 116      {
 117          WINDOW_TYPE_DONT_SCREENSHOT = 441731
 118      };
 119  
 120      template <typename any_t>
 121      struct StrongPointer
 122      {
 123          union {
 124              any_t *pointer;
 125              char padding[sizeof(std::max_align_t)];
 126          };
 127  
 128          inline any_t *operator->() const
 129          {
 130              return pointer;
 131          }
 132          inline any_t *get() const
 133          {
 134              return pointer;
 135          }
 136          inline explicit operator bool() const
 137          {
 138              return nullptr != pointer;
 139          }
 140      };
 141  
 142      template <typename enum_t>
 143      constexpr enum_t operator|(enum_t lhs, enum_t rhs)
 144          requires std::is_enum_v<enum_t>
 145      {
 146          using underlying_t = std::underlying_type_t<enum_t>;
 147  
 148          return static_cast<enum_t>(static_cast<underlying_t>(lhs) | static_cast<underlying_t>(rhs));
 149      }
 150  
 151      template <typename enum_t>
 152      constexpr enum_t operator|=(enum_t &lhs, enum_t rhs)
 153          requires std::is_enum_v<enum_t>
 154      {
 155          return (lhs = lhs | rhs);
 156      }
 157  } // namespace android::anative_window_creator::detail::types
 158  
 159  namespace android::anative_window_creator::detail::types::ui
 160  {
 161      /**
 162       * The following types and structures are adapted from AOSP android::ui.
 163       */
 164  
 165      typedef int64_t nsecs_t; // nano-seconds
 166  
 167      enum class Rotation
 168      {
 169          Rotation0 = 0,
 170          Rotation90 = 1,
 171          Rotation180 = 2,
 172          Rotation270 = 3
 173      };
 174  
 175      enum class DisplayType
 176      {
 177          DisplayIdMain = 0,
 178          DisplayIdHdmi = 1
 179      };
 180  
 181      // A LayerStack identifies a Z-ordered group of layers. A layer can only be associated to a single
 182      // LayerStack, but a LayerStack can be associated to multiple displays, mirroring the same content.
 183      struct LayerStack
 184      {
 185          uint32_t id = UINT32_MAX;
 186      };
 187  
 188      // A simple value type representing a two-dimensional size.
 189      struct Size
 190      {
 191          int32_t width = -1;
 192          int32_t height = -1;
 193      };
 194  
 195      // Transactional state of physical or virtual display. Note that libgui defines
 196      // android::DisplayState as a superset of android::ui::DisplayState.
 197      struct DisplayState
 198      {
 199          LayerStack layerStack;
 200          Rotation orientation = Rotation::Rotation0;
 201          Size layerStackSpaceRect;
 202      };
 203  
 204      struct DisplayInfo
 205      {
 206          uint32_t w{0};
 207          uint32_t h{0};
 208          float xdpi{0};
 209          float ydpi{0};
 210          float fps{0};
 211          float density{0};
 212          uint8_t orientation{0};
 213          bool secure{false};
 214          nsecs_t appVsyncOffset{0};
 215          nsecs_t presentationDeadline{0};
 216          uint32_t viewportW{0};
 217          uint32_t viewportH{0};
 218      };
 219  
 220      struct PhysicalDisplayId
 221      {
 222          uint64_t value;
 223      };
 224  } // namespace android::anative_window_creator::detail::types::ui
 225  
 226  namespace android::anative_window_creator::detail::types::apis::libutils
 227  {
 228      namespace generic
 229      {
 230          using RefBase__IncStrong = void (*)(void *thiz, void *id);
 231          using RefBase__DecStrong = void (*)(void *thiz, void *id);
 232  
 233          using String8__Constructor = void *(*)(void *thiz, const char *const string);
 234          using String8__Destructor = void (*)(void *thiz);
 235      } // namespace generic
 236  } // namespace android::anative_window_creator::detail::types::apis::libutils
 237  
 238  namespace android::anative_window_creator::detail::types::apis::libgui
 239  {
 240      namespace v5_v7
 241      {
 242          // SurfaceComposerClient::createSurface(
 243          //         const String8& name,
 244          //         uint32_t w,
 245          //         uint32_t h,
 246          //         PixelFormat format,
 247          //         uint32_t flags)
 248          using SurfaceComposerClient__CreateSurface = StrongPointer<void> (*)(void *thiz, void *name, uint32_t w, uint32_t h, PixelFormat format, WindowFlags flags);
 249  
 250          using SurfaceComposerClient__OpenGlobalTransaction__Static = void (*)();
 251          using SurfaceComposerClient__CloseGlobalTransaction__Static = void (*)(bool synchronous);
 252  
 253          using SurfaceControl__SetLayer = void *(*)(void *thiz, int32_t z);
 254  
 255          // enum {
 256          //     // The API number used to indicate the currently connected producer
 257          //     CURRENTLY_CONNECTED_API = -1,
 258          //
 259          //     // The API number used to indicate that no producer is connected
 260          //     NO_CONNECTED_API        = 0,
 261          // };
 262          using Surface__DisConnect = void *(*)(void *thiz, int api);
 263      } // namespace v5_v7
 264  
 265      namespace v8_v9
 266      {
 267          // SurfaceComposerClient::createSurface(
 268          //         const String8& name,
 269          //         uint32_t w,
 270          //         uint32_t h,
 271          //         PixelFormat format,
 272          //         uint32_t flags,
 273          //         SurfaceControl* parent,
 274          //         uint32_t windowType,
 275          //         uint32_t ownerUid)
 276          using SurfaceComposerClient__CreateSurface = StrongPointer<void> (*)(void *thiz, void *name, uint32_t w, uint32_t h, PixelFormat format, WindowFlags flags, void *parent, uint32_t windowType, uint32_t ownerUid);
 277      } // namespace v8_v9
 278  
 279      namespace v8_v12
 280      {
 281          using SurfaceComposerClient__Transaction__Apply = int32_t (*)(void *thiz, bool synchronous);
 282      } // namespace v8_v12
 283  
 284      namespace v10
 285      {
 286          // SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
 287          //         PixelFormat format, uint32_t flags,
 288          //         SurfaceControl* parent,
 289          //         LayerMetadata metadata)
 290          using SurfaceComposerClient__CreateSurface = StrongPointer<void> (*)(void *thiz, void *name, uint32_t w, uint32_t h, PixelFormat format, WindowFlags flags, void *parent, void *metadata);
 291      } // namespace v10
 292  
 293      namespace v10_v12
 294      {
 295          // SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setInputWindowInfo(
 296          //         const sp<SurfaceControl>& sc,
 297          //         const InputWindowInfo& info)
 298          using SurfaceComposerClient__Transaction__SetInputWindowInfo = void *(*)(void *thiz, StrongPointer<void> &surfaceControl, void *inputWindowInfo);
 299      } // namespace v10_v12
 300  
 301      namespace v11
 302      {
 303          // SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
 304          //         PixelFormat format, uint32_t flags,
 305          //         SurfaceControl* parent,
 306          //         LayerMetadata metadata,
 307          //         uint32_t* outTransformHint)
 308          using SurfaceComposerClient__CreateSurface = StrongPointer<void> (*)(void *thiz, void *name, uint32_t w, uint32_t h, PixelFormat format, WindowFlags flags, void *parent, void *metadata, uint32_t *outTransformHint);
 309      } // namespace v11
 310  
 311      namespace v12_v13
 312      {
 313          // SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
 314          //         PixelFormat format, uint32_t flags,
 315          //         const sp<IBinder>& parentHandle,
 316          //         LayerMetadata metadata,
 317          //         uint32_t* outTransformHint)
 318          using SurfaceComposerClient__CreateSurface = StrongPointer<void> (*)(void *thiz, void *name, uint32_t w, uint32_t h, PixelFormat format, WindowFlags flags, void **parentHandle, void *metadata, uint32_t *outTransformHint);
 319      } // namespace v12_v13
 320  
 321      namespace v13_v15
 322      {
 323          // SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setInputWindowInfo(
 324          //         const sp<SurfaceControl>& sc, const WindowInfo& info)
 325          using SurfaceComposerClient__Transaction__SetInputWindowInfo = void *(*)(void *thiz, StrongPointer<void> &surfaceControl, void *windowInfo);
 326      } // namespace v13_v15
 327  
 328      namespace v13_infinite
 329      {
 330          using SurfaceComposerClient__Transaction__Apply = int32_t (*)(void *thiz, bool synchronous, bool oneWay);
 331      } // namespace v13_infinite
 332  
 333      namespace v14_infinite
 334      {
 335          // SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
 336          //         PixelFormat format, int32_t flags,
 337          //         const sp<IBinder>& parentHandle,
 338          //         LayerMetadata metadata,
 339          //         uint32_t* outTransformHint)
 340          using SurfaceComposerClient__CreateSurface = StrongPointer<void> (*)(void *thiz, void *name, uint32_t w, uint32_t h, PixelFormat format, WindowFlags flags, void **parentHandle, void *metadata, uint32_t *outTransformHint);
 341      } // namespace v14_infinite
 342  
 343      namespace v16_infinite
 344      {
 345          // SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setInputWindowInfo(
 346          //         const sp<SurfaceControl>& sc, sp<WindowInfoHandle> info)
 347          using SurfaceComposerClient__Transaction__SetInputWindowInfo = void *(*)(void *thiz, StrongPointer<void> &surfaceControl, void *windowInfoHandle);
 348      } // namespace v16_infinite
 349  
 350      namespace generic
 351      {
 352          using LayerMetadata__Constructor = void (*)(void *thiz);
 353          using LayerMetadata__SetInt32 = void (*)(void *thiz, MetadataType key, int32_t value);
 354  
 355          using SurfaceComposerClient__Constructor = void *(*)(void *thiz);
 356          using SurfaceComposerClient__MirrorSurface = StrongPointer<void> (*)(void *thiz, void *mirrorFromSurface);
 357          // Static
 358          using SurfaceComposerClient__GetInternalDisplayToken__Static = StrongPointer<void> (*)();
 359          using SurfaceComposerClient__GetBuiltInDisplay__Static = StrongPointer<void> (*)(ui::DisplayType type);
 360          using SurfaceComposerClient__GetDisplayState__Static = int32_t (*)(StrongPointer<void> &display, ui::DisplayState *displayState);
 361          using SurfaceComposerClient__GetDisplayInfo__Static = int32_t (*)(StrongPointer<void> &display, ui::DisplayInfo *displayInfo);
 362          using SurfaceComposerClient__GetPhysicalDisplayIds__Static = std::vector<ui::PhysicalDisplayId> (*)();
 363          using SurfaceComposerClient__GetPhysicalDisplayToken__Static = StrongPointer<void> (*)(ui::PhysicalDisplayId displayId);
 364  
 365          using SurfaceComposerClient__Transaction__CopyConstructor = void *(*)(void *thiz, void *other);
 366          using SurfaceComposerClient__Transaction__Constructor = void *(*)(void *thiz);
 367          using SurfaceComposerClient__Transaction__SetLayer = void *(*)(void *thiz, StrongPointer<void> &surfaceControl, int32_t z);
 368          using SurfaceComposerClient__Transaction__SetTrustedOverlay = void *(*)(void *thiz, StrongPointer<void> &surfaceControl, bool isTrustedOverlay);
 369          using SurfaceComposerClient__Transaction__SetLayerStack = void *(*)(void *thiz, StrongPointer<void> &surfaceControl, uint32_t layerStack);
 370          using SurfaceComposerClient__Transaction__Show = void *(*)(void *thiz, StrongPointer<void> &surfaceControl);
 371          using SurfaceComposerClient__Transaction__Hide = void *(*)(void *thiz, StrongPointer<void> &surfaceControl);
 372          using SurfaceComposerClient__Transaction__Reparent = void *(*)(void *thiz, StrongPointer<void> &surfaceControl, StrongPointer<void> &newParentHandle);
 373          using SurfaceComposerClient__Transaction__SetMatrix = void *(*)(void *thiz, StrongPointer<void> &surfaceControl, float dsdx, float dtdx, float dtdy, float dsdy);
 374          using SurfaceComposerClient__Transaction__SetPosition = void *(*)(void *thiz, StrongPointer<void> &surfaceControl, float x, float y);
 375  
 376          using SurfaceControl__GetSurface = StrongPointer<void> (*)(void *thiz);
 377          using SurfaceControl__DisConnect = void (*)(void *thiz);
 378          using SurfaceControl__GetParentingLayer = StrongPointer<void> (*)(void *thiz);
 379      } // namespace generic
 380  } // namespace android::anative_window_creator::detail::types::apis::libgui
 381  
 382  #include "Signatures.h"
 383  #include <KittyScanner.hpp>
 384  #include <unistd.h>
 385  
 386  namespace android::anative_window_creator::detail::types::apis
 387  {
 388      struct ApiDescriptor
 389      {
 390          size_t minVersion;
 391          size_t maxVersion;
 392          void **storeToTarget;
 393          const signatures::MethodSignature *signature;
 394  
 395          bool IsSupported(size_t currentVersion) const
 396          {
 397              return currentVersion >= minVersion && currentVersion <= maxVersion;
 398          }
 399      };
 400  } // namespace android::anative_window_creator::detail::types::apis
 401  
 402  namespace android::anative_window_creator::detail::apis
 403  {
 404      namespace libutils
 405      {
 406          struct RefBase
 407          {
 408              struct ApiTable
 409              {
 410                  void *IncStrong;
 411                  void *DecStrong;
 412              };
 413  
 414              inline static ApiTable Api;
 415          };
 416  
 417          struct String8
 418          {
 419              struct ApiTable
 420              {
 421                  void *Constructor;
 422                  void *Destructor;
 423              };
 424  
 425              inline static ApiTable Api;
 426          };
 427      } // namespace libutils
 428  
 429      namespace libgui
 430      {
 431          struct LayerMetadata
 432          {
 433              struct ApiTable
 434              {
 435                  void *Constructor;
 436                  void *SetInt32;
 437              };
 438  
 439              inline static ApiTable Api;
 440          };
 441  
 442          struct SurfaceComposerClient
 443          {
 444              struct Transaction;
 445  
 446              struct ApiTable
 447              {
 448                  void *Constructor;
 449                  void *CreateSurface;
 450                  void *MirrorSurface;
 451                  void *GetInternalDisplayToken;
 452                  void *GetBuiltInDisplay;
 453                  void *GetDisplayState;
 454                  void *GetDisplayInfo;
 455                  void *GetPhysicalDisplayIds;
 456                  void *GetPhysicalDisplayToken;
 457  
 458                  void *OpenGlobalTransaction;
 459                  void *CloseGlobalTransaction;
 460              };
 461  
 462              inline static ApiTable Api;
 463          };
 464  
 465          struct SurfaceComposerClient::Transaction
 466          {
 467              struct ApiTable
 468              {
 469                  void *CopyConstructor;
 470                  void *Constructor;
 471                  void *SetLayer;
 472                  void *SetTrustedOverlay;
 473                  void *SetLayerStack;
 474                  void *Show;
 475                  void *Hide;
 476                  void *Reparent;
 477                  void *SetMatrix;
 478                  void *SetPosition;
 479                  void *SetInputWindowInfo;
 480                  void *Apply;
 481              };
 482  
 483              inline static ApiTable Api;
 484          };
 485  
 486          struct SurfaceControl
 487          {
 488              struct ApiTable
 489              {
 490                  void *GetSurface;
 491                  void *DisConnect;
 492                  void *GetParentingLayer;
 493  
 494                  void *SetLayer;
 495              };
 496  
 497              inline static ApiTable Api;
 498          };
 499  
 500          struct Surface
 501          {
 502              struct ApiTable
 503              {
 504                  void *DisConnect;
 505              };
 506  
 507              inline static ApiTable Api;
 508          };
 509      } // namespace libgui
 510  } // namespace android::anative_window_creator::detail::apis
 511  
 512  namespace android::anative_window_creator::detail::compat
 513  {
 514      constexpr size_t SupportedMinVersion = 5;
 515  
 516      template <size_t length>
 517      struct ApiInvokeDescriptor
 518      {
 519          size_t api;
 520          size_t version;
 521  
 522          consteval size_t DataHash(const std::string_view &data) const
 523          {
 524              constexpr size_t fnvOffsetBasis = 0x811C9DC5ull;
 525              constexpr size_t fnvPrime = 0x1000193ull;
 526              size_t hash = fnvOffsetBasis;
 527  
 528              for (size_t i = 0; i < data.size(); ++i)
 529              {
 530                  hash ^= static_cast<size_t>(data[i]);
 531                  hash *= fnvPrime;
 532              }
 533  
 534              return hash;
 535          }
 536  
 537          consteval bool operator==(const char *rhs) const
 538          {
 539              return api == DataHash(rhs);
 540          }
 541  
 542          consteval ApiInvokeDescriptor(const char (&apiInvokeName)[length])
 543          {
 544              const std::string_view apiInvokeNameView{apiInvokeName};
 545              const auto invokeNameDelimiter = apiInvokeNameView.find("@");
 546  
 547              if (std::string_view::npos == invokeNameDelimiter)
 548              {
 549                  api = DataHash(apiInvokeName);
 550                  version = SupportedMinVersion;
 551              }
 552              else
 553              {
 554                  if ('v' != apiInvokeNameView[invokeNameDelimiter + 1])
 555                      throw std::invalid_argument("Invalid version string, must start with 'v'");
 556  
 557                  const auto invokeName = apiInvokeNameView.substr(0, invokeNameDelimiter);
 558                  const auto invokeVersion = apiInvokeNameView.substr(invokeNameDelimiter + 2);
 559  
 560                  api = DataHash(invokeName);
 561  
 562                  version = 0;
 563                  for (char c : invokeVersion)
 564                  {
 565                      if (c < '0' || c > '9')
 566                          throw std::invalid_argument("Invalid version string, must be digits only");
 567  
 568                      version = version * 10 + (c - '0');
 569                  }
 570              }
 571          }
 572      };
 573  
 574      template <ApiInvokeDescriptor descriptor>
 575      constexpr auto ApiInvoker()
 576      {
 577          // libutils
 578          if constexpr ("RefBase::IncStrong" == descriptor)
 579              return reinterpret_cast<types::apis::libutils::generic::RefBase__IncStrong>(apis::libutils::RefBase::Api.IncStrong);
 580          if constexpr ("RefBase::DecStrong" == descriptor)
 581              return reinterpret_cast<types::apis::libutils::generic::RefBase__DecStrong>(apis::libutils::RefBase::Api.DecStrong);
 582  
 583          if constexpr ("String8::Constructor" == descriptor)
 584              return reinterpret_cast<types::apis::libutils::generic::String8__Constructor>(apis::libutils::String8::Api.Constructor);
 585          if constexpr ("String8::Destructor" == descriptor)
 586              return reinterpret_cast<types::apis::libutils::generic::String8__Destructor>(apis::libutils::String8::Api.Destructor);
 587  
 588          // libgui
 589          if constexpr ("LayerMetadata::Constructor" == descriptor)
 590              return reinterpret_cast<types::apis::libgui::generic::LayerMetadata__Constructor>(apis::libgui::LayerMetadata::Api.Constructor);
 591          if constexpr ("LayerMetadata::SetInt32" == descriptor)
 592              return reinterpret_cast<types::apis::libgui::generic::LayerMetadata__SetInt32>(apis::libgui::LayerMetadata::Api.SetInt32);
 593  
 594          if constexpr ("SurfaceControl::GetSurface" == descriptor)
 595              return reinterpret_cast<types::apis::libgui::generic::SurfaceControl__GetSurface>(apis::libgui::SurfaceControl::Api.GetSurface);
 596          if constexpr ("SurfaceControl::DisConnect" == descriptor)
 597              return reinterpret_cast<types::apis::libgui::generic::SurfaceControl__DisConnect>(apis::libgui::SurfaceControl::Api.DisConnect);
 598          if constexpr ("SurfaceControl::GetParentingLayer" == descriptor)
 599              return reinterpret_cast<types::apis::libgui::generic::SurfaceControl__GetParentingLayer>(apis::libgui::SurfaceControl::Api.GetParentingLayer);
 600          if constexpr ("SurfaceControl::SetLayer" == descriptor)
 601              return reinterpret_cast<types::apis::libgui::v5_v7::SurfaceControl__SetLayer>(apis::libgui::SurfaceControl::Api.SetLayer);
 602  
 603          if constexpr ("Surface::DisConnect" == descriptor)
 604              return reinterpret_cast<types::apis::libgui::v5_v7::Surface__DisConnect>(apis::libgui::Surface::Api.DisConnect);
 605  
 606          if constexpr ("SurfaceComposerClient::Transaction::Constructor" == descriptor)
 607          {
 608              if constexpr (12 > descriptor.version)
 609                  return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__CopyConstructor>(apis::libgui::SurfaceComposerClient::Transaction::Api.CopyConstructor);
 610              else
 611                  return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__Constructor>(apis::libgui::SurfaceComposerClient::Transaction::Api.Constructor);
 612          }
 613          if constexpr ("SurfaceComposerClient::Transaction::SetLayer" == descriptor)
 614              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__SetLayer>(apis::libgui::SurfaceComposerClient::Transaction::Api.SetLayer);
 615          if constexpr ("SurfaceComposerClient::Transaction::SetLayerStack" == descriptor)
 616              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__SetLayerStack>(apis::libgui::SurfaceComposerClient::Transaction::Api.SetLayerStack);
 617          if constexpr ("SurfaceComposerClient::Transaction::SetTrustedOverlay" == descriptor)
 618              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__SetTrustedOverlay>(apis::libgui::SurfaceComposerClient::Transaction::Api.SetTrustedOverlay);
 619          if constexpr ("SurfaceComposerClient::Transaction::Show" == descriptor)
 620              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__Show>(apis::libgui::SurfaceComposerClient::Transaction::Api.Show);
 621          if constexpr ("SurfaceComposerClient::Transaction::Hide" == descriptor)
 622              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__Hide>(apis::libgui::SurfaceComposerClient::Transaction::Api.Hide);
 623          if constexpr ("SurfaceComposerClient::Transaction::Reparent" == descriptor)
 624              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__Reparent>(apis::libgui::SurfaceComposerClient::Transaction::Api.Reparent);
 625          if constexpr ("SurfaceComposerClient::Transaction::SetMatrix" == descriptor)
 626              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__SetMatrix>(apis::libgui::SurfaceComposerClient::Transaction::Api.SetMatrix);
 627          if constexpr ("SurfaceComposerClient::Transaction::SetPosition" == descriptor)
 628              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Transaction__SetPosition>(apis::libgui::SurfaceComposerClient::Transaction::Api.SetPosition);
 629          if constexpr ("SurfaceComposerClient::Transaction::SetInputWindowInfo" == descriptor)
 630          {
 631              if constexpr (10 <= descriptor.version && 12 >= descriptor.version)
 632                  return reinterpret_cast<types::apis::libgui::v10_v12::SurfaceComposerClient__Transaction__SetInputWindowInfo>(apis::libgui::SurfaceComposerClient::Transaction::Api.SetInputWindowInfo);
 633              else if constexpr (13 <= descriptor.version && 15 >= descriptor.version)
 634                  return reinterpret_cast<types::apis::libgui::v13_v15::SurfaceComposerClient__Transaction__SetInputWindowInfo>(apis::libgui::SurfaceComposerClient::Transaction::Api.SetInputWindowInfo);
 635              else if constexpr (16 <= descriptor.version)
 636                  return reinterpret_cast<types::apis::libgui::v16_infinite::SurfaceComposerClient__Transaction__SetInputWindowInfo>(apis::libgui::SurfaceComposerClient::Transaction::Api.SetInputWindowInfo);
 637          }
 638          if constexpr ("SurfaceComposerClient::Transaction::Apply" == descriptor)
 639          {
 640              if constexpr (8 <= descriptor.version && 12 >= descriptor.version)
 641                  return reinterpret_cast<types::apis::libgui::v8_v12::SurfaceComposerClient__Transaction__Apply>(apis::libgui::SurfaceComposerClient::Transaction::Api.Apply);
 642              else if constexpr (13 <= descriptor.version)
 643                  return reinterpret_cast<types::apis::libgui::v13_infinite::SurfaceComposerClient__Transaction__Apply>(apis::libgui::SurfaceComposerClient::Transaction::Api.Apply);
 644          }
 645  
 646          if constexpr ("SurfaceComposerClient::Constructor" == descriptor)
 647              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__Constructor>(apis::libgui::SurfaceComposerClient::Api.Constructor);
 648          if constexpr ("SurfaceComposerClient::CreateSurface" == descriptor)
 649          {
 650              if constexpr (5 <= descriptor.version && 7 >= descriptor.version)
 651                  return reinterpret_cast<types::apis::libgui::v5_v7::SurfaceComposerClient__CreateSurface>(apis::libgui::SurfaceComposerClient::Api.CreateSurface);
 652              else if constexpr (8 <= descriptor.version && 9 >= descriptor.version)
 653                  return reinterpret_cast<types::apis::libgui::v8_v9::SurfaceComposerClient__CreateSurface>(apis::libgui::SurfaceComposerClient::Api.CreateSurface);
 654              else if constexpr (10 == descriptor.version)
 655                  return reinterpret_cast<types::apis::libgui::v10::SurfaceComposerClient__CreateSurface>(apis::libgui::SurfaceComposerClient::Api.CreateSurface);
 656              else if constexpr (11 == descriptor.version)
 657                  return reinterpret_cast<types::apis::libgui::v11::SurfaceComposerClient__CreateSurface>(apis::libgui::SurfaceComposerClient::Api.CreateSurface);
 658              else if constexpr (12 <= descriptor.version && 13 >= descriptor.version)
 659                  return reinterpret_cast<types::apis::libgui::v12_v13::SurfaceComposerClient__CreateSurface>(apis::libgui::SurfaceComposerClient::Api.CreateSurface);
 660              else if constexpr (14 <= descriptor.version)
 661                  return reinterpret_cast<types::apis::libgui::v14_infinite::SurfaceComposerClient__CreateSurface>(apis::libgui::SurfaceComposerClient::Api.CreateSurface);
 662          }
 663          if constexpr ("SurfaceComposerClient::MirrorSurface" == descriptor)
 664              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__MirrorSurface>(apis::libgui::SurfaceComposerClient::Api.MirrorSurface);
 665  
 666          if constexpr ("SurfaceComposerClient::GetBuiltInDisplay" == descriptor)
 667              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__GetBuiltInDisplay__Static>(apis::libgui::SurfaceComposerClient::Api.GetBuiltInDisplay);
 668          if constexpr ("SurfaceComposerClient::GetInternalDisplayToken" == descriptor)
 669              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__GetInternalDisplayToken__Static>(apis::libgui::SurfaceComposerClient::Api.GetInternalDisplayToken);
 670          if constexpr ("SurfaceComposerClient::GetPhysicalDisplayIds" == descriptor)
 671              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__GetPhysicalDisplayIds__Static>(apis::libgui::SurfaceComposerClient::Api.GetPhysicalDisplayIds);
 672          if constexpr ("SurfaceComposerClient::GetPhysicalDisplayToken" == descriptor)
 673              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__GetPhysicalDisplayToken__Static>(apis::libgui::SurfaceComposerClient::Api.GetPhysicalDisplayToken);
 674          if constexpr ("SurfaceComposerClient::GetDisplayState" == descriptor)
 675              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__GetDisplayState__Static>(apis::libgui::SurfaceComposerClient::Api.GetDisplayState);
 676          if constexpr ("SurfaceComposerClient::GetDisplayInfo" == descriptor)
 677              return reinterpret_cast<types::apis::libgui::generic::SurfaceComposerClient__GetDisplayInfo__Static>(apis::libgui::SurfaceComposerClient::Api.GetDisplayInfo);
 678  
 679          if constexpr ("SurfaceComposerClient::OpenGlobalTransaction" == descriptor)
 680              return reinterpret_cast<types::apis::libgui::v5_v7::SurfaceComposerClient__OpenGlobalTransaction__Static>(apis::libgui::SurfaceComposerClient::Api.OpenGlobalTransaction);
 681          if constexpr ("SurfaceComposerClient::CloseGlobalTransaction" == descriptor)
 682              return reinterpret_cast<types::apis::libgui::v5_v7::SurfaceComposerClient__CloseGlobalTransaction__Static>(apis::libgui::SurfaceComposerClient::Api.CloseGlobalTransaction);
 683      }
 684  
 685  } // namespace android::anative_window_creator::detail::compat
 686  
 687  namespace android::anative_window_creator::detail::compat
 688  {
 689      // NOTE: No default implementation
 690      extern size_t SystemVersion;
 691  
 692      struct String8
 693      {
 694          char data[1024];
 695  
 696          String8(const char *const string)
 697          {
 698              ApiInvoker<"String8::Constructor">()(data, string);
 699          }
 700  
 701          ~String8()
 702          {
 703              ApiInvoker<"String8::Destructor">()(data);
 704          }
 705  
 706          operator void *()
 707          {
 708              return reinterpret_cast<void *>(data);
 709          }
 710      };
 711  
 712      struct LayerMetadata
 713      {
 714          char data[1024];
 715  
 716          LayerMetadata()
 717          {
 718              if (9 < SystemVersion)
 719                  ApiInvoker<"LayerMetadata::Constructor@v10">()(data);
 720          }
 721  
 722          void SetInt32(types::MetadataType key, int32_t value)
 723          {
 724              if (9 < SystemVersion)
 725                  ApiInvoker<"LayerMetadata::SetInt32@v10">()(data, key, value);
 726          }
 727  
 728          operator void *()
 729          {
 730              if (9 < SystemVersion)
 731                  return reinterpret_cast<void *>(data);
 732              else
 733                  return nullptr;
 734          }
 735      };
 736  
 737      struct Surface
 738      {
 739      };
 740  
 741      struct SurfaceControl
 742      {
 743          void *data;
 744          int32_t width, height;
 745          bool skipScreenshot;
 746  
 747          SurfaceControl(void *data = nullptr)
 748              : data(data),
 749                width(0),
 750                height(0),
 751                skipScreenshot(false)
 752          {
 753          }
 754          SurfaceControl(void *data, int32_t width, int32_t height, bool skipScreenshot)
 755              : data(data),
 756                width(width),
 757                height(height),
 758                skipScreenshot(skipScreenshot)
 759          {
 760          }
 761  
 762          operator bool() const
 763          {
 764              return nullptr != data;
 765          }
 766  
 767          operator types::StrongPointer<void> &()
 768          {
 769              static types::StrongPointer<void> result;
 770  
 771              result.pointer = data;
 772  
 773              return result;
 774          }
 775  
 776          Surface *GetSurface()
 777          {
 778              if (nullptr == data)
 779                  return nullptr;
 780  
 781              auto result = ApiInvoker<"SurfaceControl::GetSurface">()(data);
 782  
 783              return reinterpret_cast<Surface *>(reinterpret_cast<size_t>(result.pointer) + sizeof(std::max_align_t) / 2);
 784          }
 785  
 786          types::StrongPointer<void> GetParentingLayer()
 787          {
 788              if (nullptr == data)
 789                  return {};
 790  
 791              if (12 > SystemVersion)
 792              {
 793                  types::StrongPointer<void> result;
 794  
 795                  result.pointer = data;
 796  
 797                  return result;
 798              }
 799  
 800              return ApiInvoker<"SurfaceControl::GetParentingLayer">()(data);
 801          }
 802  
 803          void DisConnect()
 804          {
 805              if (nullptr == data)
 806                  return;
 807  
 808              ApiInvoker<"SurfaceControl::DisConnect">()(data);
 809          }
 810  
 811          void SetLayer(int32_t z)
 812          {
 813              if (nullptr == data || 8 < SystemVersion)
 814                  return;
 815  
 816              ApiInvoker<"SurfaceControl::SetLayer@v8">()(data, z);
 817          }
 818  
 819          void DestroySurface(Surface *surface)
 820          {
 821              if (nullptr == data || nullptr == surface)
 822                  return;
 823  
 824              ApiInvoker<"RefBase::DecStrong">()(reinterpret_cast<Surface *>(reinterpret_cast<size_t>(surface) - sizeof(std::max_align_t) / 2), this);
 825              if (7 > SystemVersion)
 826                  ApiInvoker<"Surface::DisConnect@v6">()(reinterpret_cast<Surface *>(reinterpret_cast<size_t>(surface) - sizeof(std::max_align_t) / 2), -1);
 827              else
 828                  DisConnect();
 829              ApiInvoker<"RefBase::DecStrong">()(data, this);
 830          }
 831      };
 832  
 833      struct SurfaceComposerClientTransaction
 834      {
 835          char data[1024];
 836  
 837          SurfaceComposerClientTransaction()
 838          {
 839              if (12 > SystemVersion)
 840                  ApiInvoker<"SurfaceComposerClient::Transaction::Constructor@v11">()(data, data);
 841              else
 842                  ApiInvoker<"SurfaceComposerClient::Transaction::Constructor@v12">()(data);
 843          }
 844  
 845          void *SetLayer(types::StrongPointer<void> &surfaceControl, int32_t z)
 846          {
 847              return ApiInvoker<"SurfaceComposerClient::Transaction::SetLayer">()(data, surfaceControl, z);
 848          }
 849  
 850          void *SetLayerStack(types::StrongPointer<void> &surfaceControl, uint32_t layerStack)
 851          {
 852              return ApiInvoker<"SurfaceComposerClient::Transaction::SetLayerStack">()(data, surfaceControl, layerStack);
 853          }
 854  
 855          void *SetTrustedOverlay(types::StrongPointer<void> &surfaceControl, bool isTrustedOverlay)
 856          {
 857              return ApiInvoker<"SurfaceComposerClient::Transaction::SetTrustedOverlay">()(data, surfaceControl, isTrustedOverlay);
 858          }
 859  
 860          void Show(types::StrongPointer<void> &surfaceControl)
 861          {
 862              ApiInvoker<"SurfaceComposerClient::Transaction::Show">()(data, surfaceControl);
 863          }
 864  
 865          void Hide(types::StrongPointer<void> &surfaceControl)
 866          {
 867              ApiInvoker<"SurfaceComposerClient::Transaction::Hide">()(data, surfaceControl);
 868          }
 869  
 870          void Reparent(types::StrongPointer<void> &surfaceControl, types::StrongPointer<void> &newParentHandle)
 871          {
 872              ApiInvoker<"SurfaceComposerClient::Transaction::Reparent">()(data, surfaceControl, newParentHandle);
 873          }
 874  
 875          void SetMatrix(types::StrongPointer<void> &surfaceControl, float dsdx, float dtdx, float dsdy, float dtdy)
 876          {
 877              ApiInvoker<"SurfaceComposerClient::Transaction::SetMatrix">()(data, surfaceControl, dsdx, dtdx, dsdy, dtdy);
 878          }
 879  
 880          void SetPosition(types::StrongPointer<void> &surfaceControl, float x, float y)
 881          {
 882              ApiInvoker<"SurfaceComposerClient::Transaction::SetPosition">()(data, surfaceControl, x, y);
 883          }
 884  
 885          void SetInputWindowInfo(types::StrongPointer<void> &surfaceControl, void *windowInfo)
 886          {
 887              ApiInvoker<"SurfaceComposerClient::Transaction::SetInputWindowInfo@v10">()(data, surfaceControl, windowInfo);
 888          }
 889  
 890          int32_t Apply(bool synchronous, bool oneWay)
 891          {
 892              if (13 > SystemVersion)
 893                  return ApiInvoker<"SurfaceComposerClient::Transaction::Apply@v12">()(data, synchronous);
 894              else
 895                  return ApiInvoker<"SurfaceComposerClient::Transaction::Apply@v13">()(data, synchronous, oneWay);
 896          }
 897      };
 898  
 899      struct SurfaceComposerClient
 900      {
 901          char data[1024];
 902  
 903          SurfaceComposerClient()
 904          {
 905              ApiInvoker<"SurfaceComposerClient::Constructor">()(data);
 906              ApiInvoker<"RefBase::IncStrong">()(data, this);
 907          }
 908  
 909          SurfaceControl CreateSurface(const char *name, int32_t width, int32_t height, types::WindowFlags windowFlags = {}, bool skipScreenshot = false)
 910          {
 911              static void *parentHandle = nullptr;
 912  
 913              parentHandle = nullptr;
 914              String8 windowName(name);
 915              types::PixelFormat pixelFormat = types::PixelFormat::RGBA_8888;
 916              LayerMetadata layerMetadata{};
 917  
 918              types::StrongPointer<void> result{};
 919              switch (SystemVersion)
 920              {
 921              case 5:
 922              case 6:
 923              case 7:
 924              {
 925                  result = ApiInvoker<"SurfaceComposerClient::CreateSurface@v7">()(data, windowName, width, height, pixelFormat, windowFlags);
 926                  break;
 927              }
 928              case 8:
 929              case 9:
 930              {
 931                  uint32_t windowType = skipScreenshot ? types::WINDOW_TYPE_DONT_SCREENSHOT : 0;
 932  
 933                  result = ApiInvoker<"SurfaceComposerClient::CreateSurface@v9">()(data, windowName, width, height, pixelFormat, windowFlags, parentHandle, windowType, 0);
 934                  break;
 935              }
 936              case 10:
 937              {
 938                  if (skipScreenshot)
 939                      layerMetadata.SetInt32(types::MetadataType::WINDOW_TYPE, types::WINDOW_TYPE_DONT_SCREENSHOT);
 940  
 941                  result = ApiInvoker<"SurfaceComposerClient::CreateSurface@v10">()(data, windowName, width, height, pixelFormat, windowFlags, parentHandle, layerMetadata);
 942                  break;
 943              }
 944              case 11:
 945              {
 946                  if (skipScreenshot)
 947                      layerMetadata.SetInt32(types::MetadataType::WINDOW_TYPE, types::WINDOW_TYPE_DONT_SCREENSHOT);
 948  
 949                  result = ApiInvoker<"SurfaceComposerClient::CreateSurface@v11">()(data, windowName, width, height, pixelFormat, windowFlags, parentHandle, layerMetadata, nullptr);
 950                  break;
 951              }
 952              case 12:
 953              case 13:
 954              {
 955                  using types::operator|=;
 956  
 957                  if (skipScreenshot)
 958                      windowFlags |= types::WindowFlags::eSkipScreenshot;
 959  
 960                  result = ApiInvoker<"SurfaceComposerClient::CreateSurface@v13">()(data, windowName, width, height, pixelFormat, windowFlags, &parentHandle, layerMetadata, nullptr);
 961              }
 962              default:
 963              {
 964                  using types::operator|=;
 965  
 966                  if (skipScreenshot)
 967                      windowFlags |= types::WindowFlags::eSkipScreenshot;
 968  
 969                  result = ApiInvoker<"SurfaceComposerClient::CreateSurface@v14">()(data, windowName, width, height, pixelFormat, windowFlags, &parentHandle, layerMetadata, nullptr);
 970                  break;
 971              }
 972              }
 973  
 974              if (12 <= SystemVersion)
 975              {
 976                  static SurfaceComposerClientTransaction transaction;
 977  
 978                  transaction.SetTrustedOverlay(result, true);
 979                  transaction.SetLayer(result, INT_MAX);
 980                  transaction.Apply(false, true);
 981              }
 982              else if (8 >= SystemVersion)
 983              {
 984                  OpenGlobalTransaction();
 985                  SurfaceControl{result.get()}.SetLayer(INT_MAX);
 986                  CloseGlobalTransaction(false);
 987              }
 988  
 989              return {result.get(), width, height, skipScreenshot};
 990          }
 991  
 992          SurfaceControl MirrorSurface(SurfaceControl &surface, uint32_t layerStack)
 993          {
 994              using mirror_surfaces_t = std::pair<void *, void *>;
 995              constexpr auto MirrorSurfacesDeleter = [](mirror_surfaces_t *pair)
 996              {
 997                  SurfaceControl fakeSurface;
 998  
 999                  ApiInvoker<"SurfaceControl::DisConnect@v14">()(pair->first);
1000                  ApiInvoker<"RefBase::DecStrong">()(pair->first, fakeSurface.data);
1001  
1002                  ApiInvoker<"SurfaceControl::DisConnect@v14">()(pair->second);
1003                  ApiInvoker<"RefBase::DecStrong">()(pair->second, fakeSurface.data);
1004  
1005                  delete pair;
1006              };
1007  
1008              using mirror_surfaces_proxy_t = std::unique_ptr<mirror_surfaces_t, decltype(MirrorSurfacesDeleter)>;
1009  
1010              if (14 > compat::SystemVersion)
1011                  return {};
1012              if (surface.skipScreenshot)
1013              {
1014                  LogInfo("[=] Surface not need mirror: skipScreenshot is true");
1015                  return {};
1016              }
1017              if (0 == surface.width || 0 == surface.height)
1018              {
1019                  LogInfo("[=] Surface not need mirror: width or height is 0");
1020                  return {};
1021              }
1022  
1023              auto mirrorSurface = ApiInvoker<"SurfaceComposerClient::MirrorSurface@v14">()(data, surface.data);
1024              if (nullptr == mirrorSurface.get())
1025              {
1026                  LogError("[-] Failed to mirror surface: %u", layerStack);
1027                  return {};
1028              }
1029  
1030              auto mirrorRootName = "MirrorRoot@" + std::to_string(layerStack);
1031              auto mirrorRootSurface = CreateSurface(mirrorRootName.data(), surface.width, surface.height, types::WindowFlags::eNoColorFill);
1032              if (!mirrorRootSurface)
1033              {
1034                  LogError("[-] Failed to create mirror root surface: %u", layerStack);
1035                  return {};
1036              }
1037  
1038              static SurfaceComposerClientTransaction transaction;
1039              static std::vector<mirror_surfaces_proxy_t> mirrorSurfaces;
1040  
1041              transaction.SetLayer(mirrorRootSurface, INT_MAX);
1042              transaction.SetLayerStack(mirrorRootSurface, layerStack);
1043              transaction.Apply(false, true);
1044  
1045              transaction.SetLayerStack(mirrorSurface, layerStack);
1046              transaction.Show(mirrorSurface);
1047              transaction.Reparent(mirrorSurface, mirrorRootSurface);
1048              transaction.Apply(false, true);
1049  
1050              mirrorSurfaces.emplace_back(new mirror_surfaces_t{mirrorSurface.get(), mirrorRootSurface.data}, MirrorSurfacesDeleter);
1051  
1052              return mirrorRootSurface;
1053          }
1054  
1055          void ZoomSurface(SurfaceControl &surface, float scaleX, float scaleY)
1056          {
1057              static SurfaceComposerClientTransaction transaction;
1058  
1059              transaction.SetMatrix(surface, scaleX, 0.f, 0.f, scaleY);
1060              transaction.Apply(false, true);
1061          }
1062  
1063          void MoveSurface(SurfaceControl &surface, float x, float y)
1064          {
1065              static SurfaceComposerClientTransaction transaction;
1066  
1067              transaction.SetPosition(surface, x, y);
1068              transaction.Apply(false, true);
1069          }
1070  
1071          bool GetDisplayInfo(types::ui::DisplayState *displayInfo)
1072          {
1073              types::StrongPointer<void> defaultDisplay;
1074  
1075              if (9 >= SystemVersion)
1076                  defaultDisplay = ApiInvoker<"SurfaceComposerClient::GetBuiltInDisplay@v9">()(types::ui::DisplayType::DisplayIdMain);
1077              else
1078              {
1079                  if (14 > SystemVersion)
1080                      defaultDisplay = ApiInvoker<"SurfaceComposerClient::GetInternalDisplayToken@v13">()();
1081                  else
1082                  {
1083                      auto displayIds = ApiInvoker<"SurfaceComposerClient::GetPhysicalDisplayIds@v14">()();
1084                      if (displayIds.empty())
1085                          return false;
1086  
1087                      defaultDisplay = ApiInvoker<"SurfaceComposerClient::GetPhysicalDisplayToken@v14">()(displayIds[0]);
1088                  }
1089              }
1090  
1091              if (nullptr == defaultDisplay.get())
1092                  return false;
1093  
1094              if (11 <= SystemVersion)
1095                  return 0 == ApiInvoker<"SurfaceComposerClient::GetDisplayState@v11">()(defaultDisplay, displayInfo);
1096              else
1097              {
1098                  types::ui::DisplayInfo realDisplayInfo{};
1099                  if (0 != ApiInvoker<"SurfaceComposerClient::GetDisplayInfo@v10">()(defaultDisplay, &realDisplayInfo))
1100                      return false;
1101  
1102                  displayInfo->layerStackSpaceRect.width = realDisplayInfo.w;
1103                  displayInfo->layerStackSpaceRect.height = realDisplayInfo.h;
1104                  displayInfo->orientation = static_cast<types::ui::Rotation>(realDisplayInfo.orientation);
1105  
1106                  return true;
1107              }
1108          }
1109  
1110          void OpenGlobalTransaction()
1111          {
1112              ApiInvoker<"SurfaceComposerClient::OpenGlobalTransaction@v7">()();
1113          }
1114  
1115          void CloseGlobalTransaction(bool synchronous)
1116          {
1117              ApiInvoker<"SurfaceComposerClient::CloseGlobalTransaction@v7">()(synchronous);
1118          }
1119  
1120          SurfaceComposerClientTransaction &GetDefaultTransaction()
1121          {
1122              static SurfaceComposerClientTransaction transaction;
1123  
1124              return transaction;
1125          }
1126      };
1127  } // namespace android::anative_window_creator::detail::compat
1128  
1129  namespace android::anative_window_creator::detail
1130  {
1131      struct ApiTableDescriptor
1132      {
1133          static const auto GetDefaultDescriptors()
1134          {
1135              using namespace android::anative_window_creator::detail::types::apis;
1136              using namespace android::anative_window_creator::signatures;
1137  
1138              return std::make_pair(
1139                  // libutils
1140                  std::to_array({
1141                      // RefBase
1142                      ApiDescriptor{5, UINT_MAX, &apis::libutils::RefBase::Api.IncStrong, &gRegistry.RefBase_incStrong},
1143                      ApiDescriptor{5, UINT_MAX, &apis::libutils::RefBase::Api.DecStrong, &gRegistry.RefBase_decStrong},
1144  
1145                      // String8
1146                      ApiDescriptor{5, UINT_MAX, &apis::libutils::String8::Api.Constructor, &gRegistry.String8_Constructor},
1147                      ApiDescriptor{5, UINT_MAX, &apis::libutils::String8::Api.Destructor, &gRegistry.String8_Destructor},
1148                  }),
1149                  // libgui
1150                  std::to_array({
1151                      // LayerMetadata
1152                      ApiDescriptor{10, UINT_MAX, &apis::libgui::LayerMetadata::Api.Constructor, &gRegistry.LayerMetadata_Constructor},
1153                      ApiDescriptor{10, UINT_MAX, &apis::libgui::LayerMetadata::Api.SetInt32, &gRegistry.LayerMetadata_SetInt32},
1154  
1155                      // SurfaceComposerClient
1156                      ApiDescriptor{5, UINT_MAX, &apis::libgui::SurfaceComposerClient::Api.Constructor, &gRegistry.SurfaceComposerClient_Constructor},
1157  
1158                      ApiDescriptor{5, 7, &apis::libgui::SurfaceComposerClient::Api.CreateSurface, &gRegistry.CreateSurface_v7},
1159                      ApiDescriptor{8, 8, &apis::libgui::SurfaceComposerClient::Api.CreateSurface, &gRegistry.CreateSurface_v8},
1160                      ApiDescriptor{9, 9, &apis::libgui::SurfaceComposerClient::Api.CreateSurface, &gRegistry.CreateSurface_v9},
1161                      ApiDescriptor{10, 10, &apis::libgui::SurfaceComposerClient::Api.CreateSurface, &gRegistry.CreateSurface_v10},
1162                      ApiDescriptor{11, 11, &apis::libgui::SurfaceComposerClient::Api.CreateSurface, &gRegistry.CreateSurface_v11},
1163                      ApiDescriptor{12, 12, &apis::libgui::SurfaceComposerClient::Api.CreateSurface, &gRegistry.CreateSurface_v12},
1164                      ApiDescriptor{13, 13, &apis::libgui::SurfaceComposerClient::Api.CreateSurface, &gRegistry.CreateSurface_v13},
1165                      ApiDescriptor{14, UINT_MAX, &apis::libgui::SurfaceComposerClient::Api.CreateSurface, &gRegistry.CreateSurface_v14},
1166  
1167                      ApiDescriptor{11, UINT_MAX, &apis::libgui::SurfaceComposerClient::Api.MirrorSurface, &gRegistry.MirrorSurface},
1168  
1169                      ApiDescriptor{5, 9, &apis::libgui::SurfaceComposerClient::Api.GetBuiltInDisplay, &gRegistry.GetBuiltInDisplay},
1170                      ApiDescriptor{10, 13, &apis::libgui::SurfaceComposerClient::Api.GetInternalDisplayToken, &gRegistry.GetInternalDisplayToken},
1171                      ApiDescriptor{10, UINT_MAX, &apis::libgui::SurfaceComposerClient::Api.GetPhysicalDisplayIds, &gRegistry.GetPhysicalDisplayIds},
1172                      ApiDescriptor{12, UINT_MAX, &apis::libgui::SurfaceComposerClient::Api.GetPhysicalDisplayToken, &gRegistry.GetPhysicalDisplayToken},
1173  
1174                      ApiDescriptor{5, 11, &apis::libgui::SurfaceComposerClient::Api.GetDisplayInfo, &gRegistry.GetDisplayInfo},
1175                      ApiDescriptor{11, UINT_MAX, &apis::libgui::SurfaceComposerClient::Api.GetDisplayState, &gRegistry.GetDisplayState},
1176  
1177                      // SurfaceComposerClient::Transaction
1178                      ApiDescriptor{11, 11, &apis::libgui::SurfaceComposerClient::Transaction::Api.CopyConstructor, &gRegistry.Transaction_CopyConstructor},
1179                      ApiDescriptor{12, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.Constructor, &gRegistry.Transaction_Constructor},
1180                      ApiDescriptor{9, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.SetLayer, &gRegistry.Transaction_SetLayer},
1181                      ApiDescriptor{12, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.SetTrustedOverlay, &gRegistry.Transaction_SetTrustedOverlay},
1182  
1183                      ApiDescriptor{9, 12, &apis::libgui::SurfaceComposerClient::Transaction::Api.Apply, &gRegistry.Transaction_Apply_v12},
1184                      ApiDescriptor{13, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.Apply, &gRegistry.Transaction_Apply_v13},
1185  
1186                      ApiDescriptor{13, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.SetLayerStack, &gRegistry.Transaction_SetLayerStack},
1187                      ApiDescriptor{9, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.Show, &gRegistry.Transaction_Show},
1188                      ApiDescriptor{9, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.Hide, &gRegistry.Transaction_Hide},
1189                      ApiDescriptor{12, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.Reparent, &gRegistry.Transaction_Reparent},
1190  
1191                      ApiDescriptor{9, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.SetMatrix, &gRegistry.Transaction_SetMatrix},
1192                      ApiDescriptor{9, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.SetPosition, &gRegistry.Transaction_SetPosition},
1193  
1194                      ApiDescriptor{10, 12, &apis::libgui::SurfaceComposerClient::Transaction::Api.SetInputWindowInfo, &gRegistry.Transaction_SetInputWindowInfo_v10},
1195                      ApiDescriptor{13, 15, &apis::libgui::SurfaceComposerClient::Transaction::Api.SetInputWindowInfo, &gRegistry.Transaction_SetInputWindowInfo_v10},
1196                      ApiDescriptor{16, UINT_MAX, &apis::libgui::SurfaceComposerClient::Transaction::Api.SetInputWindowInfo, &gRegistry.Transaction_SetInputWindowInfo_v16},
1197  
1198                      // SurfaceComposerClient::GlobalTransaction
1199                      ApiDescriptor{5, 8, &apis::libgui::SurfaceComposerClient::Api.OpenGlobalTransaction, &gRegistry.OpenGlobalTransaction},
1200                      ApiDescriptor{5, 8, &apis::libgui::SurfaceComposerClient::Api.CloseGlobalTransaction, &gRegistry.CloseGlobalTransaction},
1201  
1202                      // SurfaceControl
1203                      ApiDescriptor{5, 11, &apis::libgui::SurfaceControl::Api.GetSurface, &gRegistry.SurfaceControl_GetSurface_v11},
1204                      ApiDescriptor{12, UINT_MAX, &apis::libgui::SurfaceControl::Api.GetSurface, &gRegistry.SurfaceControl_GetSurface_v12},
1205  
1206                      ApiDescriptor{5, 7, &apis::libgui::Surface::Api.DisConnect, &gRegistry.Surface_DisConnect},
1207                      ApiDescriptor{7, UINT_MAX, &apis::libgui::SurfaceControl::Api.DisConnect, &gRegistry.SurfaceControl_DisConnect},
1208  
1209                      ApiDescriptor{12, UINT_MAX, &apis::libgui::SurfaceControl::Api.GetParentingLayer, &gRegistry.SurfaceControl_GetParentingLayer},
1210  
1211                      ApiDescriptor{5, 8, &apis::libgui::SurfaceControl::Api.SetLayer, &gRegistry.SurfaceControl_SetLayer},
1212                  }));
1213          }
1214      };
1215  
1216      struct ApiResolver
1217      {
1218          struct ResolverImpl
1219          {
1220              void *(*Open)(const char *filename, int flag);
1221              void *(*Resolve)(void *handle, const char *symbol);
1222              int (*Close)(void *handle);
1223  
1224              ResolverImpl()
1225                  : Open(dlopen),
1226                    Resolve(dlsym),
1227                    Close(dlclose)
1228              {
1229              }
1230  
1231              ResolverImpl(decltype(Open) open, decltype(Resolve) resolve, decltype(Close) close)
1232                  : Open(open),
1233                    Resolve(resolve),
1234                    Close(close)
1235              {
1236              }
1237          };
1238  
1239          static void Resolve()
1240          {
1241              static bool resolved = false;
1242  
1243              if (resolved)
1244                  return;
1245  
1246              std::string systemVersionString(128, 0);
1247              systemVersionString.resize(__system_property_get("ro.build.version.release", systemVersionString.data()));
1248              if (!systemVersionString.empty())
1249                  compat::SystemVersion = std::stoi(systemVersionString);
1250  
1251              if (compat::SupportedMinVersion > compat::SystemVersion)
1252              {
1253                  LogError("[!] Unsupported system version: %zu", compat::SystemVersion);
1254                  return;
1255              }
1256  
1257              LogInfo("[*] Starting to resolve signatures for Android %zu", compat::SystemVersion);
1258  
1259              // Initialize KittyMemory scanner
1260              static KittyMemSys mem;
1261              mem.init(getpid());
1262              static ElfScannerMgr elfScannerMgr(&mem);
1263              static KittyScannerMgr scanner(&mem);
1264  
1265  #ifdef __LP64__
1266              auto libgui = elfScannerMgr.findElf("/system/lib64/libgui.so");
1267              auto libutils = elfScannerMgr.findElf("/system/lib64/libutils.so");
1268  #else
1269              auto libgui = elfScannerMgr.findElf("/system/lib/libgui.so");
1270              auto libutils = elfScannerMgr.findElf("/system/lib/libutils.so");
1271  #endif
1272  
1273              if (!libgui.isValid() || !libutils.isValid())
1274              {
1275                  LogError("[!] Failed to find libgui.so or libutils.so in memory");
1276                  throw std::runtime_error("Failed to find libgui.so or libutils.so");
1277              }
1278  
1279              const auto &[libutilsApis, libguiApis] = ApiTableDescriptor::GetDefaultDescriptors();
1280              
1281              auto resolveBySignature = [&](const ElfScanner &elf, const auto &apis, const char* libName) {
1282                  LogInfo("[*] Scanning %s (Base: %p, End: %p)", libName, (void*)elf.base(), (void*)elf.end());
1283                  for (const auto &descriptor : apis)
1284                  {
1285                      if (!descriptor.IsSupported(compat::SystemVersion))
1286                          continue;
1287  
1288                      const char* pattern = descriptor.signature->Get();
1289                      if (!pattern || std::string(pattern) == "signature-here") {
1290                          LogError("[!] No valid signature for method in %s. Please update Signatures.h", libName);
1291                          continue;
1292                      }
1293  
1294                      *descriptor.storeToTarget = (void*)scanner.findIdaPatternFirst(elf.base(), elf.end(), pattern);
1295                      if (nullptr == *descriptor.storeToTarget)
1296                      {
1297                          LogError("[!] Failed to resolve [%s] signature in %s", pattern, libName);
1298                          
1299                          std::string errorMsg = "Signature resolution failed for pattern [";
1300                          errorMsg += pattern;
1301                          errorMsg += "] in ";
1302                          errorMsg += libName;
1303                          throw std::runtime_error(errorMsg);
1304                      }
1305                  }
1306              };
1307  
1308              resolveBySignature(libutils, libutilsApis, "libutils");
1309              resolveBySignature(libgui, libguiApis, "libgui");
1310  
1311              resolved = true;
1312              LogInfo("[+] Version[Android %zu] resolved all signatures", compat::SystemVersion);
1313          }
1314      };
1315  
1316      struct DumpDisplayInfo
1317      {
1318          std::string uniqueId;
1319          uint32_t currentLayerStack;
1320          struct
1321          {
1322              int32_t left;
1323              int32_t top;
1324              int32_t right;
1325              int32_t bottom;
1326          } currentLayerStackRect;
1327  
1328          static DumpDisplayInfo MakeFromRawDumpInfo(const std::string_view &uniqueId, const std::string_view &currentLayerStack, const std::string_view &currentLayerStackRect)
1329          {
1330              DumpDisplayInfo result;
1331  
1332              result.uniqueId = std::string{uniqueId.begin(), uniqueId.end()};
1333              result.currentLayerStack = static_cast<uint32_t>(std::stoul(std::string{currentLayerStack.begin(), currentLayerStack.end()}));
1334  
1335              auto leftPos = currentLayerStackRect.find("(") + 1;
1336              auto topPos = currentLayerStackRect.find(", ", leftPos);
1337              auto rightPos = currentLayerStackRect.find(" - ", topPos + 2);
1338              auto bottomPos = currentLayerStackRect.find(", ", rightPos + 3);
1339              auto endPos = currentLayerStackRect.find(")", bottomPos + 2);
1340  
1341              // Don't check it, even though it might cause a crash.
1342              result.currentLayerStackRect.left = std::stoi(std::string{currentLayerStackRect.begin() + leftPos, currentLayerStackRect.begin() + topPos});
1343              result.currentLayerStackRect.top = std::stoi(std::string{currentLayerStackRect.begin() + topPos + 2, currentLayerStackRect.begin() + rightPos});
1344              result.currentLayerStackRect.right = std::stoi(std::string{currentLayerStackRect.begin() + rightPos + 3, currentLayerStackRect.begin() + bottomPos});
1345              result.currentLayerStackRect.bottom = std::stoi(std::string{currentLayerStackRect.begin() + bottomPos + 2, currentLayerStackRect.begin() + endPos});
1346  
1347              return result;
1348          }
1349      };
1350  
1351      struct MirrorLayerTransform
1352      {
1353          bool isAspectRatioSimilar;
1354          float widthScale;
1355          float heightScale;
1356          float offsetX;
1357          float offsetY;
1358      };
1359  
1360      inline std::vector<DumpDisplayInfo> ParseDumpDisplayInfo(const std::string_view &dumpDisplayInfo)
1361      {
1362          constexpr auto SubStringView = [](const std::string_view &str, std::string_view start, std::string_view end, int startOffset = 0) -> std::string_view
1363          {
1364              auto startIt = str.find(start, startOffset);
1365              if (std::string::npos == startIt)
1366                  return {};
1367  
1368              auto endIt = str.find(end, startIt + start.size());
1369              if (std::string::npos == endIt)
1370                  return {};
1371  
1372              return str.substr(startIt + start.size(), endIt - startIt - start.size());
1373          };
1374  
1375          std::vector<DumpDisplayInfo> result;
1376  
1377          // DisplayDeviceInfo
1378          auto dumpDisplayInfoIt = std::string_view::npos;
1379          while (std::string_view::npos != (dumpDisplayInfoIt = dumpDisplayInfo.find("DisplayDeviceInfo", dumpDisplayInfoIt + 1)))
1380          {
1381              auto uniqueId = SubStringView(dumpDisplayInfo, "mUniqueId=", "\n", dumpDisplayInfoIt);
1382              auto currentLayerStack = SubStringView(dumpDisplayInfo, "mCurrentLayerStack=", "\n", dumpDisplayInfoIt);
1383              auto currentLayerStackRect = SubStringView(dumpDisplayInfo, "mCurrentLayerStackRect=", "\n", dumpDisplayInfoIt);
1384  
1385              if ("-1" == currentLayerStack)
1386              {
1387                  LogError("[-] %s -> Current layer stack is -1, skipping", std::string{uniqueId.begin(), uniqueId.end()}.data());
1388  
1389                  continue;
1390              }
1391  
1392              result.push_back(DumpDisplayInfo::MakeFromRawDumpInfo(uniqueId, currentLayerStack, currentLayerStackRect));
1393          }
1394  
1395          return result;
1396      }
1397  
1398      inline MirrorLayerTransform CalcMirrorLayerTransform(float targetWidth, float targetHeight, float sourceWidth, float sourceHeight, float epsilon = 0.002)
1399      {
1400          if (0.f == targetHeight || 0.f == sourceHeight)
1401              throw std::runtime_error("[-] Invalid height");
1402  
1403          MirrorLayerTransform result{
1404              .isAspectRatioSimilar = std::abs(targetWidth / targetHeight - sourceWidth / sourceHeight) < epsilon,
1405              .widthScale = sourceWidth / targetWidth,
1406              .heightScale = sourceHeight / targetHeight,
1407          };
1408          if (result.isAspectRatioSimilar)
1409              return result;
1410  
1411          if (result.widthScale > result.heightScale)
1412          {
1413              result.offsetX = (sourceWidth - targetWidth * result.heightScale) / 2;
1414              result.widthScale = result.heightScale;
1415          }
1416          else
1417          {
1418              result.offsetY = (sourceHeight - targetHeight * result.widthScale) / 2;
1419              result.heightScale = result.widthScale;
1420          }
1421  
1422          return result;
1423      }
1424  } // namespace android::anative_window_creator::detail
1425  
1426  namespace android
1427  {
1428      class ANativeWindowCreator
1429      {
1430      public:
1431          struct DisplayInfo
1432          {
1433              int32_t theta;
1434              int32_t width;
1435              int32_t height;
1436          };
1437  
1438          struct CreateOptions
1439          {
1440              const char *name;
1441              int32_t width;
1442              int32_t height;
1443              bool skipScreenshot;
1444          };
1445  
1446      public:
1447          static void SetupCustomApiResolver(const anative_window_creator::detail::ApiResolver::ResolverImpl &)
1448          {
1449              anative_window_creator::detail::ApiResolver::Resolve();
1450          }
1451  
1452      public:
1453          static anative_window_creator::detail::compat::SurfaceComposerClient &GetComposerInstance()
1454          {
1455              anative_window_creator::detail::ApiResolver::Resolve();
1456  
1457              static anative_window_creator::detail::compat::SurfaceComposerClient surfaceComposerClient;
1458  
1459              return surfaceComposerClient;
1460          }
1461  
1462          static DisplayInfo GetDisplayInfo()
1463          {
1464              auto &surfaceComposerClient = GetComposerInstance();
1465              anative_window_creator::detail::types::ui::DisplayState displayInfo{};
1466  
1467              if (!surfaceComposerClient.GetDisplayInfo(&displayInfo))
1468                  return {};
1469  
1470              return DisplayInfo{
1471                  .theta = 90 * static_cast<int32_t>(displayInfo.orientation),
1472                  .width = displayInfo.layerStackSpaceRect.width,
1473                  .height = displayInfo.layerStackSpaceRect.height,
1474              };
1475          }
1476  
1477          static ANativeWindow *Create(const CreateOptions &options = {.name = "AImGui"})
1478          {
1479              auto &surfaceComposerClient = GetComposerInstance();
1480  
1481              int32_t width = options.width;
1482              int32_t height = options.height;
1483              while (0 == width || 0 == height)
1484              {
1485                  anative_window_creator::detail::types::ui::DisplayState displayInfo{};
1486  
1487                  if (!surfaceComposerClient.GetDisplayInfo(&displayInfo))
1488                      break;
1489  
1490                  width = displayInfo.layerStackSpaceRect.width;
1491                  height = displayInfo.layerStackSpaceRect.height;
1492  
1493                  break;
1494              }
1495  
1496              auto surfaceControl = surfaceComposerClient.CreateSurface(options.name, width, height, {}, options.skipScreenshot);
1497              auto nativeWindow = reinterpret_cast<ANativeWindow *>(surfaceControl.GetSurface());
1498  
1499              m_cachedSurfaceControl.emplace(nativeWindow, std::move(surfaceControl));
1500              return nativeWindow;
1501          }
1502  
1503          static void Destroy(ANativeWindow *nativeWindow)
1504          {
1505              if (!m_cachedSurfaceControl.contains(nativeWindow))
1506                  return;
1507  
1508              m_cachedSurfaceControl[nativeWindow].DestroySurface(reinterpret_cast<anative_window_creator::detail::compat::Surface *>(nativeWindow));
1509              m_cachedSurfaceControl.erase(nativeWindow);
1510          }
1511  
1512          static void ProcessMirrorDisplay()
1513          {
1514              static std::chrono::steady_clock::time_point lastTime{};
1515  
1516              if (14 > anative_window_creator::detail::compat::SystemVersion)
1517                  return;
1518              if (std::chrono::steady_clock::now() - lastTime < std::chrono::seconds(1))
1519                  return;
1520  
1521              // Check if have surfaces need to mirror
1522              static std::vector<anative_window_creator::detail::compat::SurfaceControl *> surfacesNeedToMirror;
1523  
1524              surfacesNeedToMirror.clear();
1525              for (auto &[_, surfaceControl] : m_cachedSurfaceControl)
1526              {
1527                  if (!surfaceControl.skipScreenshot)
1528                      surfacesNeedToMirror.push_back(&surfaceControl);
1529              }
1530              if (surfacesNeedToMirror.empty())
1531                  return;
1532  
1533              // Run "dumpsys display" and get result
1534              auto pipe = popen("dumpsys display", "r");
1535              if (!pipe)
1536              {
1537                  LogError("[-] Failed to run dumpsys command");
1538                  return;
1539              }
1540  
1541              char buffer[512]{};
1542              std::string dumpDisplayResult;
1543              while (fgets(buffer, sizeof(buffer), pipe) != nullptr)
1544                  dumpDisplayResult += buffer;
1545              pclose(pipe);
1546  
1547              static std::unordered_map<uint32_t, std::vector<anative_window_creator::detail::compat::SurfaceControl>> cachedLayerStackMirrorSurfaces;
1548              static std::unordered_set<uint32_t> cachedLayerStackScales;
1549  
1550              auto dumpDisplayInfos = anative_window_creator::detail::ParseDumpDisplayInfo(dumpDisplayResult);
1551              for (auto &displayInfo : dumpDisplayInfos)
1552              {
1553                  // Update multi display layer scale
1554                  static int32_t builtinDisplayWidth = -1, builtinDisplayHeight = -1;
1555                  if (0 == displayInfo.currentLayerStack)
1556                  {
1557                      builtinDisplayWidth = displayInfo.currentLayerStackRect.right;
1558                      builtinDisplayHeight = displayInfo.currentLayerStackRect.bottom;
1559                  }
1560  
1561                  // Process mirror display
1562                  if (0 == displayInfo.currentLayerStack)
1563                      continue;
1564  
1565                  if (!cachedLayerStackMirrorSurfaces.contains(displayInfo.currentLayerStack))
1566                  {
1567                      LogInfo("[=] New display layerstack detected: [%s] -> %u", displayInfo.uniqueId.data(), displayInfo.currentLayerStack);
1568  
1569                      for (auto surfaceControl : surfacesNeedToMirror)
1570                      {
1571                          auto mirrorLayer = GetComposerInstance().MirrorSurface(*surfaceControl, displayInfo.currentLayerStack);
1572  
1573                          LogInfo("[+] Mirror layer created: %p", mirrorLayer.data);
1574                          cachedLayerStackMirrorSurfaces[displayInfo.currentLayerStack].emplace_back(std::move(mirrorLayer));
1575                      }
1576                  }
1577  
1578                  if (-1 != builtinDisplayWidth && -1 != builtinDisplayHeight && cachedLayerStackMirrorSurfaces.contains(displayInfo.currentLayerStack))
1579                  {
1580                      if ((displayInfo.currentLayerStackRect.right != builtinDisplayWidth || displayInfo.currentLayerStackRect.bottom != builtinDisplayHeight) && !cachedLayerStackScales.contains(displayInfo.currentLayerStack))
1581                      {
1582                          LogInfo("[=] Display layerstack size changed[%d x %d]: %u -> %d x %d",
1583                                  builtinDisplayWidth,
1584                                  builtinDisplayHeight,
1585                                  displayInfo.currentLayerStack,
1586                                  displayInfo.currentLayerStackRect.right,
1587                                  displayInfo.currentLayerStackRect.bottom);
1588  
1589                          auto &composerInstance = GetComposerInstance();
1590                          auto &mirrorLayers = cachedLayerStackMirrorSurfaces.at(displayInfo.currentLayerStack);
1591                          auto transformParams = anative_window_creator::detail::CalcMirrorLayerTransform(
1592                              builtinDisplayWidth,
1593                              builtinDisplayHeight,
1594                              displayInfo.currentLayerStackRect.right,
1595                              displayInfo.currentLayerStackRect.bottom);
1596  
1597                          for (auto &mirrorLayer : mirrorLayers)
1598                          {
1599                              composerInstance.ZoomSurface(mirrorLayer, transformParams.widthScale, transformParams.heightScale);
1600  
1601                              if (!transformParams.isAspectRatioSimilar)
1602                                  composerInstance.MoveSurface(mirrorLayer, transformParams.offsetX, transformParams.offsetY);
1603  
1604                              cachedLayerStackScales.emplace(displayInfo.currentLayerStack);
1605                              LogInfo("[+] Transform mirror layer:%p similar:%d width:%f height:%f x:%f y:%f",
1606                                      mirrorLayer.data,
1607                                      transformParams.isAspectRatioSimilar,
1608                                      transformParams.widthScale,
1609                                      transformParams.heightScale,
1610                                      transformParams.offsetX,
1611                                      transformParams.offsetY);
1612                          }
1613                      }
1614                  }
1615              }
1616  
1617              lastTime = std::chrono::steady_clock::now();
1618          }
1619  
1620          static void UpdateWindowInfo(ANativeWindow *nativeWindow, void *windowInfo)
1621          {
1622              if (!m_cachedSurfaceControl.contains(nativeWindow))
1623                  return;
1624  
1625              auto &transaction = GetComposerInstance().GetDefaultTransaction();
1626              auto &surfaceControl = m_cachedSurfaceControl.at(nativeWindow);
1627              auto parentingLayer = surfaceControl.GetParentingLayer();
1628  
1629              transaction.SetInputWindowInfo(parentingLayer, windowInfo);
1630              transaction.Apply(true, false);
1631          }
1632  
1633      private:
1634          inline static std::unordered_map<ANativeWindow *, anative_window_creator::detail::compat::SurfaceControl> m_cachedSurfaceControl;
1635      };
1636  } // namespace android
1637  
1638  #if LOGTAG_DEFINED
1639  #undef LOGTAG
1640  
1641  #undef LOGTAG_DEFINED
1642  #endif // LOGTAG_DEFINED
1643  
1644  #if LogInfo_DEFINED
1645  #undef LogInfo
1646  #undef LogDebug
1647  #undef LogError
1648  
1649  #undef LogInfo_DEFINED
1650  #endif // LogInfo_DEFINED
1651  
1652  #endif // !A_NATIVE_WINDOW_CREATOR_H