Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Recovery UI 實現原理剖析:直接刷 framebuffer 是怎麼做到的

編輯:關於 Android 程式設計

先回答一個常見問題:recovery 到底是什麼?網路上已經有各種解釋,這裡只從技術角度切入。

本質上,recovery 與 Android 是兩個獨立的 rootfs,只是 recovery 存在的意義就是為 Android 服務,因此常被視為 Android 系統的一部分。作為一個極簡的 rootfs,recovery 只提供了非常有限的功能、只帶了幾個簡單的函式庫,而它的 UI 並不是走 SurfaceFlinger 那套,而是直接刷 framebuffer。對習慣 framework 與 app 層開發的人來說這相對陌生,值得梳理一遍。

先看 main 函式裡與 UI 相關的部分

main(int argc, char **argv) {
    …………
    Device* device = make_device();
    ui = device->GetUI();
    gCurrentUI = ui;
    ui->Init();
    ui->SetLocale(locale);
    ui->SetBackground(RecoveryUI::NONE);
    if (show_text) ui->ShowText(true);
    …………
    if (status != INSTALL_SUCCESS || ui->IsTextVisible()) {
        prompt_and_wait(device, status);
    }
    …………
}

整段流程可以拆成幾步:

  1. 建立 Device 物件,它封裝了包含 UI 在內的多項操作。
  2. 呼叫 GetUI() 取得 DefaultUI 物件。recovery 涉及三個 UI 類別,彼此為繼承關係:DefaultUI → ScreenRecoveryUI → RecoveryUI。
  3. 呼叫 Init()。DefaultUI 沒有實作 Init,因此實際走的是父類 ScreenRecoveryUI 的版本。
  4. 同理,SetLocale() 與 SetBackground() 也都落在 ScreenRecoveryUI,分別用來標記特殊排版區域與設定初始背景圖。
  5. 最後顯示主界面,也就是那個我們熟悉的选择選單。

ScreenRecoveryUI::Init()

void ScreenRecoveryUI::Init() {
    gr_init();
    gr_font_size(&char_width, &char_height);

    text_col = text_row = 0;
    text_rows = gr_fb_height() / char_height;
    if (text_rows > kMaxRows) text_rows = kMaxRows;
    text_top = 1;
    text_cols = gr_fb_width() / char_width;
    if (text_cols > kMaxCols - 1) text_cols = kMaxCols - 1;

    LoadBitmap("icon_installing", &backgroundIcon[INSTALLING_UPDATE]);
    backgroundIcon[ERASING] = backgroundIcon[INSTALLING_UPDATE];
    LoadBitmap("icon_error", &backgroundIcon[ERROR]);
    backgroundIcon[NO_COMMAND] = backgroundIcon[ERROR];

    LoadBitmap("progress_empty", &progressBarEmpty);
    LoadBitmap("progress_fill", &progressBarFill);

    LoadLocalizedBitmap("installing_text", &backgroundText[INSTALLING_UPDATE]);
    LoadLocalizedBitmap("erasing_text", &backgroundText[ERASING]);
    LoadLocalizedBitmap("no_command_text", &backgroundText[NO_COMMAND]);
    LoadLocalizedBitmap("error_text", &backgroundText[ERROR]);

    int i;
    progressBarIndeterminate =
            (gr_surface*)malloc(indeterminate_frames * sizeof(gr_surface));
    for (i = 0; i < indeterminate_frames; ++i) {
        char filename[40];
        // "indeterminate01.png", "indeterminate02.png", ...
        sprintf(filename, "indeterminate%02d", i + 1);
        LoadBitmap(filename, progressBarIndeterminate + i);
    }

    if (installing_frames > 0) {
        installationOverlay =
                (gr_surface*)malloc(installing_frames * sizeof(gr_surface));
        for (i = 0; i < installing_frames; ++i) {
            char filename[40];
            sprintf(filename, "icon_installing_overlay%02d", i + 1);
            LoadBitmap(filename, installationOverlay + i);
        }
    } else {
        installationOverlay = NULL;
    }

    pthread_create(&progress_t, NULL, progress_thread, NULL);
    RecoveryUI::Init();
}

逐項說明:

  • gr_init():初始化圖形設備,配置供 Pixelflinger 庫渲染用的記憶體。
  • gr_font_size():把字型對應的 surface 長寬寫入 char_width 與 char_height。
  • LoadBitmap():把每張 png 轉成一個 surface,全部放進同一個陣列管理。
  • LoadLocalizedBitmap():依當前 locale 從圖片中提取對應的文字資訊生成 surface,同樣放進陣列。
  • pthread_create(progress_thread):建立一個無窮迴圈的執行緒,持續檢查 currentIcon 與 progressBarType 決定是否更新進度條。
  • 最後呼叫 RecoveryUI 的 Init(),初始化輸入事件處理。

