Move librecovery_ui to a sub-directory

This helps to expose librecovery_ui for device specific RecoveryUi.

Bug: 76436783
Test: mma, unit tests pass
Change-Id: Ic6c3d301d5833e4a592e6ea9d9d059bc4e4919be
(cherry picked from commit b5108c372c8b92671ea5ebb4eeff00757fcee187)
diff --git a/recovery_ui/include/recovery_ui/device.h b/recovery_ui/include/recovery_ui/device.h
new file mode 100644
index 0000000..cfa914e
--- /dev/null
+++ b/recovery_ui/include/recovery_ui/device.h
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _RECOVERY_DEVICE_H
+#define _RECOVERY_DEVICE_H
+
+#include <stddef.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+// Forward declaration to avoid including "ui.h".
+class RecoveryUI;
+
+class Device {
+ public:
+  static constexpr const int kNoAction = -1;
+  static constexpr const int kHighlightUp = -2;
+  static constexpr const int kHighlightDown = -3;
+  static constexpr const int kInvokeItem = -4;
+
+  enum BuiltinAction {
+    NO_ACTION = 0,
+    REBOOT = 1,
+    APPLY_SDCARD = 2,
+    // APPLY_CACHE was 3.
+    APPLY_ADB_SIDELOAD = 4,
+    WIPE_DATA = 5,
+    WIPE_CACHE = 6,
+    REBOOT_BOOTLOADER = 7,
+    SHUTDOWN = 8,
+    VIEW_RECOVERY_LOGS = 9,
+    MOUNT_SYSTEM = 10,
+    RUN_GRAPHICS_TEST = 11,
+    RUN_LOCALE_TEST = 12,
+    KEY_INTERRUPTED = 13,
+    ENTER_FASTBOOT = 14,
+    ENTER_RECOVERY = 15,
+  };
+
+  explicit Device(RecoveryUI* ui);
+  virtual ~Device() {}
+
+  // Returns a raw pointer to the RecoveryUI object.
+  virtual RecoveryUI* GetUI() {
+    return ui_.get();
+  }
+
+  // Resets the UI object to the given UI. Used to override the default UI in case initialization
+  // failed, or we want a different UI for some reason. The device object will take the ownership.
+  virtual void ResetUI(RecoveryUI* ui) {
+    ui_.reset(ui);
+  }
+
+  // Called when recovery starts up (after the UI has been obtained and initialized and after the
+  // arguments have been parsed, but before anything else).
+  virtual void StartRecovery() {}
+
+  // Called from the main thread when recovery is at the main menu and waiting for input, and a key
+  // is pressed. (Note that "at" the main menu does not necessarily mean the menu is visible;
+  // recovery will be at the main menu with it invisible after an unsuccessful operation, such as
+  // failed to install an OTA package, or if recovery is started with no command.)
+  //
+  // 'key' is the code of the key just pressed. (You can call IsKeyPressed() on the RecoveryUI
+  // object you returned from GetUI() if you want to find out if other keys are held down.)
+  //
+  // 'visible' is true if the menu is visible.
+  //
+  // Returns one of the defined constants below in order to:
+  //   - move the menu highlight (kHighlight{Up,Down}: negative value)
+  //   - invoke the highlighted item (kInvokeItem: negative value)
+  //   - do nothing (kNoAction: negative value)
+  //   - invoke a specific action (a menu position: non-negative value)
+  virtual int HandleMenuKey(int key, bool visible);
+
+  // Returns the list of menu items (a vector of strings). The menu_position passed to
+  // InvokeMenuItem() will correspond to the indexes into this array.
+  virtual const std::vector<std::string>& GetMenuItems();
+
+  // Performs a recovery action selected from the menu. 'menu_position' will be the index of the
+  // selected menu item, or a non-negative value returned from HandleMenuKey(). The menu will be
+  // hidden when this is called; implementations can call ui_print() to print information to the
+  // screen. If the menu position is one of the builtin actions, you can just return the
+  // corresponding enum value. If it is an action specific to your device, you actually perform it
+  // here and return NO_ACTION.
+  virtual BuiltinAction InvokeMenuItem(size_t menu_position);
+
+  // Removes the menu item for the given action. This allows tailoring the menu based on the
+  // runtime info, such as the availability of /cache or /sdcard.
+  virtual void RemoveMenuItemForAction(Device::BuiltinAction action);
+
+  // Called before and after we do a wipe data/factory reset operation, either via a reboot from the
+  // main system with the --wipe_data flag, or when the user boots into recovery image manually and
+  // selects the option from the menu, to perform whatever device-specific wiping actions as needed.
+  // Returns true on success; returning false from PreWipeData will prevent the regular wipe, and
+  // returning false from PostWipeData will cause the wipe to be considered a failure.
+  virtual bool PreWipeData() {
+    return true;
+  }
+
+  virtual bool PostWipeData() {
+    return true;
+  }
+
+ private:
+  // The RecoveryUI object that should be used to display the user interface for this device.
+  std::unique_ptr<RecoveryUI> ui_;
+};
+
+// Disable name mangling, as this function will be loaded via dlsym(3).
+extern "C" {
+
+// The device-specific library must define this function (or the default one will be used, if there
+// is no device-specific library). It returns the Device object that recovery should use.
+Device* make_device();
+}
+
+#endif  // _DEVICE_H
diff --git a/recovery_ui/include/recovery_ui/screen_ui.h b/recovery_ui/include/recovery_ui/screen_ui.h
new file mode 100644
index 0000000..5cda2a2
--- /dev/null
+++ b/recovery_ui/include/recovery_ui/screen_ui.h
@@ -0,0 +1,412 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef RECOVERY_SCREEN_UI_H
+#define RECOVERY_SCREEN_UI_H
+
+#include <stdio.h>
+
+#include <atomic>
+#include <functional>
+#include <memory>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "ui.h"
+
+// From minui/minui.h.
+class GRSurface;
+
+enum class UIElement {
+  HEADER,
+  MENU,
+  MENU_SEL_BG,
+  MENU_SEL_BG_ACTIVE,
+  MENU_SEL_FG,
+  LOG,
+  TEXT_FILL,
+  INFO
+};
+
+// Interface to draw the UI elements on the screen.
+class DrawInterface {
+ public:
+  virtual ~DrawInterface() = default;
+
+  // Sets the color to the predefined value for |element|.
+  virtual void SetColor(UIElement element) const = 0;
+
+  // Draws a highlight bar at (x, y) - (x + width, y + height).
+  virtual void DrawHighlightBar(int x, int y, int width, int height) const = 0;
+
+  // Draws a horizontal rule at Y. Returns the offset it should be moving along Y-axis.
+  virtual int DrawHorizontalRule(int y) const = 0;
+
+  // Draws a line of text. Returns the offset it should be moving along Y-axis.
+  virtual int DrawTextLine(int x, int y, const std::string& line, bool bold) const = 0;
+
+  // Draws surface portion (sx, sy, w, h) at screen location (dx, dy).
+  virtual void DrawSurface(const GRSurface* surface, int sx, int sy, int w, int h, int dx,
+                           int dy) const = 0;
+
+  // Draws rectangle at (x, y) - (x + w, y + h).
+  virtual void DrawFill(int x, int y, int w, int h) const = 0;
+
+  // Draws given surface (surface->pixel_bytes = 1) as text at (x, y).
+  virtual void DrawTextIcon(int x, int y, const GRSurface* surface) const = 0;
+
+  // Draws multiple text lines. Returns the offset it should be moving along Y-axis.
+  virtual int DrawTextLines(int x, int y, const std::vector<std::string>& lines) const = 0;
+
+  // Similar to DrawTextLines() to draw multiple text lines, but additionally wraps long lines. It
+  // keeps symmetrical margins of 'x' at each end of a line. Returns the offset it should be moving
+  // along Y-axis.
+  virtual int DrawWrappedTextLines(int x, int y, const std::vector<std::string>& lines) const = 0;
+};
+
+// Interface for classes that maintain the menu selection and display.
+class Menu {
+ public:
+  virtual ~Menu() = default;
+  // Returns the current menu selection.
+  size_t selection() const;
+  // Sets the current selection to |sel|. Handle the overflow cases depending on if the menu is
+  // scrollable.
+  virtual int Select(int sel) = 0;
+  // Displays the menu headers on the screen at offset x, y
+  virtual int DrawHeader(int x, int y) const = 0;
+  // Iterates over the menu items and displays each of them at offset x, y.
+  virtual int DrawItems(int x, int y, int screen_width, bool long_press) const = 0;
+
+ protected:
+  Menu(size_t initial_selection, const DrawInterface& draw_func);
+  // Current menu selection.
+  size_t selection_;
+  // Reference to the class that implements all the draw functions.
+  const DrawInterface& draw_funcs_;
+};
+
+// This class uses strings as the menu header and items.
+class TextMenu : public Menu {
+ public:
+  // Constructs a Menu instance with the given |headers|, |items| and properties. Sets the initial
+  // selection to |initial_selection|.
+  TextMenu(bool scrollable, size_t max_items, size_t max_length,
+           const std::vector<std::string>& headers, const std::vector<std::string>& items,
+           size_t initial_selection, int char_height, const DrawInterface& draw_funcs);
+
+  int Select(int sel) override;
+  int DrawHeader(int x, int y) const override;
+  int DrawItems(int x, int y, int screen_width, bool long_press) const override;
+
+  bool scrollable() const {
+    return scrollable_;
+  }
+
+  // Returns count of menu items.
+  size_t ItemsCount() const;
+
+  // Returns the index of the first menu item.
+  size_t MenuStart() const;
+
+  // Returns the index of the last menu item + 1.
+  size_t MenuEnd() const;
+
+  // Menu example:
+  // info:                           Android Recovery
+  //                                 ....
+  // help messages:                  Swipe up/down to move
+  //                                 Swipe left/right to select
+  // empty line (horizontal rule):
+  // menu headers:                   Select file to view
+  // menu items:                     /cache/recovery/last_log
+  //                                 /cache/recovery/last_log.1
+  //                                 /cache/recovery/last_log.2
+  //                                 ...
+  const std::vector<std::string>& text_headers() const;
+  std::string TextItem(size_t index) const;
+
+  // Checks if the menu items fit vertically on the screen. Returns true and set the
+  // |cur_selection_str| if the items exceed the screen limit.
+  bool ItemsOverflow(std::string* cur_selection_str) const;
+
+ private:
+  // The menu is scrollable to display more items. Used on wear devices who have smaller screens.
+  const bool scrollable_;
+  // The max number of menu items to fit vertically on a screen.
+  const size_t max_display_items_;
+  // The length of each item to fit horizontally on a screen.
+  const size_t max_item_length_;
+  // The menu headers.
+  std::vector<std::string> text_headers_;
+  // The actual menu items trimmed to fit the given properties.
+  std::vector<std::string> text_items_;
+  // The first item to display on the screen.
+  size_t menu_start_;
+
+  // Height in pixels of each character.
+  int char_height_;
+};
+
+// This class uses GRSurface's as the menu header and items.
+class GraphicMenu : public Menu {
+ public:
+  // Constructs a Menu instance with the given |headers|, |items| and properties. Sets the initial
+  // selection to |initial_selection|. |headers| and |items| will be made local copies.
+  GraphicMenu(const GRSurface* graphic_headers, const std::vector<const GRSurface*>& graphic_items,
+              size_t initial_selection, const DrawInterface& draw_funcs);
+
+  int Select(int sel) override;
+  int DrawHeader(int x, int y) const override;
+  int DrawItems(int x, int y, int screen_width, bool long_press) const override;
+
+  // Checks if all the header and items are valid GRSurface's; and that they can fit in the area
+  // defined by |max_width| and |max_height|.
+  static bool Validate(size_t max_width, size_t max_height, const GRSurface* graphic_headers,
+                       const std::vector<const GRSurface*>& graphic_items);
+
+  // Returns true if |surface| fits on the screen with a vertical offset |y|.
+  static bool ValidateGraphicSurface(size_t max_width, size_t max_height, int y,
+                                     const GRSurface* surface);
+
+ private:
+  // Menu headers and items in graphic icons. These are the copies owned by the class instance.
+  std::unique_ptr<GRSurface> graphic_headers_;
+  std::vector<std::unique_ptr<GRSurface>> graphic_items_;
+};
+
+// Implementation of RecoveryUI appropriate for devices with a screen
+// (shows an icon + a progress bar, text logging, menu, etc.)
+class ScreenRecoveryUI : public RecoveryUI, public DrawInterface {
+ public:
+  ScreenRecoveryUI();
+  explicit ScreenRecoveryUI(bool scrollable_menu);
+  ~ScreenRecoveryUI() override;
+
+  bool Init(const std::string& locale) override;
+  std::string GetLocale() const override;
+
+  // overall recovery state ("background image")
+  void SetBackground(Icon icon) override;
+  void SetSystemUpdateText(bool security_update) override;
+
+  // progress indicator
+  void SetProgressType(ProgressType type) override;
+  void ShowProgress(float portion, float seconds) override;
+  void SetProgress(float fraction) override;
+
+  void SetStage(int current, int max) override;
+
+  // text log
+  void ShowText(bool visible) override;
+  bool IsTextVisible() override;
+  bool WasTextEverVisible() override;
+
+  // printing messages
+  void Print(const char* fmt, ...) override __printflike(2, 3);
+  void PrintOnScreenOnly(const char* fmt, ...) override __printflike(2, 3);
+  void ShowFile(const std::string& filename) override;
+
+  // menu display
+  size_t ShowMenu(const std::vector<std::string>& headers, const std::vector<std::string>& items,
+                  size_t initial_selection, bool menu_only,
+                  const std::function<int(int, bool)>& key_handler) override;
+  void SetTitle(const std::vector<std::string>& lines) override;
+
+  void KeyLongPress(int) override;
+
+  void Redraw();
+
+  // Checks the background text image, for debugging purpose. It iterates the locales embedded in
+  // the on-device resource files and shows the localized text, for manual inspection.
+  void CheckBackgroundTextImages();
+
+  // Displays the localized wipe data menu.
+  size_t ShowPromptWipeDataMenu(const std::vector<std::string>& backup_headers,
+                                const std::vector<std::string>& backup_items,
+                                const std::function<int(int, bool)>& key_handler) override;
+
+  // Displays the localized wipe data confirmation menu.
+  size_t ShowPromptWipeDataConfirmationMenu(
+      const std::vector<std::string>& backup_headers, const std::vector<std::string>& backup_items,
+      const std::function<int(int, bool)>& key_handler) override;
+
+ protected:
+  static constexpr int kMenuIndent = 4;
+
+  // The margin that we don't want to use for showing texts (e.g. round screen, or screen with
+  // rounded corners).
+  const int margin_width_;
+  const int margin_height_;
+
+  // Number of frames per sec (default: 30) for both parts of the animation.
+  const int animation_fps_;
+
+  // The scale factor from dp to pixels. 1.0 for mdpi, 4.0 for xxxhdpi.
+  const float density_;
+
+  virtual bool InitTextParams();
+
+  virtual bool LoadWipeDataMenuText();
+
+  // Creates a GraphicMenu with |graphic_header| and |graphic_items|. If the GraphicMenu isn't
+  // valid or it doesn't fit on the screen; falls back to create a TextMenu instead. If succeeds,
+  // returns a unique pointer to the created menu; otherwise returns nullptr.
+  virtual std::unique_ptr<Menu> CreateMenu(const GRSurface* graphic_header,
+                                           const std::vector<const GRSurface*>& graphic_items,
+                                           const std::vector<std::string>& text_headers,
+                                           const std::vector<std::string>& text_items,
+                                           size_t initial_selection) const;
+
+  // Creates a TextMenu with |text_headers| and |text_items|; and sets the menu selection to
+  // |initial_selection|.
+  virtual std::unique_ptr<Menu> CreateMenu(const std::vector<std::string>& text_headers,
+                                           const std::vector<std::string>& text_items,
+                                           size_t initial_selection) const;
+
+  // Takes the ownership of |menu| and displays it.
+  virtual size_t ShowMenu(std::unique_ptr<Menu>&& menu, bool menu_only,
+                          const std::function<int(int, bool)>& key_handler);
+
+  // Sets the menu highlight to the given index, wrapping if necessary. Returns the actual item
+  // selected.
+  virtual int SelectMenu(int sel);
+
+  virtual void draw_background_locked();
+  virtual void draw_foreground_locked();
+  virtual void draw_screen_locked();
+  virtual void draw_menu_and_text_buffer_locked(const std::vector<std::string>& help_message);
+  virtual void update_screen_locked();
+  virtual void update_progress_locked();
+
+  const GRSurface* GetCurrentFrame() const;
+  const GRSurface* GetCurrentText() const;
+
+  void ProgressThreadLoop();
+
+  virtual void ShowFile(FILE*);
+  virtual void PrintV(const char*, bool, va_list);
+  void PutChar(char);
+  void ClearText();
+
+  void LoadAnimation();
+  std::unique_ptr<GRSurface> LoadBitmap(const std::string& filename);
+  std::unique_ptr<GRSurface> LoadLocalizedBitmap(const std::string& filename);
+
+  int PixelsFromDp(int dp) const;
+  virtual int GetAnimationBaseline() const;
+  virtual int GetProgressBaseline() const;
+  virtual int GetTextBaseline() const;
+
+  // Returns pixel width of draw buffer.
+  virtual int ScreenWidth() const;
+  // Returns pixel height of draw buffer.
+  virtual int ScreenHeight() const;
+
+  // Implementation of the draw functions in DrawInterface.
+  void SetColor(UIElement e) const override;
+  void DrawHighlightBar(int x, int y, int width, int height) const override;
+  int DrawHorizontalRule(int y) const override;
+  void DrawSurface(const GRSurface* surface, int sx, int sy, int w, int h, int dx,
+                   int dy) const override;
+  void DrawFill(int x, int y, int w, int h) const override;
+  void DrawTextIcon(int x, int y, const GRSurface* surface) const override;
+  int DrawTextLine(int x, int y, const std::string& line, bool bold) const override;
+  int DrawTextLines(int x, int y, const std::vector<std::string>& lines) const override;
+  int DrawWrappedTextLines(int x, int y, const std::vector<std::string>& lines) const override;
+
+  // The layout to use.
+  int layout_;
+
+  // The images that contain localized texts.
+  std::unique_ptr<GRSurface> erasing_text_;
+  std::unique_ptr<GRSurface> error_text_;
+  std::unique_ptr<GRSurface> installing_text_;
+  std::unique_ptr<GRSurface> no_command_text_;
+
+  // Localized text images for the wipe data menu.
+  std::unique_ptr<GRSurface> cancel_wipe_data_text_;
+  std::unique_ptr<GRSurface> factory_data_reset_text_;
+  std::unique_ptr<GRSurface> try_again_text_;
+  std::unique_ptr<GRSurface> wipe_data_confirmation_text_;
+  std::unique_ptr<GRSurface> wipe_data_menu_header_text_;
+
+  std::unique_ptr<GRSurface> fastbootd_logo_;
+
+  // current_icon_ points to one of the frames in intro_frames_ or loop_frames_, indexed by
+  // current_frame_, or error_icon_.
+  Icon current_icon_;
+  std::unique_ptr<GRSurface> error_icon_;
+  std::vector<std::unique_ptr<GRSurface>> intro_frames_;
+  std::vector<std::unique_ptr<GRSurface>> loop_frames_;
+  size_t current_frame_;
+  bool intro_done_;
+
+  // progress_bar and stage_marker images.
+  std::unique_ptr<GRSurface> progress_bar_empty_;
+  std::unique_ptr<GRSurface> progress_bar_fill_;
+  std::unique_ptr<GRSurface> stage_marker_empty_;
+  std::unique_ptr<GRSurface> stage_marker_fill_;
+
+  ProgressType progressBarType;
+
+  float progressScopeStart, progressScopeSize, progress;
+  double progressScopeTime, progressScopeDuration;
+
+  // true when both graphics pages are the same (except for the progress bar).
+  bool pagesIdentical;
+
+  size_t text_cols_, text_rows_;
+
+  // Log text overlay, displayed when a magic key is pressed.
+  char** text_;
+  size_t text_col_, text_row_;
+
+  bool show_text;
+  bool show_text_ever;  // has show_text ever been true?
+
+  std::vector<std::string> title_lines_;
+
+  bool scrollable_menu_;
+  std::unique_ptr<Menu> menu_;
+
+  // An alternate text screen, swapped with 'text_' when we're viewing a log file.
+  char** file_viewer_text_;
+
+  std::thread progress_thread_;
+  std::atomic<bool> progress_thread_stopped_{ false };
+
+  int stage, max_stage;
+
+  int char_width_;
+  int char_height_;
+
+  // The locale that's used to show the rendered texts.
+  std::string locale_;
+  bool rtl_locale_;
+
+  std::mutex updateMutex;
+
+ private:
+  void SetLocale(const std::string&);
+
+  // Display the background texts for "erasing", "error", "no_command" and "installing" for the
+  // selected locale.
+  void SelectAndShowBackgroundText(const std::vector<std::string>& locales_entries, size_t sel);
+};
+
+#endif  // RECOVERY_UI_H
diff --git a/recovery_ui/include/recovery_ui/stub_ui.h b/recovery_ui/include/recovery_ui/stub_ui.h
new file mode 100644
index 0000000..fb1d8c7
--- /dev/null
+++ b/recovery_ui/include/recovery_ui/stub_ui.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef RECOVERY_STUB_UI_H
+#define RECOVERY_STUB_UI_H
+
+#include <functional>
+#include <string>
+#include <vector>
+
+#include "ui.h"
+
+// Stub implementation of RecoveryUI for devices without screen.
+class StubRecoveryUI : public RecoveryUI {
+ public:
+  StubRecoveryUI() = default;
+
+  std::string GetLocale() const override {
+    return "";
+  }
+  void SetBackground(Icon /* icon */) override {}
+  void SetSystemUpdateText(bool /* security_update */) override {}
+
+  // progress indicator
+  void SetProgressType(ProgressType /* type */) override {}
+  void ShowProgress(float /* portion */, float /* seconds */) override {}
+  void SetProgress(float /* fraction */) override {}
+
+  void SetStage(int /* current */, int /* max */) override {}
+
+  // text log
+  void ShowText(bool /* visible */) override {}
+  bool IsTextVisible() override {
+    return false;
+  }
+  bool WasTextEverVisible() override {
+    return false;
+  }
+
+  // printing messages
+  void Print(const char* fmt, ...) override {
+    va_list ap;
+    va_start(ap, fmt);
+    vprintf(fmt, ap);
+    va_end(ap);
+  }
+  void PrintOnScreenOnly(const char* /* fmt */, ...) override {}
+  void ShowFile(const std::string& /* filename */) override {}
+
+  // menu display
+  size_t ShowMenu(const std::vector<std::string>& /* headers */,
+                  const std::vector<std::string>& /* items */, size_t initial_selection,
+                  bool /* menu_only */,
+                  const std::function<int(int, bool)>& /* key_handler */) override {
+    return initial_selection;
+  }
+
+  size_t ShowPromptWipeDataMenu(const std::vector<std::string>& /* backup_headers */,
+                                const std::vector<std::string>& /* backup_items */,
+                                const std::function<int(int, bool)>& /* key_handle */) override {
+    return 0;
+  }
+
+  size_t ShowPromptWipeDataConfirmationMenu(
+      const std::vector<std::string>& /* backup_headers */,
+      const std::vector<std::string>& /* backup_items */,
+      const std::function<int(int, bool)>& /* key_handle */) override {
+    return 0;
+  }
+
+  void SetTitle(const std::vector<std::string>& /* lines */) override {}
+};
+
+#endif  // RECOVERY_STUB_UI_H
diff --git a/recovery_ui/include/recovery_ui/ui.h b/recovery_ui/include/recovery_ui/ui.h
new file mode 100644
index 0000000..d55322c
--- /dev/null
+++ b/recovery_ui/include/recovery_ui/ui.h
@@ -0,0 +1,272 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef RECOVERY_UI_H
+#define RECOVERY_UI_H
+
+#include <linux/input.h>  // KEY_MAX
+
+#include <atomic>
+#include <condition_variable>
+#include <functional>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+// Abstract class for controlling the user interface during recovery.
+class RecoveryUI {
+ public:
+  enum Icon {
+    NONE,
+    INSTALLING_UPDATE,
+    ERASING,
+    NO_COMMAND,
+    ERROR,
+  };
+
+  enum ProgressType {
+    EMPTY,
+    INDETERMINATE,
+    DETERMINATE,
+  };
+
+  enum KeyAction {
+    ENQUEUE,
+    TOGGLE,
+    REBOOT,
+    IGNORE,
+  };
+
+  enum class KeyError : int {
+    TIMED_OUT = -1,
+    INTERRUPTED = -2,
+  };
+
+  RecoveryUI();
+
+  virtual ~RecoveryUI();
+
+  // Initializes the object; called before anything else. UI texts will be initialized according
+  // to the given locale. Returns true on success.
+  virtual bool Init(const std::string& locale);
+
+  virtual std::string GetLocale() const = 0;
+
+  // Shows a stage indicator. Called immediately after Init().
+  virtual void SetStage(int current, int max) = 0;
+
+  // Sets the overall recovery state ("background image").
+  virtual void SetBackground(Icon icon) = 0;
+  virtual void SetSystemUpdateText(bool security_update) = 0;
+
+  // --- progress indicator ---
+  virtual void SetProgressType(ProgressType determinate) = 0;
+
+  // Shows a progress bar and define the scope of the next operation:
+  //   portion - fraction of the progress bar the next operation will use
+  //   seconds - expected time interval (progress bar moves at this minimum rate)
+  virtual void ShowProgress(float portion, float seconds) = 0;
+
+  // Sets progress bar position (0.0 - 1.0 within the scope defined by the last call to
+  // ShowProgress).
+  virtual void SetProgress(float fraction) = 0;
+
+  // --- text log ---
+
+  virtual void ShowText(bool visible) = 0;
+
+  virtual bool IsTextVisible() = 0;
+
+  virtual bool WasTextEverVisible() = 0;
+
+  // Writes a message to the on-screen log (shown if the user has toggled on the text display).
+  // Print() will also dump the message to stdout / log file, while PrintOnScreenOnly() not.
+  virtual void Print(const char* fmt, ...) __printflike(2, 3) = 0;
+  virtual void PrintOnScreenOnly(const char* fmt, ...) __printflike(2, 3) = 0;
+
+  // Shows the contents of the given file. Caller ensures the patition that contains the file has
+  // been mounted.
+  virtual void ShowFile(const std::string& filename) = 0;
+
+  // --- key handling ---
+
+  // Waits for a key and return it. May return TIMED_OUT after timeout and
+  // KeyError::INTERRUPTED on a key interrupt.
+  virtual int WaitKey();
+
+  // Wakes up the UI if it is waiting on key input, causing WaitKey to return KeyError::INTERRUPTED.
+  virtual void InterruptKey();
+
+  virtual bool IsKeyPressed(int key);
+  virtual bool IsLongPress();
+
+  // Returns true if you have the volume up/down and power trio typical of phones and tablets, false
+  // otherwise.
+  virtual bool HasThreeButtons();
+
+  // Returns true if it has a power key.
+  virtual bool HasPowerKey() const;
+
+  // Returns true if it supports touch inputs.
+  virtual bool HasTouchScreen() const;
+
+  // Erases any queued-up keys.
+  virtual void FlushKeys();
+
+  // Called on each key press, even while operations are in progress. Return value indicates whether
+  // an immediate operation should be triggered (toggling the display, rebooting the device), or if
+  // the key should be enqueued for use by the main thread.
+  virtual KeyAction CheckKey(int key, bool is_long_press);
+
+  // Called when a key is held down long enough to have been a long-press (but before the key is
+  // released). This means that if the key is eventually registered (released without any other keys
+  // being pressed in the meantime), CheckKey will be called with 'is_long_press' true.
+  virtual void KeyLongPress(int key);
+
+  // Normally in recovery there's a key sequence that triggers immediate reboot of the device,
+  // regardless of what recovery is doing (with the default CheckKey implementation, it's pressing
+  // the power button 7 times in row). Call this to enable or disable that feature. It is enabled by
+  // default.
+  virtual void SetEnableReboot(bool enabled);
+
+  // --- menu display ---
+
+  virtual void SetTitle(const std::vector<std::string>& lines) = 0;
+
+  // Displays a menu with the given 'headers' and 'items'. The supplied 'key_handler' callback,
+  // which is typically bound to Device::HandleMenuKey(), should return the expected action for the
+  // given key code and menu visibility (e.g. to move the cursor or to select an item). Caller sets
+  // 'menu_only' to true to ensure only a menu item gets selected and returned. Otherwise if
+  // 'menu_only' is false, ShowMenu() will forward any non-negative value returned from the
+  // key_handler, which may be beyond the range of menu items. This could be used to trigger a
+  // device-specific action, even without that being listed in the menu. Caller needs to handle
+  // such a case accordingly (e.g. by calling Device::InvokeMenuItem() to process the action).
+  // Returns a non-negative value (the chosen item number or device-specific action code), or
+  // static_cast<size_t>(TIMED_OUT) if timed out waiting for input or
+  // static_cast<size_t>(ERR_KEY_INTERTUPT) if interrupted, such as by InterruptKey().
+  virtual size_t ShowMenu(const std::vector<std::string>& headers,
+                          const std::vector<std::string>& items, size_t initial_selection,
+                          bool menu_only, const std::function<int(int, bool)>& key_handler) = 0;
+
+  // Displays the localized wipe data menu with pre-generated graphs. If there's an issue
+  // with the graphs, falls back to use the backup string headers and items instead. The initial
+  // selection is the 0th item in the menu, which is expected to reboot the device without a wipe.
+  virtual size_t ShowPromptWipeDataMenu(const std::vector<std::string>& backup_headers,
+                                        const std::vector<std::string>& backup_items,
+                                        const std::function<int(int, bool)>& key_handler) = 0;
+  // Displays the localized wipe data confirmation menu with pre-generated images. Falls back to
+  // the text strings upon failures. The initial selection is the 0th item, which returns to the
+  // upper level menu.
+  virtual size_t ShowPromptWipeDataConfirmationMenu(
+      const std::vector<std::string>& backup_headers, const std::vector<std::string>& backup_items,
+      const std::function<int(int, bool)>& key_handler) = 0;
+
+  // Set whether or not the fastbootd logo is displayed.
+  void SetEnableFastbootdLogo(bool enable) {
+    fastbootd_logo_enabled_ = enable;
+  }
+
+  // Resets the key interrupt status.
+  void ResetKeyInterruptStatus() {
+    key_interrupted_ = false;
+  }
+
+  // Returns the key interrupt status.
+  bool IsKeyInterrupted() const {
+    return key_interrupted_;
+  }
+
+ protected:
+  void EnqueueKey(int key_code);
+
+  // The normal and dimmed brightness percentages (default: 50 and 25, which means 50% and 25% of
+  // the max_brightness). Because the absolute values may vary across devices. These two values can
+  // be configured via subclassing. Setting brightness_normal_ to 0 to disable screensaver.
+  unsigned int brightness_normal_;
+  unsigned int brightness_dimmed_;
+  std::string brightness_file_;
+  std::string max_brightness_file_;
+
+  // Whether we should listen for touch inputs (default: false).
+  bool touch_screen_allowed_;
+
+  bool fastbootd_logo_enabled_;
+
+ private:
+  enum class ScreensaverState {
+    DISABLED,
+    NORMAL,
+    DIMMED,
+    OFF,
+  };
+
+  // The sensitivity when detecting a swipe.
+  const int touch_low_threshold_;
+  const int touch_high_threshold_;
+
+  void OnKeyDetected(int key_code);
+  void OnTouchDetected(int dx, int dy);
+  int OnInputEvent(int fd, uint32_t epevents);
+  void ProcessKey(int key_code, int updown);
+  void TimeKey(int key_code, int count);
+
+  bool IsUsbConnected();
+
+  bool InitScreensaver();
+  void SetScreensaverState(ScreensaverState state);
+  // Key event input queue
+  std::mutex key_queue_mutex;
+  std::condition_variable key_queue_cond;
+  bool key_interrupted_;
+  int key_queue[256], key_queue_len;
+  char key_pressed[KEY_MAX + 1];  // under key_queue_mutex
+  int key_last_down;              // under key_queue_mutex
+  bool key_long_press;            // under key_queue_mutex
+  int key_down_count;             // under key_queue_mutex
+  bool enable_reboot;             // under key_queue_mutex
+  int rel_sum;
+
+  int consecutive_power_keys;
+  int last_key;
+
+  bool has_power_key;
+  bool has_up_key;
+  bool has_down_key;
+  bool has_touch_screen;
+
+  // Touch event related variables. See the comments in RecoveryUI::OnInputEvent().
+  int touch_slot_;
+  int touch_X_;
+  int touch_Y_;
+  int touch_start_X_;
+  int touch_start_Y_;
+  bool touch_finger_down_;
+  bool touch_swiping_;
+  bool is_bootreason_recovery_ui_;
+
+  std::thread input_thread_;
+  std::atomic<bool> input_thread_stopped_{ false };
+
+  ScreensaverState screensaver_state_;
+
+  // The following two contain the absolute values computed from brightness_normal_ and
+  // brightness_dimmed_ respectively.
+  unsigned int brightness_normal_value_;
+  unsigned int brightness_dimmed_value_;
+};
+
+#endif  // RECOVERY_UI_H
diff --git a/recovery_ui/include/recovery_ui/vr_ui.h b/recovery_ui/include/recovery_ui/vr_ui.h
new file mode 100644
index 0000000..2e8ac59
--- /dev/null
+++ b/recovery_ui/include/recovery_ui/vr_ui.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef RECOVERY_VR_UI_H
+#define RECOVERY_VR_UI_H
+
+#include <string>
+
+#include "screen_ui.h"
+
+class VrRecoveryUI : public ScreenRecoveryUI {
+ public:
+  VrRecoveryUI();
+
+ protected:
+  // Pixel offsets to move drawing functions to visible range.
+  // Can vary per device depending on screen size and lens distortion.
+  const int stereo_offset_;
+
+  int ScreenWidth() const override;
+  int ScreenHeight() const override;
+
+  void DrawSurface(const GRSurface* surface, int sx, int sy, int w, int h, int dx,
+                   int dy) const override;
+  int DrawHorizontalRule(int y) const override;
+  void DrawHighlightBar(int x, int y, int width, int height) const override;
+  void DrawFill(int x, int y, int w, int h) const override;
+  void DrawTextIcon(int x, int y, const GRSurface* surface) const override;
+  int DrawTextLine(int x, int y, const std::string& line, bool bold) const override;
+};
+
+#endif  // RECOVERY_VR_UI_H
diff --git a/recovery_ui/include/recovery_ui/wear_ui.h b/recovery_ui/include/recovery_ui/wear_ui.h
new file mode 100644
index 0000000..429af69
--- /dev/null
+++ b/recovery_ui/include/recovery_ui/wear_ui.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef RECOVERY_WEAR_UI_H
+#define RECOVERY_WEAR_UI_H
+
+#include <string>
+#include <vector>
+
+#include "screen_ui.h"
+
+class WearRecoveryUI : public ScreenRecoveryUI {
+ public:
+  WearRecoveryUI();
+
+  void SetStage(int current, int max) override;
+
+ protected:
+  // progress bar vertical position, it's centered horizontally
+  const int progress_bar_baseline_;
+
+  // Unusable rows when displaying the recovery menu, including the lines for headers (Android
+  // Recovery, build id and etc) and the bottom lines that may otherwise go out of the screen.
+  const int menu_unusable_rows_;
+
+  std::unique_ptr<Menu> CreateMenu(const std::vector<std::string>& text_headers,
+                                   const std::vector<std::string>& text_items,
+                                   size_t initial_selection) const override;
+
+  int GetProgressBaseline() const override;
+
+  void update_progress_locked() override;
+
+ private:
+  void draw_background_locked() override;
+  void draw_screen_locked() override;
+};
+
+#endif  // RECOVERY_WEAR_UI_H