1 /*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <dirent.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <linux/input.h>
21 #include <pthread.h>
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/time.h>
28 #include <sys/types.h>
29 #include <time.h>
30 #include <unistd.h>
31
32 #include <vector>
33
34 #include <android-base/strings.h>
35 #include <android-base/stringprintf.h>
36 #include <cutils/properties.h>
37
38 #include "common.h"
39 #include "device.h"
40 #include "minui/minui.h"
41 #include "screen_ui.h"
42 #include "ui.h"
43
44 #define TEXT_INDENT 4
45
46 // Return the current time as a double (including fractions of a second).
now()47 static double now() {
48 struct timeval tv;
49 gettimeofday(&tv, nullptr);
50 return tv.tv_sec + tv.tv_usec / 1000000.0;
51 }
52
ScreenRecoveryUI()53 ScreenRecoveryUI::ScreenRecoveryUI() :
54 currentIcon(NONE),
55 locale(nullptr),
56 progressBarType(EMPTY),
57 progressScopeStart(0),
58 progressScopeSize(0),
59 progress(0),
60 pagesIdentical(false),
61 text_cols_(0),
62 text_rows_(0),
63 text_(nullptr),
64 text_col_(0),
65 text_row_(0),
66 text_top_(0),
67 show_text(false),
68 show_text_ever(false),
69 menu_(nullptr),
70 show_menu(false),
71 menu_items(0),
72 menu_sel(0),
73 file_viewer_text_(nullptr),
74 intro_frames(0),
75 loop_frames(0),
76 current_frame(0),
77 intro_done(false),
78 animation_fps(30), // TODO: there's currently no way to infer this.
79 stage(-1),
80 max_stage(-1),
81 updateMutex(PTHREAD_MUTEX_INITIALIZER),
82 rtl_locale(false) {
83 }
84
GetCurrentFrame()85 GRSurface* ScreenRecoveryUI::GetCurrentFrame() {
86 if (currentIcon == INSTALLING_UPDATE || currentIcon == ERASING) {
87 return intro_done ? loopFrames[current_frame] : introFrames[current_frame];
88 }
89 return error_icon;
90 }
91
GetCurrentText()92 GRSurface* ScreenRecoveryUI::GetCurrentText() {
93 switch (currentIcon) {
94 case ERASING: return erasing_text;
95 case ERROR: return error_text;
96 case INSTALLING_UPDATE: return installing_text;
97 case NO_COMMAND: return no_command_text;
98 case NONE: abort();
99 }
100 }
101
PixelsFromDp(int dp)102 int ScreenRecoveryUI::PixelsFromDp(int dp) {
103 return dp * density_;
104 }
105
106 // Here's the intended layout:
107
108 // | portrait large landscape large
109 // ---------+-------------------------------------------------
110 // gap | 220dp 366dp 142dp 284dp
111 // icon | (200dp)
112 // gap | 68dp 68dp 56dp 112dp
113 // text | (14sp)
114 // gap | 32dp 32dp 26dp 52dp
115 // progress | (2dp)
116 // gap | 194dp 340dp 131dp 262dp
117
118 // Note that "baseline" is actually the *top* of each icon (because that's how our drawing
119 // routines work), so that's the more useful measurement for calling code.
120
121 enum Layout { PORTRAIT = 0, PORTRAIT_LARGE = 1, LANDSCAPE = 2, LANDSCAPE_LARGE = 3, LAYOUT_MAX };
122 enum Dimension { PROGRESS = 0, TEXT = 1, ICON = 2, DIMENSION_MAX };
123 static constexpr int kLayouts[LAYOUT_MAX][DIMENSION_MAX] = {
124 { 194, 32, 68, }, // PORTRAIT
125 { 340, 32, 68, }, // PORTRAIT_LARGE
126 { 131, 26, 56, }, // LANDSCAPE
127 { 262, 52, 112, }, // LANDSCAPE_LARGE
128 };
129
GetAnimationBaseline()130 int ScreenRecoveryUI::GetAnimationBaseline() {
131 return GetTextBaseline() - PixelsFromDp(kLayouts[layout_][ICON]) -
132 gr_get_height(loopFrames[0]);
133 }
134
GetTextBaseline()135 int ScreenRecoveryUI::GetTextBaseline() {
136 return GetProgressBaseline() - PixelsFromDp(kLayouts[layout_][TEXT]) -
137 gr_get_height(installing_text);
138 }
139
GetProgressBaseline()140 int ScreenRecoveryUI::GetProgressBaseline() {
141 return gr_fb_height() - PixelsFromDp(kLayouts[layout_][PROGRESS]) -
142 gr_get_height(progressBarFill);
143 }
144
145 // Clear the screen and draw the currently selected background icon (if any).
146 // Should only be called with updateMutex locked.
draw_background_locked()147 void ScreenRecoveryUI::draw_background_locked() {
148 pagesIdentical = false;
149 gr_color(0, 0, 0, 255);
150 gr_clear();
151
152 if (currentIcon != NONE) {
153 if (max_stage != -1) {
154 int stage_height = gr_get_height(stageMarkerEmpty);
155 int stage_width = gr_get_width(stageMarkerEmpty);
156 int x = (gr_fb_width() - max_stage * gr_get_width(stageMarkerEmpty)) / 2;
157 int y = gr_fb_height() - stage_height;
158 for (int i = 0; i < max_stage; ++i) {
159 GRSurface* stage_surface = (i < stage) ? stageMarkerFill : stageMarkerEmpty;
160 gr_blit(stage_surface, 0, 0, stage_width, stage_height, x, y);
161 x += stage_width;
162 }
163 }
164
165 GRSurface* text_surface = GetCurrentText();
166 int text_x = (gr_fb_width() - gr_get_width(text_surface)) / 2;
167 int text_y = GetTextBaseline();
168 gr_color(255, 255, 255, 255);
169 gr_texticon(text_x, text_y, text_surface);
170 }
171 }
172
173 // Draws the animation and progress bar (if any) on the screen.
174 // Does not flip pages.
175 // Should only be called with updateMutex locked.
draw_foreground_locked()176 void ScreenRecoveryUI::draw_foreground_locked() {
177 if (currentIcon != NONE) {
178 GRSurface* frame = GetCurrentFrame();
179 int frame_width = gr_get_width(frame);
180 int frame_height = gr_get_height(frame);
181 int frame_x = (gr_fb_width() - frame_width) / 2;
182 int frame_y = GetAnimationBaseline();
183 gr_blit(frame, 0, 0, frame_width, frame_height, frame_x, frame_y);
184 }
185
186 if (progressBarType != EMPTY) {
187 int width = gr_get_width(progressBarEmpty);
188 int height = gr_get_height(progressBarEmpty);
189
190 int progress_x = (gr_fb_width() - width)/2;
191 int progress_y = GetProgressBaseline();
192
193 // Erase behind the progress bar (in case this was a progress-only update)
194 gr_color(0, 0, 0, 255);
195 gr_fill(progress_x, progress_y, width, height);
196
197 if (progressBarType == DETERMINATE) {
198 float p = progressScopeStart + progress * progressScopeSize;
199 int pos = (int) (p * width);
200
201 if (rtl_locale) {
202 // Fill the progress bar from right to left.
203 if (pos > 0) {
204 gr_blit(progressBarFill, width-pos, 0, pos, height,
205 progress_x+width-pos, progress_y);
206 }
207 if (pos < width-1) {
208 gr_blit(progressBarEmpty, 0, 0, width-pos, height, progress_x, progress_y);
209 }
210 } else {
211 // Fill the progress bar from left to right.
212 if (pos > 0) {
213 gr_blit(progressBarFill, 0, 0, pos, height, progress_x, progress_y);
214 }
215 if (pos < width-1) {
216 gr_blit(progressBarEmpty, pos, 0, width-pos, height,
217 progress_x+pos, progress_y);
218 }
219 }
220 }
221 }
222 }
223
SetColor(UIElement e)224 void ScreenRecoveryUI::SetColor(UIElement e) {
225 switch (e) {
226 case INFO:
227 gr_color(249, 194, 0, 255);
228 break;
229 case HEADER:
230 gr_color(247, 0, 6, 255);
231 break;
232 case MENU:
233 case MENU_SEL_BG:
234 gr_color(0, 106, 157, 255);
235 break;
236 case MENU_SEL_BG_ACTIVE:
237 gr_color(0, 156, 100, 255);
238 break;
239 case MENU_SEL_FG:
240 gr_color(255, 255, 255, 255);
241 break;
242 case LOG:
243 gr_color(196, 196, 196, 255);
244 break;
245 case TEXT_FILL:
246 gr_color(0, 0, 0, 160);
247 break;
248 default:
249 gr_color(255, 255, 255, 255);
250 break;
251 }
252 }
253
DrawHorizontalRule(int * y)254 void ScreenRecoveryUI::DrawHorizontalRule(int* y) {
255 SetColor(MENU);
256 *y += 4;
257 gr_fill(0, *y, gr_fb_width(), *y + 2);
258 *y += 4;
259 }
260
DrawTextLine(int x,int * y,const char * line,bool bold)261 void ScreenRecoveryUI::DrawTextLine(int x, int* y, const char* line, bool bold) {
262 gr_text(gr_sys_font(), x, *y, line, bold);
263 *y += char_height_ + 4;
264 }
265
DrawTextLines(int x,int * y,const char * const * lines)266 void ScreenRecoveryUI::DrawTextLines(int x, int* y, const char* const* lines) {
267 for (size_t i = 0; lines != nullptr && lines[i] != nullptr; ++i) {
268 DrawTextLine(x, y, lines[i], false);
269 }
270 }
271
272 static const char* REGULAR_HELP[] = {
273 "Use volume up/down and power.",
274 NULL
275 };
276
277 static const char* LONG_PRESS_HELP[] = {
278 "Any button cycles highlight.",
279 "Long-press activates.",
280 NULL
281 };
282
283 // Redraw everything on the screen. Does not flip pages.
284 // Should only be called with updateMutex locked.
draw_screen_locked()285 void ScreenRecoveryUI::draw_screen_locked() {
286 if (!show_text) {
287 draw_background_locked();
288 draw_foreground_locked();
289 } else {
290 gr_color(0, 0, 0, 255);
291 gr_clear();
292
293 int y = 0;
294 if (show_menu) {
295 char recovery_fingerprint[PROPERTY_VALUE_MAX];
296 property_get("ro.bootimage.build.fingerprint", recovery_fingerprint, "");
297
298 SetColor(INFO);
299 DrawTextLine(TEXT_INDENT, &y, "Android Recovery", true);
300 for (auto& chunk : android::base::Split(recovery_fingerprint, ":")) {
301 DrawTextLine(TEXT_INDENT, &y, chunk.c_str(), false);
302 }
303 DrawTextLines(TEXT_INDENT, &y, HasThreeButtons() ? REGULAR_HELP : LONG_PRESS_HELP);
304
305 SetColor(HEADER);
306 DrawTextLines(TEXT_INDENT, &y, menu_headers_);
307
308 SetColor(MENU);
309 DrawHorizontalRule(&y);
310 y += 4;
311 for (int i = 0; i < menu_items; ++i) {
312 if (i == menu_sel) {
313 // Draw the highlight bar.
314 SetColor(IsLongPress() ? MENU_SEL_BG_ACTIVE : MENU_SEL_BG);
315 gr_fill(0, y - 2, gr_fb_width(), y + char_height_ + 2);
316 // Bold white text for the selected item.
317 SetColor(MENU_SEL_FG);
318 gr_text(gr_sys_font(), 4, y, menu_[i], true);
319 SetColor(MENU);
320 } else {
321 gr_text(gr_sys_font(), 4, y, menu_[i], false);
322 }
323 y += char_height_ + 4;
324 }
325 DrawHorizontalRule(&y);
326 }
327
328 // display from the bottom up, until we hit the top of the
329 // screen, the bottom of the menu, or we've displayed the
330 // entire text buffer.
331 SetColor(LOG);
332 int row = (text_top_ + text_rows_ - 1) % text_rows_;
333 size_t count = 0;
334 for (int ty = gr_fb_height() - char_height_;
335 ty >= y && count < text_rows_;
336 ty -= char_height_, ++count) {
337 gr_text(gr_sys_font(), 0, ty, text_[row], false);
338 --row;
339 if (row < 0) row = text_rows_ - 1;
340 }
341 }
342 }
343
344 // Redraw everything on the screen and flip the screen (make it visible).
345 // Should only be called with updateMutex locked.
update_screen_locked()346 void ScreenRecoveryUI::update_screen_locked() {
347 draw_screen_locked();
348 gr_flip();
349 }
350
351 // Updates only the progress bar, if possible, otherwise redraws the screen.
352 // Should only be called with updateMutex locked.
update_progress_locked()353 void ScreenRecoveryUI::update_progress_locked() {
354 if (show_text || !pagesIdentical) {
355 draw_screen_locked(); // Must redraw the whole screen
356 pagesIdentical = true;
357 } else {
358 draw_foreground_locked(); // Draw only the progress bar and overlays
359 }
360 gr_flip();
361 }
362
363 // Keeps the progress bar updated, even when the process is otherwise busy.
ProgressThreadStartRoutine(void * data)364 void* ScreenRecoveryUI::ProgressThreadStartRoutine(void* data) {
365 reinterpret_cast<ScreenRecoveryUI*>(data)->ProgressThreadLoop();
366 return nullptr;
367 }
368
ProgressThreadLoop()369 void ScreenRecoveryUI::ProgressThreadLoop() {
370 double interval = 1.0 / animation_fps;
371 while (true) {
372 double start = now();
373 pthread_mutex_lock(&updateMutex);
374
375 bool redraw = false;
376
377 // update the installation animation, if active
378 // skip this if we have a text overlay (too expensive to update)
379 if ((currentIcon == INSTALLING_UPDATE || currentIcon == ERASING) && !show_text) {
380 if (!intro_done) {
381 if (current_frame == intro_frames - 1) {
382 intro_done = true;
383 current_frame = 0;
384 } else {
385 ++current_frame;
386 }
387 } else {
388 current_frame = (current_frame + 1) % loop_frames;
389 }
390
391 redraw = true;
392 }
393
394 // move the progress bar forward on timed intervals, if configured
395 int duration = progressScopeDuration;
396 if (progressBarType == DETERMINATE && duration > 0) {
397 double elapsed = now() - progressScopeTime;
398 float p = 1.0 * elapsed / duration;
399 if (p > 1.0) p = 1.0;
400 if (p > progress) {
401 progress = p;
402 redraw = true;
403 }
404 }
405
406 if (redraw) update_progress_locked();
407
408 pthread_mutex_unlock(&updateMutex);
409 double end = now();
410 // minimum of 20ms delay between frames
411 double delay = interval - (end-start);
412 if (delay < 0.02) delay = 0.02;
413 usleep((long)(delay * 1000000));
414 }
415 }
416
LoadBitmap(const char * filename,GRSurface ** surface)417 void ScreenRecoveryUI::LoadBitmap(const char* filename, GRSurface** surface) {
418 int result = res_create_display_surface(filename, surface);
419 if (result < 0) {
420 LOGE("couldn't load bitmap %s (error %d)\n", filename, result);
421 }
422 }
423
LoadLocalizedBitmap(const char * filename,GRSurface ** surface)424 void ScreenRecoveryUI::LoadLocalizedBitmap(const char* filename, GRSurface** surface) {
425 int result = res_create_localized_alpha_surface(filename, locale, surface);
426 if (result < 0) {
427 LOGE("couldn't load bitmap %s (error %d)\n", filename, result);
428 }
429 }
430
Alloc2d(size_t rows,size_t cols)431 static char** Alloc2d(size_t rows, size_t cols) {
432 char** result = new char*[rows];
433 for (size_t i = 0; i < rows; ++i) {
434 result[i] = new char[cols];
435 memset(result[i], 0, cols);
436 }
437 return result;
438 }
439
440 // Choose the right background string to display during update.
SetSystemUpdateText(bool security_update)441 void ScreenRecoveryUI::SetSystemUpdateText(bool security_update) {
442 if (security_update) {
443 LoadLocalizedBitmap("installing_security_text", &installing_text);
444 } else {
445 LoadLocalizedBitmap("installing_text", &installing_text);
446 }
447 Redraw();
448 }
449
InitTextParams()450 void ScreenRecoveryUI::InitTextParams() {
451 gr_init();
452
453 gr_font_size(gr_sys_font(), &char_width_, &char_height_);
454 text_rows_ = gr_fb_height() / char_height_;
455 text_cols_ = gr_fb_width() / char_width_;
456 }
457
Init()458 void ScreenRecoveryUI::Init() {
459 RecoveryUI::Init();
460 InitTextParams();
461
462 density_ = static_cast<float>(property_get_int32("ro.sf.lcd_density", 160)) / 160.f;
463
464 // Are we portrait or landscape?
465 layout_ = (gr_fb_width() > gr_fb_height()) ? LANDSCAPE : PORTRAIT;
466 // Are we the large variant of our base layout?
467 if (gr_fb_height() > PixelsFromDp(800)) ++layout_;
468
469 text_ = Alloc2d(text_rows_, text_cols_ + 1);
470 file_viewer_text_ = Alloc2d(text_rows_, text_cols_ + 1);
471 menu_ = Alloc2d(text_rows_, text_cols_ + 1);
472
473 text_col_ = text_row_ = 0;
474 text_top_ = 1;
475
476 LoadBitmap("icon_error", &error_icon);
477
478 LoadBitmap("progress_empty", &progressBarEmpty);
479 LoadBitmap("progress_fill", &progressBarFill);
480
481 LoadBitmap("stage_empty", &stageMarkerEmpty);
482 LoadBitmap("stage_fill", &stageMarkerFill);
483
484 // Background text for "installing_update" could be "installing update"
485 // or "installing security update". It will be set after UI init according
486 // to commands in BCB.
487 installing_text = nullptr;
488 LoadLocalizedBitmap("erasing_text", &erasing_text);
489 LoadLocalizedBitmap("no_command_text", &no_command_text);
490 LoadLocalizedBitmap("error_text", &error_text);
491
492 LoadAnimation();
493
494 pthread_create(&progress_thread_, nullptr, ProgressThreadStartRoutine, this);
495 }
496
LoadAnimation()497 void ScreenRecoveryUI::LoadAnimation() {
498 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir("/res/images"), closedir);
499 dirent* de;
500 std::vector<std::string> intro_frame_names;
501 std::vector<std::string> loop_frame_names;
502
503 while ((de = readdir(dir.get())) != nullptr) {
504 int value, num_chars;
505 if (sscanf(de->d_name, "intro%d%n.png", &value, &num_chars) == 1) {
506 intro_frame_names.emplace_back(de->d_name, num_chars);
507 } else if (sscanf(de->d_name, "loop%d%n.png", &value, &num_chars) == 1) {
508 loop_frame_names.emplace_back(de->d_name, num_chars);
509 }
510 }
511
512 intro_frames = intro_frame_names.size();
513 loop_frames = loop_frame_names.size();
514
515 // It's okay to not have an intro.
516 if (intro_frames == 0) intro_done = true;
517 // But you must have an animation.
518 if (loop_frames == 0) abort();
519
520 std::sort(intro_frame_names.begin(), intro_frame_names.end());
521 std::sort(loop_frame_names.begin(), loop_frame_names.end());
522
523 introFrames = new GRSurface*[intro_frames];
524 for (size_t i = 0; i < intro_frames; i++) {
525 LoadBitmap(intro_frame_names.at(i).c_str(), &introFrames[i]);
526 }
527
528 loopFrames = new GRSurface*[loop_frames];
529 for (size_t i = 0; i < loop_frames; i++) {
530 LoadBitmap(loop_frame_names.at(i).c_str(), &loopFrames[i]);
531 }
532 }
533
SetLocale(const char * new_locale)534 void ScreenRecoveryUI::SetLocale(const char* new_locale) {
535 this->locale = new_locale;
536 this->rtl_locale = false;
537
538 if (locale) {
539 char* lang = strdup(locale);
540 for (char* p = lang; *p; ++p) {
541 if (*p == '_') {
542 *p = '\0';
543 break;
544 }
545 }
546
547 // A bit cheesy: keep an explicit list of supported RTL languages.
548 if (strcmp(lang, "ar") == 0 || // Arabic
549 strcmp(lang, "fa") == 0 || // Persian (Farsi)
550 strcmp(lang, "he") == 0 || // Hebrew (new language code)
551 strcmp(lang, "iw") == 0 || // Hebrew (old language code)
552 strcmp(lang, "ur") == 0) { // Urdu
553 rtl_locale = true;
554 }
555 free(lang);
556 }
557 }
558
SetBackground(Icon icon)559 void ScreenRecoveryUI::SetBackground(Icon icon) {
560 pthread_mutex_lock(&updateMutex);
561
562 currentIcon = icon;
563 update_screen_locked();
564
565 pthread_mutex_unlock(&updateMutex);
566 }
567
SetProgressType(ProgressType type)568 void ScreenRecoveryUI::SetProgressType(ProgressType type) {
569 pthread_mutex_lock(&updateMutex);
570 if (progressBarType != type) {
571 progressBarType = type;
572 }
573 progressScopeStart = 0;
574 progressScopeSize = 0;
575 progress = 0;
576 update_progress_locked();
577 pthread_mutex_unlock(&updateMutex);
578 }
579
ShowProgress(float portion,float seconds)580 void ScreenRecoveryUI::ShowProgress(float portion, float seconds) {
581 pthread_mutex_lock(&updateMutex);
582 progressBarType = DETERMINATE;
583 progressScopeStart += progressScopeSize;
584 progressScopeSize = portion;
585 progressScopeTime = now();
586 progressScopeDuration = seconds;
587 progress = 0;
588 update_progress_locked();
589 pthread_mutex_unlock(&updateMutex);
590 }
591
SetProgress(float fraction)592 void ScreenRecoveryUI::SetProgress(float fraction) {
593 pthread_mutex_lock(&updateMutex);
594 if (fraction < 0.0) fraction = 0.0;
595 if (fraction > 1.0) fraction = 1.0;
596 if (progressBarType == DETERMINATE && fraction > progress) {
597 // Skip updates that aren't visibly different.
598 int width = gr_get_width(progressBarEmpty);
599 float scale = width * progressScopeSize;
600 if ((int) (progress * scale) != (int) (fraction * scale)) {
601 progress = fraction;
602 update_progress_locked();
603 }
604 }
605 pthread_mutex_unlock(&updateMutex);
606 }
607
SetStage(int current,int max)608 void ScreenRecoveryUI::SetStage(int current, int max) {
609 pthread_mutex_lock(&updateMutex);
610 stage = current;
611 max_stage = max;
612 pthread_mutex_unlock(&updateMutex);
613 }
614
PrintV(const char * fmt,bool copy_to_stdout,va_list ap)615 void ScreenRecoveryUI::PrintV(const char* fmt, bool copy_to_stdout, va_list ap) {
616 std::string str;
617 android::base::StringAppendV(&str, fmt, ap);
618
619 if (copy_to_stdout) {
620 fputs(str.c_str(), stdout);
621 }
622
623 pthread_mutex_lock(&updateMutex);
624 if (text_rows_ > 0 && text_cols_ > 0) {
625 for (const char* ptr = str.c_str(); *ptr != '\0'; ++ptr) {
626 if (*ptr == '\n' || text_col_ >= text_cols_) {
627 text_[text_row_][text_col_] = '\0';
628 text_col_ = 0;
629 text_row_ = (text_row_ + 1) % text_rows_;
630 if (text_row_ == text_top_) text_top_ = (text_top_ + 1) % text_rows_;
631 }
632 if (*ptr != '\n') text_[text_row_][text_col_++] = *ptr;
633 }
634 text_[text_row_][text_col_] = '\0';
635 update_screen_locked();
636 }
637 pthread_mutex_unlock(&updateMutex);
638 }
639
Print(const char * fmt,...)640 void ScreenRecoveryUI::Print(const char* fmt, ...) {
641 va_list ap;
642 va_start(ap, fmt);
643 PrintV(fmt, true, ap);
644 va_end(ap);
645 }
646
PrintOnScreenOnly(const char * fmt,...)647 void ScreenRecoveryUI::PrintOnScreenOnly(const char *fmt, ...) {
648 va_list ap;
649 va_start(ap, fmt);
650 PrintV(fmt, false, ap);
651 va_end(ap);
652 }
653
PutChar(char ch)654 void ScreenRecoveryUI::PutChar(char ch) {
655 pthread_mutex_lock(&updateMutex);
656 if (ch != '\n') text_[text_row_][text_col_++] = ch;
657 if (ch == '\n' || text_col_ >= text_cols_) {
658 text_col_ = 0;
659 ++text_row_;
660
661 if (text_row_ == text_top_) text_top_ = (text_top_ + 1) % text_rows_;
662 }
663 pthread_mutex_unlock(&updateMutex);
664 }
665
ClearText()666 void ScreenRecoveryUI::ClearText() {
667 pthread_mutex_lock(&updateMutex);
668 text_col_ = 0;
669 text_row_ = 0;
670 text_top_ = 1;
671 for (size_t i = 0; i < text_rows_; ++i) {
672 memset(text_[i], 0, text_cols_ + 1);
673 }
674 pthread_mutex_unlock(&updateMutex);
675 }
676
ShowFile(FILE * fp)677 void ScreenRecoveryUI::ShowFile(FILE* fp) {
678 std::vector<long> offsets;
679 offsets.push_back(ftell(fp));
680 ClearText();
681
682 struct stat sb;
683 fstat(fileno(fp), &sb);
684
685 bool show_prompt = false;
686 while (true) {
687 if (show_prompt) {
688 PrintOnScreenOnly("--(%d%% of %d bytes)--",
689 static_cast<int>(100 * (double(ftell(fp)) / double(sb.st_size))),
690 static_cast<int>(sb.st_size));
691 Redraw();
692 while (show_prompt) {
693 show_prompt = false;
694 int key = WaitKey();
695 if (key == KEY_POWER || key == KEY_ENTER) {
696 return;
697 } else if (key == KEY_UP || key == KEY_VOLUMEUP) {
698 if (offsets.size() <= 1) {
699 show_prompt = true;
700 } else {
701 offsets.pop_back();
702 fseek(fp, offsets.back(), SEEK_SET);
703 }
704 } else {
705 if (feof(fp)) {
706 return;
707 }
708 offsets.push_back(ftell(fp));
709 }
710 }
711 ClearText();
712 }
713
714 int ch = getc(fp);
715 if (ch == EOF) {
716 while (text_row_ < text_rows_ - 1) PutChar('\n');
717 show_prompt = true;
718 } else {
719 PutChar(ch);
720 if (text_col_ == 0 && text_row_ >= text_rows_ - 1) {
721 show_prompt = true;
722 }
723 }
724 }
725 }
726
ShowFile(const char * filename)727 void ScreenRecoveryUI::ShowFile(const char* filename) {
728 FILE* fp = fopen_path(filename, "re");
729 if (fp == nullptr) {
730 Print(" Unable to open %s: %s\n", filename, strerror(errno));
731 return;
732 }
733
734 char** old_text = text_;
735 size_t old_text_col = text_col_;
736 size_t old_text_row = text_row_;
737 size_t old_text_top = text_top_;
738
739 // Swap in the alternate screen and clear it.
740 text_ = file_viewer_text_;
741 ClearText();
742
743 ShowFile(fp);
744 fclose(fp);
745
746 text_ = old_text;
747 text_col_ = old_text_col;
748 text_row_ = old_text_row;
749 text_top_ = old_text_top;
750 }
751
StartMenu(const char * const * headers,const char * const * items,int initial_selection)752 void ScreenRecoveryUI::StartMenu(const char* const * headers, const char* const * items,
753 int initial_selection) {
754 pthread_mutex_lock(&updateMutex);
755 if (text_rows_ > 0 && text_cols_ > 0) {
756 menu_headers_ = headers;
757 size_t i = 0;
758 for (; i < text_rows_ && items[i] != nullptr; ++i) {
759 strncpy(menu_[i], items[i], text_cols_ - 1);
760 menu_[i][text_cols_ - 1] = '\0';
761 }
762 menu_items = i;
763 show_menu = true;
764 menu_sel = initial_selection;
765 update_screen_locked();
766 }
767 pthread_mutex_unlock(&updateMutex);
768 }
769
SelectMenu(int sel)770 int ScreenRecoveryUI::SelectMenu(int sel) {
771 pthread_mutex_lock(&updateMutex);
772 if (show_menu) {
773 int old_sel = menu_sel;
774 menu_sel = sel;
775
776 // Wrap at top and bottom.
777 if (menu_sel < 0) menu_sel = menu_items - 1;
778 if (menu_sel >= menu_items) menu_sel = 0;
779
780 sel = menu_sel;
781 if (menu_sel != old_sel) update_screen_locked();
782 }
783 pthread_mutex_unlock(&updateMutex);
784 return sel;
785 }
786
EndMenu()787 void ScreenRecoveryUI::EndMenu() {
788 pthread_mutex_lock(&updateMutex);
789 if (show_menu && text_rows_ > 0 && text_cols_ > 0) {
790 show_menu = false;
791 update_screen_locked();
792 }
793 pthread_mutex_unlock(&updateMutex);
794 }
795
IsTextVisible()796 bool ScreenRecoveryUI::IsTextVisible() {
797 pthread_mutex_lock(&updateMutex);
798 int visible = show_text;
799 pthread_mutex_unlock(&updateMutex);
800 return visible;
801 }
802
WasTextEverVisible()803 bool ScreenRecoveryUI::WasTextEverVisible() {
804 pthread_mutex_lock(&updateMutex);
805 int ever_visible = show_text_ever;
806 pthread_mutex_unlock(&updateMutex);
807 return ever_visible;
808 }
809
ShowText(bool visible)810 void ScreenRecoveryUI::ShowText(bool visible) {
811 pthread_mutex_lock(&updateMutex);
812 show_text = visible;
813 if (show_text) show_text_ever = true;
814 update_screen_locked();
815 pthread_mutex_unlock(&updateMutex);
816 }
817
Redraw()818 void ScreenRecoveryUI::Redraw() {
819 pthread_mutex_lock(&updateMutex);
820 update_screen_locked();
821 pthread_mutex_unlock(&updateMutex);
822 }
823
KeyLongPress(int)824 void ScreenRecoveryUI::KeyLongPress(int) {
825 // Redraw so that if we're in the menu, the highlight
826 // will change color to indicate a successful long press.
827 Redraw();
828 }
829