SetLocale:處理由右到左的語言

void ScreenRecoveryUI::SetLocale(const char* locale) {
    if (locale) {
        char* lang = strdup(locale);
        for (char* p = lang; *p; ++p) {
            if (*p == '_') { *p = '\0'; break; }
        }
        // 明確列出支援的 RTL 語言
        if (strcmp(lang, "ar") == 0 ||   // Arabic
            strcmp(lang, "fa") == 0 ||   // Persian (Farsi)
            strcmp(lang, "he") == 0 ||   // Hebrew (新語言碼)
            strcmp(lang, "iw") == 0 ||   // Hebrew (舊語言碼)
            strcmp(lang, "ur") == 0) {   // Urdu
            rtl_locale = true;
        }
        free(lang);
    }
}

這個函式判斷當前語言是否屬於阿拉伯語系。阿拉伯語的書寫方向是由右到左,若是則設一個旗標,後續繪製文字與進度條時依此決定方向。

locale 的來源有兩處:優先從 command 檔讀取(例如 --locale=zh_CN);若未指定,初始化過程會嘗試讀 /cache/recovery/last_locale;兩者都沒有時 locale 不被赋值,也就是預設使用英文。

SetBackground 與畫面更新的核心

void ScreenRecoveryUI::SetBackground(Icon icon) {
    pthread_mutex_lock(&updateMutex);
    // 依底圖在螢幕上的位置做偏移補償
    if (backgroundIcon[icon] != NULL) {
        gr_surface bg = backgroundIcon[icon];
        gr_surface text = backgroundText[icon];
        overlay_offset_x = install_overlay_offset_x
                + (gr_fb_width() - gr_get_width(bg)) / 2;
        overlay_offset_y = install_overlay_offset_y
                + (gr_fb_height() - (gr_get_height(bg) + gr_get_height(text) + 40)) / 2;
    }
    currentIcon = icon;
    update_screen_locked();
    pthread_mutex_unlock(&updateMutex);
}

關鍵邏輯都在 update_screen_locked() 裡。update_screen_locked() 與 update_progress_locked() 是整個 UI 部分的兩根支柱,分別負責更新背景與進度條;由於畫面持續在變,這兩個函式會在不同地方被反覆呼叫。

void ScreenRecoveryUI::update_screen_locked() {
    draw_screen_locked();
    gr_flip();
}

可見它只做兩件事:更新畫面內容,然後切換前後 buffer。

draw_screen_locked:把元件疊上去

void ScreenRecoveryUI::draw_screen_locked() {
    draw_background_locked(currentIcon);
    draw_progress_locked();

    if (show_text) {
        SetColor(TEXT_FILL);
        gr_fill(0, 0, gr_fb_width(), gr_fb_height());

        int y = 0;
        int i = 0;
        if (show_menu) {
            SetColor(HEADER);
            for (; i < menu_top + menu_items; ++i) {
                if (i == menu_top) SetColor(MENU);
                if (i == menu_top + menu_sel) {
                    // 畫出選取項的高亮底色
                    SetColor(MENU_SEL_BG);
                    gr_fill(0, y - 2, gr_fb_width(), y + char_height + 2);
                    // 選取項使用白色文字
                    SetColor(MENU_SEL_FG);
                    if (menu[i][0]) gr_text(4, y, menu[i], 1);
                    SetColor(MENU);
                } else {
                    if (menu[i][0]) gr_text(4, y, menu[i], i < menu_top);
                }
                y += char_height + 4;
            }
            SetColor(MENU);
            y += 4;
            gr_fill(0, y, gr_fb_width(), y + 2);
            y += 4;
            ++i;
        }

        SetColor(LOG);
        // 從下往上顯示,直到碰到螢幕頂端、選單底部或整個文字緩衝區顯示完畢
        int ty;
        int row = (text_top + text_rows - 1) % text_rows;
        for (int ty = gr_fb_height() - char_height, count = 0;
             ty > y + 2 && count < text_rows;
             ty -= char_height, ++count) {
            gr_text(4, ty, text[row], 0);
            --row;
            if (row < 0) row = text_rows - 1;
        }
    }
}

minui:recovery 的繪圖基礎

上面出現的 gr_ 開頭函式都來自 minui 庫,源碼就在 recovery 的 minui 目錄下。它提供了圖形描繪與固定尺寸文字顯示的能力:

