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 "recovery_ui/ui.h"
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/time.h>
25 #include <sys/types.h>
26 #include <time.h>
27 #include <unistd.h>
28
29 #include <chrono>
30 #include <functional>
31 #include <string>
32 #include <thread>
33
34 #include <android-base/file.h>
35 #include <android-base/logging.h>
36 #include <android-base/parseint.h>
37 #include <android-base/properties.h>
38 #include <android-base/strings.h>
39
40 #include "minui/minui.h"
41 #include "otautil/sysutil.h"
42
43 using namespace std::chrono_literals;
44
45 constexpr int UI_WAIT_KEY_TIMEOUT_SEC = 120;
46 constexpr const char* BRIGHTNESS_FILE = "/sys/class/leds/lcd-backlight/brightness";
47 constexpr const char* MAX_BRIGHTNESS_FILE = "/sys/class/leds/lcd-backlight/max_brightness";
48 constexpr const char* BRIGHTNESS_FILE_SDM = "/sys/class/backlight/panel0-backlight/brightness";
49 constexpr const char* MAX_BRIGHTNESS_FILE_SDM =
50 "/sys/class/backlight/panel0-backlight/max_brightness";
51 constexpr const char* BRIGHTNESS_FILE_PWM =
52 "/sys/class/backlight/pwm-backlight.0/brightness";
53 constexpr const char* MAX_BRIGHTNESS_FILE_PWM =
54 "/sys/class/backlight/pwm-backlight.0/max_brightness";
55
56 constexpr int kDefaultTouchLowThreshold = 50;
57 constexpr int kDefaultTouchHighThreshold = 90;
58
RecoveryUI()59 RecoveryUI::RecoveryUI()
60 : brightness_normal_(50),
61 brightness_dimmed_(25),
62 brightness_file_(BRIGHTNESS_FILE),
63 max_brightness_file_(MAX_BRIGHTNESS_FILE),
64 touch_screen_allowed_(false),
65 fastbootd_logo_enabled_(false),
66 touch_low_threshold_(android::base::GetIntProperty("ro.recovery.ui.touch_low_threshold",
67 kDefaultTouchLowThreshold)),
68 touch_high_threshold_(android::base::GetIntProperty("ro.recovery.ui.touch_high_threshold",
69 kDefaultTouchHighThreshold)),
70 key_interrupted_(false),
71 key_queue_len(0),
72 key_last_down(-1),
73 key_long_press(false),
74 key_down_count(0),
75 enable_reboot(true),
76 consecutive_power_keys(0),
77 has_power_key(false),
78 has_up_key(false),
79 has_down_key(false),
80 has_touch_screen(false),
81 touch_slot_(0),
82 is_bootreason_recovery_ui_(false),
83 screensaver_state_(ScreensaverState::DISABLED) {
84 memset(key_pressed, 0, sizeof(key_pressed));
85 }
86
~RecoveryUI()87 RecoveryUI::~RecoveryUI() {
88 ev_exit();
89 input_thread_stopped_ = true;
90 if (input_thread_.joinable()) {
91 input_thread_.join();
92 }
93 }
94
OnKeyDetected(int key_code)95 void RecoveryUI::OnKeyDetected(int key_code) {
96 if (key_code == KEY_POWER) {
97 has_power_key = true;
98 } else if (key_code == KEY_DOWN || key_code == KEY_VOLUMEDOWN) {
99 has_down_key = true;
100 } else if (key_code == KEY_UP || key_code == KEY_VOLUMEUP) {
101 has_up_key = true;
102 } else if (key_code == ABS_MT_POSITION_X || key_code == ABS_MT_POSITION_Y) {
103 has_touch_screen = true;
104 }
105 }
106
InitScreensaver()107 bool RecoveryUI::InitScreensaver() {
108 // Disabled.
109 if (brightness_normal_ == 0 || brightness_dimmed_ > brightness_normal_) {
110 return false;
111 }
112 if (access(brightness_file_.c_str(), R_OK | W_OK)) {
113 if (!access(BRIGHTNESS_FILE_SDM, R_OK | W_OK)) {
114 brightness_file_ = BRIGHTNESS_FILE_SDM;
115 } else {
116 brightness_file_ = BRIGHTNESS_FILE_PWM;
117 }
118 }
119
120 if (access(max_brightness_file_.c_str(), R_OK)) {
121 if (!access(MAX_BRIGHTNESS_FILE_SDM, R_OK)) {
122 max_brightness_file_ = MAX_BRIGHTNESS_FILE_SDM;
123 } else {
124 max_brightness_file_ = MAX_BRIGHTNESS_FILE_PWM;
125 }
126 }
127 // Set the initial brightness level based on the max brightness. Note that reading the initial
128 // value from BRIGHTNESS_FILE doesn't give the actual brightness value (bullhead, sailfish), so
129 // we don't have a good way to query the default value.
130 std::string content;
131 if (!android::base::ReadFileToString(max_brightness_file_, &content)) {
132 PLOG(WARNING) << "Failed to read max brightness";
133 return false;
134 }
135
136 unsigned int max_value;
137 if (!android::base::ParseUint(android::base::Trim(content), &max_value)) {
138 LOG(WARNING) << "Failed to parse max brightness: " << content;
139 return false;
140 }
141
142 brightness_normal_value_ = max_value * brightness_normal_ / 100.0;
143 brightness_dimmed_value_ = max_value * brightness_dimmed_ / 100.0;
144 if (!android::base::WriteStringToFile(std::to_string(brightness_normal_value_),
145 brightness_file_)) {
146 PLOG(WARNING) << "Failed to set brightness";
147 return false;
148 }
149
150 LOG(INFO) << "Brightness: " << brightness_normal_value_ << " (" << brightness_normal_ << "%)";
151 screensaver_state_ = ScreensaverState::NORMAL;
152 return true;
153 }
154
Init(const std::string &)155 bool RecoveryUI::Init(const std::string& /* locale */) {
156 ev_init(std::bind(&RecoveryUI::OnInputEvent, this, std::placeholders::_1, std::placeholders::_2),
157 touch_screen_allowed_);
158
159 ev_iterate_available_keys(std::bind(&RecoveryUI::OnKeyDetected, this, std::placeholders::_1));
160
161 if (touch_screen_allowed_) {
162 ev_iterate_touch_inputs(std::bind(&RecoveryUI::OnKeyDetected, this, std::placeholders::_1));
163
164 // Parse /proc/cmdline to determine if it's booting into recovery with a bootreason of
165 // "recovery_ui". This specific reason is set by some (wear) bootloaders, to allow an easier way
166 // to turn on text mode. It will only be set if the recovery boot is triggered from fastboot, or
167 // with 'adb reboot recovery'. Note that this applies to all build variants. Otherwise the text
168 // mode will be turned on automatically on debuggable builds, even without a swipe.
169 std::string cmdline;
170 if (android::base::ReadFileToString("/proc/cmdline", &cmdline)) {
171 is_bootreason_recovery_ui_ = cmdline.find("bootreason=recovery_ui") != std::string::npos;
172 } else {
173 // Non-fatal, and won't affect Init() result.
174 PLOG(WARNING) << "Failed to read /proc/cmdline";
175 }
176 }
177
178 if (!InitScreensaver()) {
179 LOG(INFO) << "Screensaver disabled";
180 }
181
182 // Create a separate thread that handles input events.
183 input_thread_ = std::thread([this]() {
184 while (!this->input_thread_stopped_) {
185 if (!ev_wait(500)) {
186 ev_dispatch();
187 }
188 }
189 });
190
191 return true;
192 }
193
OnTouchDetected(int dx,int dy)194 void RecoveryUI::OnTouchDetected(int dx, int dy) {
195 enum SwipeDirection { UP, DOWN, RIGHT, LEFT } direction;
196
197 // We only consider a valid swipe if:
198 // - the delta along one axis is below touch_low_threshold_;
199 // - and the delta along the other axis is beyond touch_high_threshold_.
200 if (abs(dy) < touch_low_threshold_ && abs(dx) > touch_high_threshold_) {
201 direction = dx < 0 ? SwipeDirection::LEFT : SwipeDirection::RIGHT;
202 } else if (abs(dx) < touch_low_threshold_ && abs(dy) > touch_high_threshold_) {
203 direction = dy < 0 ? SwipeDirection::UP : SwipeDirection::DOWN;
204 } else {
205 LOG(DEBUG) << "Ignored " << dx << " " << dy << " (low: " << touch_low_threshold_
206 << ", high: " << touch_high_threshold_ << ")";
207 return;
208 }
209
210 // Allow turning on text mode with any swipe, if bootloader has set a bootreason of recovery_ui.
211 if (is_bootreason_recovery_ui_ && !IsTextVisible()) {
212 ShowText(true);
213 return;
214 }
215
216 LOG(DEBUG) << "Swipe direction=" << direction;
217 switch (direction) {
218 case SwipeDirection::UP:
219 ProcessKey(KEY_UP, 1); // press up key
220 ProcessKey(KEY_UP, 0); // and release it
221 break;
222
223 case SwipeDirection::DOWN:
224 ProcessKey(KEY_DOWN, 1); // press down key
225 ProcessKey(KEY_DOWN, 0); // and release it
226 break;
227
228 case SwipeDirection::LEFT:
229 case SwipeDirection::RIGHT:
230 ProcessKey(KEY_POWER, 1); // press power key
231 ProcessKey(KEY_POWER, 0); // and release it
232 break;
233 };
234 }
235
OnInputEvent(int fd,uint32_t epevents)236 int RecoveryUI::OnInputEvent(int fd, uint32_t epevents) {
237 struct input_event ev;
238 if (ev_get_input(fd, epevents, &ev) == -1) {
239 return -1;
240 }
241
242 // Touch inputs handling.
243 //
244 // We handle the touch inputs by tracking the position changes between initial contacting and
245 // upon lifting. touch_start_X/Y record the initial positions, with touch_finger_down set. Upon
246 // detecting the lift, we unset touch_finger_down and detect a swipe based on position changes.
247 //
248 // Per the doc Multi-touch Protocol at below, there are two protocols.
249 // https://www.kernel.org/doc/Documentation/input/multi-touch-protocol.txt
250 //
251 // The main difference between the stateless type A protocol and the stateful type B slot protocol
252 // lies in the usage of identifiable contacts to reduce the amount of data sent to userspace. The
253 // slot protocol (i.e. type B) sends ABS_MT_TRACKING_ID with a unique id on initial contact, and
254 // sends ABS_MT_TRACKING_ID -1 upon lifting the contact. Protocol A doesn't send
255 // ABS_MT_TRACKING_ID -1 on lifting, but the driver may additionally report BTN_TOUCH event.
256 //
257 // For protocol A, we rely on BTN_TOUCH to recognize lifting, while for protocol B we look for
258 // ABS_MT_TRACKING_ID being -1.
259 //
260 // Touch input events will only be available if touch_screen_allowed_ is set.
261
262 if (ev.type == EV_SYN) {
263 if (touch_screen_allowed_ && ev.code == SYN_REPORT) {
264 // There might be multiple SYN_REPORT events. We should only detect a swipe after lifting the
265 // contact.
266 if (touch_finger_down_ && !touch_swiping_) {
267 touch_start_X_ = touch_X_;
268 touch_start_Y_ = touch_Y_;
269 touch_swiping_ = true;
270 } else if (!touch_finger_down_ && touch_swiping_) {
271 touch_swiping_ = false;
272 OnTouchDetected(touch_X_ - touch_start_X_, touch_Y_ - touch_start_Y_);
273 }
274 }
275 return 0;
276 }
277
278 if (ev.type == EV_REL) {
279 if (ev.code == REL_Y) {
280 // accumulate the up or down motion reported by
281 // the trackball. When it exceeds a threshold
282 // (positive or negative), fake an up/down
283 // key event.
284 rel_sum += ev.value;
285 if (rel_sum > 3) {
286 ProcessKey(KEY_DOWN, 1); // press down key
287 ProcessKey(KEY_DOWN, 0); // and release it
288 rel_sum = 0;
289 } else if (rel_sum < -3) {
290 ProcessKey(KEY_UP, 1); // press up key
291 ProcessKey(KEY_UP, 0); // and release it
292 rel_sum = 0;
293 }
294 }
295 } else {
296 rel_sum = 0;
297 }
298
299 if (touch_screen_allowed_ && ev.type == EV_ABS) {
300 if (ev.code == ABS_MT_SLOT) {
301 touch_slot_ = ev.value;
302 }
303 // Ignore other fingers.
304 if (touch_slot_ > 0) return 0;
305
306 switch (ev.code) {
307 case ABS_MT_POSITION_X:
308 touch_X_ = ev.value;
309 touch_finger_down_ = true;
310 break;
311
312 case ABS_MT_POSITION_Y:
313 touch_Y_ = ev.value;
314 touch_finger_down_ = true;
315 break;
316
317 case ABS_MT_TRACKING_ID:
318 // Protocol B: -1 marks lifting the contact.
319 if (ev.value < 0) touch_finger_down_ = false;
320 break;
321 }
322 return 0;
323 }
324
325 if (ev.type == EV_KEY && ev.code <= KEY_MAX) {
326 if (touch_screen_allowed_) {
327 if (ev.code == BTN_TOUCH) {
328 // A BTN_TOUCH with value 1 indicates the start of contact (protocol A), with 0 means
329 // lifting the contact.
330 touch_finger_down_ = (ev.value == 1);
331 }
332
333 // Intentionally ignore BTN_TOUCH and BTN_TOOL_FINGER, which would otherwise trigger
334 // additional scrolling (because in ScreenRecoveryUI::ShowFile(), we consider keys other than
335 // KEY_POWER and KEY_UP as KEY_DOWN).
336 if (ev.code == BTN_TOUCH || ev.code == BTN_TOOL_FINGER) {
337 return 0;
338 }
339 }
340
341 ProcessKey(ev.code, ev.value);
342 }
343
344 return 0;
345 }
346
347 // Processes a key-up or -down event. A key is "registered" when it is pressed and then released,
348 // with no other keypresses or releases in between. Registered keys are passed to CheckKey() to
349 // see if it should trigger a visibility toggle, an immediate reboot, or be queued to be processed
350 // next time the foreground thread wants a key (eg, for the menu).
351 //
352 // We also keep track of which keys are currently down so that CheckKey() can call IsKeyPressed()
353 // to see what other keys are held when a key is registered.
354 //
355 // updown == 1 for key down events; 0 for key up events
ProcessKey(int key_code,int updown)356 void RecoveryUI::ProcessKey(int key_code, int updown) {
357 bool register_key = false;
358 bool long_press = false;
359
360 {
361 std::lock_guard<std::mutex> lg(key_press_mutex);
362 key_pressed[key_code] = updown;
363 if (updown) {
364 ++key_down_count;
365 key_last_down = key_code;
366 key_long_press = false;
367 std::thread time_key_thread(&RecoveryUI::TimeKey, this, key_code, key_down_count);
368 time_key_thread.detach();
369 } else {
370 if (key_last_down == key_code) {
371 long_press = key_long_press;
372 register_key = true;
373 }
374 key_last_down = -1;
375 }
376 }
377
378 bool reboot_enabled = enable_reboot;
379 if (register_key) {
380 switch (CheckKey(key_code, long_press)) {
381 case RecoveryUI::IGNORE:
382 break;
383
384 case RecoveryUI::TOGGLE:
385 ShowText(!IsTextVisible());
386 break;
387
388 case RecoveryUI::REBOOT:
389 if (reboot_enabled) {
390 Reboot("userrequested,recovery,ui");
391 }
392 break;
393
394 case RecoveryUI::ENQUEUE:
395 EnqueueKey(key_code);
396 break;
397 }
398 }
399 }
400
TimeKey(int key_code,int count)401 void RecoveryUI::TimeKey(int key_code, int count) {
402 std::this_thread::sleep_for(750ms); // 750 ms == "long"
403 bool long_press = false;
404 {
405 std::lock_guard<std::mutex> lg(key_press_mutex);
406 if (key_last_down == key_code && key_down_count == count) {
407 long_press = key_long_press = true;
408 }
409 }
410 if (long_press) KeyLongPress(key_code);
411 }
412
EnqueueKey(int key_code)413 void RecoveryUI::EnqueueKey(int key_code) {
414 std::lock_guard<std::mutex> lg(key_queue_mutex);
415 const int queue_max = sizeof(key_queue) / sizeof(key_queue[0]);
416 if (key_queue_len < queue_max) {
417 key_queue[key_queue_len++] = key_code;
418 key_queue_cond.notify_one();
419 }
420 }
421
SetScreensaverState(ScreensaverState state)422 void RecoveryUI::SetScreensaverState(ScreensaverState state) {
423 switch (state) {
424 case ScreensaverState::NORMAL:
425 if (android::base::WriteStringToFile(std::to_string(brightness_normal_value_),
426 brightness_file_)) {
427 screensaver_state_ = ScreensaverState::NORMAL;
428 LOG(INFO) << "Brightness: " << brightness_normal_value_ << " (" << brightness_normal_
429 << "%)";
430 } else {
431 LOG(WARNING) << "Unable to set brightness to normal";
432 }
433 break;
434 case ScreensaverState::DIMMED:
435 if (android::base::WriteStringToFile(std::to_string(brightness_dimmed_value_),
436 brightness_file_)) {
437 LOG(INFO) << "Brightness: " << brightness_dimmed_value_ << " (" << brightness_dimmed_
438 << "%)";
439 screensaver_state_ = ScreensaverState::DIMMED;
440 } else {
441 LOG(WARNING) << "Unable to set brightness to dim";
442 }
443 break;
444 case ScreensaverState::OFF:
445 if (android::base::WriteStringToFile("0", brightness_file_)) {
446 LOG(INFO) << "Brightness: 0 (off)";
447 screensaver_state_ = ScreensaverState::OFF;
448 } else {
449 LOG(WARNING) << "Unable to set brightness to off";
450 }
451 break;
452 default:
453 LOG(ERROR) << "Invalid screensaver state";
454 }
455 }
456
WaitKey()457 int RecoveryUI::WaitKey() {
458 std::unique_lock<std::mutex> lk(key_queue_mutex);
459
460 // Check for a saved key queue interruption.
461 if (key_interrupted_) {
462 SetScreensaverState(ScreensaverState::NORMAL);
463 return static_cast<int>(KeyError::INTERRUPTED);
464 }
465
466 // Time out after UI_WAIT_KEY_TIMEOUT_SEC, unless a USB cable is plugged in.
467 do {
468 bool rc = key_queue_cond.wait_for(lk, std::chrono::seconds(UI_WAIT_KEY_TIMEOUT_SEC), [this] {
469 return this->key_queue_len != 0 || key_interrupted_;
470 });
471 if (key_interrupted_) {
472 SetScreensaverState(ScreensaverState::NORMAL);
473 return static_cast<int>(KeyError::INTERRUPTED);
474 }
475 if (screensaver_state_ != ScreensaverState::DISABLED) {
476 if (!rc) {
477 // Must be after a timeout. Lower the brightness level: NORMAL -> DIMMED; DIMMED -> OFF.
478 if (screensaver_state_ == ScreensaverState::NORMAL) {
479 SetScreensaverState(ScreensaverState::DIMMED);
480 } else if (screensaver_state_ == ScreensaverState::DIMMED) {
481 SetScreensaverState(ScreensaverState::OFF);
482 }
483 } else if (screensaver_state_ != ScreensaverState::NORMAL) {
484 // Drop the first key if it's changing from OFF to NORMAL.
485 if (screensaver_state_ == ScreensaverState::OFF) {
486 if (key_queue_len > 0) {
487 memcpy(&key_queue[0], &key_queue[1], sizeof(int) * --key_queue_len);
488 }
489 }
490
491 // Reset the brightness to normal.
492 SetScreensaverState(ScreensaverState::NORMAL);
493 }
494 }
495 } while (IsUsbConnected() && key_queue_len == 0);
496
497 int key = static_cast<int>(KeyError::TIMED_OUT);
498 if (key_queue_len > 0) {
499 key = key_queue[0];
500 memcpy(&key_queue[0], &key_queue[1], sizeof(int) * --key_queue_len);
501 }
502 return key;
503 }
504
InterruptKey()505 void RecoveryUI::InterruptKey() {
506 {
507 std::lock_guard<std::mutex> lg(key_queue_mutex);
508 key_interrupted_ = true;
509 }
510 key_queue_cond.notify_one();
511 }
512
IsUsbConnected()513 bool RecoveryUI::IsUsbConnected() {
514 int fd = open("/sys/class/android_usb/android0/state", O_RDONLY);
515 if (fd < 0) {
516 printf("failed to open /sys/class/android_usb/android0/state: %s\n", strerror(errno));
517 return 0;
518 }
519
520 char buf;
521 // USB is connected if android_usb state is CONNECTED or CONFIGURED.
522 int connected = (TEMP_FAILURE_RETRY(read(fd, &buf, 1)) == 1) && (buf == 'C');
523 if (close(fd) < 0) {
524 printf("failed to close /sys/class/android_usb/android0/state: %s\n", strerror(errno));
525 }
526 return connected;
527 }
528
IsKeyPressed(int key)529 bool RecoveryUI::IsKeyPressed(int key) {
530 std::lock_guard<std::mutex> lg(key_press_mutex);
531 int pressed = key_pressed[key];
532 return pressed;
533 }
534
IsLongPress()535 bool RecoveryUI::IsLongPress() {
536 std::lock_guard<std::mutex> lg(key_press_mutex);
537 bool result = key_long_press;
538 return result;
539 }
540
HasThreeButtons() const541 bool RecoveryUI::HasThreeButtons() const {
542 return has_power_key && has_up_key && has_down_key;
543 }
544
HasPowerKey() const545 bool RecoveryUI::HasPowerKey() const {
546 return has_power_key;
547 }
548
HasTouchScreen() const549 bool RecoveryUI::HasTouchScreen() const {
550 return has_touch_screen;
551 }
552
FlushKeys()553 void RecoveryUI::FlushKeys() {
554 std::lock_guard<std::mutex> lg(key_queue_mutex);
555 key_queue_len = 0;
556 }
557
CheckKey(int key,bool is_long_press)558 RecoveryUI::KeyAction RecoveryUI::CheckKey(int key, bool is_long_press) {
559 {
560 std::lock_guard<std::mutex> lg(key_press_mutex);
561 key_long_press = false;
562 }
563
564 // If we have power and volume up keys, that chord is the signal to toggle the text display.
565 if (HasThreeButtons() || (HasPowerKey() && HasTouchScreen() && touch_screen_allowed_)) {
566 if ((key == KEY_VOLUMEUP || key == KEY_UP) && IsKeyPressed(KEY_POWER)) {
567 return TOGGLE;
568 }
569 } else {
570 // Otherwise long press of any button toggles to the text display,
571 // and there's no way to toggle back (but that's pretty useless anyway).
572 if (is_long_press && !IsTextVisible()) {
573 return TOGGLE;
574 }
575
576 // Also, for button-limited devices, a long press is translated to KEY_ENTER.
577 if (is_long_press && IsTextVisible()) {
578 EnqueueKey(KEY_ENTER);
579 return IGNORE;
580 }
581 }
582
583 // Press power seven times in a row to reboot.
584 if (key == KEY_POWER) {
585 bool reboot_enabled = enable_reboot;
586
587 if (reboot_enabled) {
588 ++consecutive_power_keys;
589 if (consecutive_power_keys >= 7) {
590 return REBOOT;
591 }
592 }
593 } else {
594 consecutive_power_keys = 0;
595 }
596
597 return (IsTextVisible() || screensaver_state_ == ScreensaverState::OFF) ? ENQUEUE : IGNORE;
598 }
599
KeyLongPress(int)600 void RecoveryUI::KeyLongPress(int) {}
601
SetEnableReboot(bool enabled)602 void RecoveryUI::SetEnableReboot(bool enabled) {
603 std::lock_guard<std::mutex> lg(key_press_mutex);
604 enable_reboot = enabled;
605 }
606