gr_color(unsigned char r, unsigned char g, unsigned char b, unsigned char a);
/* 設定字型顏色 */

gr_fill(int x, int y, int w, int h);
/* 填滿矩形區域,參數為起始座標與區域大小 */

gr_blit(gr_surface source, int sx, int sy, int w, int h, int dx, int dy);
/* 貼上由 source 指定的圖片 */

draw_background_locked() 的做法是:先把整個渲染 buffer 填成黑色,再算出背景 surface 與文字 surface 的長寬,結合 framebuffer 的尺寸推出各自的繪製座標,最後呼叫 Pixelflinger 的介面完成渲染。

draw_progress_locked:進度條的兩種型態

void ScreenRecoveryUI::draw_progress_locked() {
    if (currentIcon == ERROR) return;
    if (currentIcon == INSTALLING_UPDATE || currentIcon == ERASING) {
        draw_install_overlay_locked(installingFrame);
    }

    if (progressBarType != EMPTY) {
        int iconHeight = gr_get_height(backgroundIcon[INSTALLING_UPDATE]);
        int width  = gr_get_width(progressBarEmpty);
        int height = gr_get_height(progressBarEmpty);
        int dx = (gr_fb_width() - width) / 2;
        int dy = (3 * gr_fb_height() + iconHeight - 2 * height) / 4;

        // 先把進度條背後擦掉,處理「只更新進度條」的情況
        gr_color(0, 0, 0, 255);
        gr_fill(dx, dy, width, height);

        if (progressBarType == DETERMINATE) {
            float p = progressScopeStart + progress * progressScopeSize;
            int pos = (int) (p * width);
            if (rtl_locale) {
                // 由右到左填滿
                if (pos > 0)
                    gr_blit(progressBarFill, width - pos, 0, pos, height, dx + width - pos, dy);
                if (pos < width - 1)
                    gr_blit(progressBarEmpty, 0, 0, width - pos, height, dx, dy);
            } else {
                // 由左到右填滿
                if (pos > 0)
                    gr_blit(progressBarFill, 0, 0, pos, height, dx, dy);
                if (pos < width - 1)
                    gr_blit(progressBarEmpty, pos, 0, width - pos, height, dx + pos, dy);
            }
        }

        if (progressBarType == INDETERMINATE) {
            static int frame = 0;
            gr_blit(progressBarIndeterminate[frame], 0, 0, width, height, dx, dy);
            // RTL 語言下動畫反向播放,讓轉圈方向相反
            if (rtl_locale) {
                frame = (frame + indeterminate_frames - 1) % indeterminate_frames;
            } else {
                frame = (frame + 1) % indeterminate_frames;
            }
        }
    }
}

原理與 update_screen_locked() 類似,最終都是把進度條的 surface 輸出到渲染 buffer。recovery 各個場景的畫面,就是由背景、文字、進度條三者疊合而成,差別只在使用的 surface 與座標不同。

minui 介面速查

int gr_init(void);          /* 初始化圖形顯示:開設備、配置記憶體、初始化參數 */
void gr_exit(void);         /* 註銷圖形顯示:關設備並釋放記憶體 */
int gr_fb_width(void);      /* 取得螢幕寬度 */
int gr_fb_height(void);     /* 取得螢幕高度 */
gr_pixel *gr_fb_data(void); /* 取得顯示資料緩衝區位址 */
void gr_flip(void);         /* 刷新顯示內容 */
void gr_fb_blank(bool blank); /* 清屏 */
void gr_color(unsigned char r, unsigned char g, unsigned char b, unsigned char a);
void gr_fill(int x, int y, int w, int h);
int gr_text(int x, int y, const char *s);   /* 顯示字串 */
int gr_measure(const char *s);              /* 取得字串佔用的像素長度 */
void gr_font_size(int *x, int *y);          /* 取得單一字元長寬 */
void gr_blit(gr_surface source, int sx, int sy, int w, int h, int dx, int dy);
unsigned int gr_get_width(gr_surface surface);
unsigned int gr_get_height(gr_surface surface);

/* 依 mk 檔中指定的相對路徑建立顯示資源 */
int res_create_surface(const char* name, gr_surface* pSurface);
void res_free_surface(gr_surface surface);  /* 釋放資源 */

總結來說,recovery 的 UI 部分難度並不高:應用層呼叫 minui 完成圖形描繪與文字顯示,minui 再往下呼叫 Pixelflinger 進行渲染。理解這一層之後,要客製化 recovery 的介面(換圖、改選單、調整排版)就只是替換資源與改座標的問題了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved