cargo_mobile2/android/
device.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use super::{aab, adb, bundletool, config::Config, env::Env, jnilibs, target::Target};
use crate::{
    android::apk,
    env::ExplicitEnv as _,
    opts::{FilterLevel, NoiseLevel, Profile},
    os::consts,
    util::{
        self,
        cli::{Report, Reportable},
        last_modified, prefix_path,
    },
    DuctExpressionExt,
};
use std::{
    fmt::{self, Display},
    path::PathBuf,
    thread::sleep,
    time::Duration,
};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum AabBuildError {
    #[error("Failed to build AAB: {0}")]
    BuildFailed(std::io::Error),
}

impl Reportable for AabBuildError {
    fn report(&self) -> Report {
        match self {
            Self::BuildFailed(err) => Report::error("Failed to build AAB", err),
        }
    }
}

#[derive(Debug, Error)]
pub enum ApksBuildError {
    #[error("Failed to clean old APKS: {0}")]
    CleanFailed(std::io::Error),
    #[error("Failed to build APKS from AAB: {0}")]
    BuildFromAabFailed(std::io::Error),
}

impl Reportable for ApksBuildError {
    fn report(&self) -> Report {
        match self {
            Self::CleanFailed(err) => Report::error("Failed to clean old APKS", err),
            Self::BuildFromAabFailed(err) => Report::error("Failed to build APKS from AAB", err),
        }
    }
}

#[derive(Debug, Error)]
pub enum ApkInstallError {
    #[error("Failed to install APK: {0}")]
    InstallFailed(#[from] std::io::Error),
    #[error("Failed to install APK from AAB: {0}")]
    InstallFromAabFailed(std::io::Error),
}

impl Reportable for ApkInstallError {
    fn report(&self) -> Report {
        match self {
            Self::InstallFailed(err) => Report::error("Failed to install APK", err),
            Self::InstallFromAabFailed(err) => Report::error("Failed to install APK from AAB", err),
        }
    }
}

#[derive(Debug, Error)]
pub enum RunError {
    #[error(transparent)]
    ApkError(apk::ApkError),
    #[error(transparent)]
    AabError(aab::AabError),
    #[error(transparent)]
    ApkInstallFailed(ApkInstallError),
    #[error("Failed to wake device screen: {0}")]
    WakeScreenFailed(std::io::Error),
    #[error(transparent)]
    BundletoolInstallFailed(bundletool::InstallError),
    #[error(transparent)]
    AabBuildFailed(AabBuildError),
    #[error(transparent)]
    ApksFromAabBuildFailed(ApksBuildError),
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

impl Reportable for RunError {
    fn report(&self) -> Report {
        match self {
            Self::ApkError(err) => err.report(),
            Self::AabError(err) => err.report(),
            Self::ApkInstallFailed(err) => err.report(),
            Self::WakeScreenFailed(err) => Report::error("Failed to wake device screen", err),
            Self::BundletoolInstallFailed(err) => err.report(),
            Self::AabBuildFailed(err) => err.report(),
            Self::ApksFromAabBuildFailed(err) => err.report(),
            Self::Io(err) => Report::error("IO error", err),
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum StacktraceError {
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

impl Reportable for StacktraceError {
    fn report(&self) -> Report {
        match self {
            Self::Io(err) => Report::error("IO error", err),
        }
    }
}

#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Device<'a> {
    serial_no: String,
    name: String,
    model: String,
    target: &'a Target<'a>,
}

impl<'a> Display for Device<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)?;
        if self.model != self.name {
            write!(f, " ({})", self.model)?;
        }
        Ok(())
    }
}

impl<'a> Device<'a> {
    pub(super) fn new(
        serial_no: String,
        name: String,
        model: String,
        target: &'a Target<'a>,
    ) -> Self {
        Self {
            serial_no,
            name,
            model,
            target,
        }
    }

    pub fn target(&self) -> &'a Target<'a> {
        self.target
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn model(&self) -> &str {
        &self.model
    }

    pub fn serial_no(&self) -> &str {
        &self.serial_no
    }

    fn adb(&self, env: &Env) -> duct::Expression {
        adb::adb(env, ["-s", &self.serial_no])
    }

    pub fn all_apks_paths(config: &Config, profile: Profile, flavor: &str) -> Vec<PathBuf> {
        profile
            .suffixes()
            .iter()
            .map(|suffix| {
                prefix_path(
                    config.project_dir(),
                    format!(
                        "app/build/outputs/apk/{}/{}/app-{}-{}.{}",
                        flavor,
                        profile.as_str(),
                        flavor,
                        suffix,
                        "apk"
                    ),
                )
            })
            .collect()
    }

    fn wait_device_boot(&self, env: &Env) {
        loop {
            let cmd = self
                .adb(env)
                .stderr_capture()
                .stdout_capture()
                .before_spawn(move |cmd| {
                    cmd.args(["shell", "getprop", "init.svc.bootanim"]);
                    Ok(())
                });
            let handle = cmd.start();
            if let Ok(handle) = handle {
                if let Ok(output) = handle.wait() {
                    if output.status.success() {
                        let stdout = String::from_utf8_lossy(&output.stdout);
                        if stdout.trim() == "stopped" {
                            break;
                        }
                        sleep(Duration::from_secs(2));
                    }
                } else {
                    break;
                }
            }
        }
    }

    fn build_apk(
        &self,
        config: &Config,
        env: &Env,
        noise_level: NoiseLevel,
        profile: Profile,
    ) -> Result<(), apk::ApkError> {
        apk::build(config, env, noise_level, profile, vec![self.target()], true)?;
        Ok(())
    }

    fn install_apk(
        &self,
        config: &Config,
        env: &Env,
        profile: Profile,
    ) -> Result<(), ApkInstallError> {
        let flavor = self.target.arch;
        let apk_path = apk::apks_paths(config, profile, flavor)
            .into_iter()
            .reduce(last_modified)
            .unwrap();

        self.adb(env)
            .before_spawn(move |cmd| {
                cmd.args(["install", "-r"]);
                cmd.arg(&apk_path);
                Ok(())
            })
            .dup_stdio()
            .start()?
            .wait()?;

        Ok(())
    }

    fn build_aab(
        &self,
        config: &Config,
        env: &Env,
        noise_level: NoiseLevel,
        profile: Profile,
    ) -> Result<(), aab::AabError> {
        aab::build(
            config,
            env,
            noise_level,
            profile,
            vec![self.target()],
            false,
        )?;
        Ok(())
    }

    fn build_apks_from_aab(&self, config: &Config, profile: Profile) -> Result<(), ApksBuildError> {
        let flavor = self.target.arch;
        // In the case that profile is `Release`, it is safe to pick the first one
        // which should have the suffix `release` instead of `release-unsigned`.
        // This is fine since we determine the resulting name before-hand unlike other situations
        // where gradle is the one to determine it.
        //
        // and in the case that profile is `Debug` there will be only one path that has the suffix `debug`
        let all_apks_path = Self::all_apks_paths(config, profile, flavor)[0].clone();
        let aab_path = aab::aab_path(config, profile, flavor);
        bundletool::command()
            .before_spawn(move |cmd| {
                cmd.args([
                    "build-apks",
                    &format!("--bundle={}", aab_path.to_str().unwrap()),
                    &format!("--output={}", all_apks_path.to_str().unwrap()),
                    "--connected-device",
                ]);
                Ok(())
            })
            .run()
            .map_err(ApksBuildError::BuildFromAabFailed)?;
        Ok(())
    }

    fn install_apk_from_aab(
        &self,
        config: &Config,
        profile: Profile,
    ) -> Result<(), ApkInstallError> {
        let flavor = self.target.arch;
        let apks_path = Self::all_apks_paths(config, profile, flavor)
            .into_iter()
            .reduce(last_modified)
            .unwrap();
        bundletool::command()
            .before_spawn(move |cmd| {
                cmd.args([
                    "install-apks",
                    &format!("--apks={}", apks_path.to_str().unwrap()),
                ]);

                Ok(())
            })
            .run()
            .map_err(ApkInstallError::InstallFromAabFailed)?;
        Ok(())
    }

    fn wake_screen(&self, env: &Env) -> std::io::Result<()> {
        self.adb(env)
            .before_spawn(move |cmd| {
                cmd.args(["shell", "input", "keyevent", "KEYCODE_WAKEUP"]);
                Ok(())
            })
            .dup_stdio()
            .start()?
            .wait()?;
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn run(
        &self,
        config: &Config,
        env: &Env,
        noise_level: NoiseLevel,
        profile: Profile,
        filter_level: Option<FilterLevel>,
        build_app_bundle: bool,
        reinstall_deps: bool,
        activity: String,
    ) -> Result<duct::Handle, RunError> {
        if build_app_bundle {
            bundletool::install(reinstall_deps).map_err(RunError::BundletoolInstallFailed)?;
            self.build_aab(config, env, noise_level, profile)
                .map_err(RunError::AabError)?;
            self.build_apks_from_aab(config, profile)
                .map_err(RunError::ApksFromAabBuildFailed)?;
            if self.serial_no.starts_with("emulator") {
                self.wait_device_boot(env);
            }
            self.install_apk_from_aab(config, profile)
                .map_err(RunError::ApkInstallFailed)?;
        } else {
            self.build_apk(config, env, noise_level, profile)
                .map_err(RunError::ApkError)?;
            if self.serial_no.starts_with("emulator") {
                self.wait_device_boot(env);
            }
            self.install_apk(config, env, profile)
                .map_err(RunError::ApkInstallFailed)?;
        }
        let activity = format!("{}/{}", config.app().identifier(), activity);
        self.adb(env)
            .before_spawn(move |cmd| {
                cmd.args(["shell", "am", "start", "-n", &activity]);
                Ok(())
            })
            .dup_stdio()
            .start()?
            .wait()?;

        let _ = self.wake_screen(env);

        let filter = format!(
            "{}:{}",
            config.app().name(),
            filter_level
                .unwrap_or(match noise_level {
                    NoiseLevel::Polite => FilterLevel::Warn,
                    NoiseLevel::LoudAndProud => FilterLevel::Info,
                    NoiseLevel::FranklyQuitePedantic => FilterLevel::Verbose,
                })
                .logcat()
        );

        let stdout = loop {
            let cmd = duct::cmd(
                env.platform_tools_path().join("adb"),
                ["shell", "pidof", "-s", config.app().identifier()],
            )
            .vars(env.explicit_env())
            .stderr_capture()
            .stdout_capture();
            let handle = cmd.start()?;
            if let Ok(out) = handle.wait() {
                if out.status.success() {
                    break String::from_utf8_lossy(&out.stdout).into_owned();
                }
            }
            sleep(Duration::from_secs(2));
        };
        let pid = stdout.trim().to_string();
        let mut logcat = duct::cmd(
            env.platform_tools_path().join("adb"),
            ["logcat", "-v", "color", "-s", &filter],
        )
        .vars(env.explicit_env())
        .dup_stdio();

        let logcat_filter_specs = config.logcat_filter_specs().to_vec();
        logcat = logcat.before_spawn(move |cmd| {
            if !pid.is_empty() {
                cmd.args(["--pid", &pid]);
            }
            cmd.args(&logcat_filter_specs);
            Ok(())
        });
        logcat.start().map_err(Into::into)
    }

    pub fn stacktrace(&self, config: &Config, env: &Env) -> Result<(), StacktraceError> {
        let jnilib_path = config
            .app()
            // ndk-stack can't seem to handle spaces in args, no matter
            // how I try to quote or escape them... so, instead of
            // mandating that the entire path not contain spaces, we'll
            // just use a relative path!
            .unprefix_path(jnilibs::path(config, *self.target))
            .expect("developer error: jnilibs subdir not prefixed");
        // -d = print and exit
        let logcat_command = adb::adb(env, ["-s", &self.serial_no])
            .before_spawn(move |cmd| {
                cmd.args(["logcat", "-d"]);
                cmd.arg("-sym");
                cmd.arg(&jnilib_path);
                Ok(())
            })
            .dup_stdio();
        let stack_command =
            duct::cmd::<PathBuf, [String; 0]>(env.ndk.home().join(consts::NDK_STACK), [])
                .vars(env.explicit_env())
                .env(
                    "PATH",
                    util::prepend_to_path(env.ndk.home().display(), env.path().to_string_lossy()),
                )
                .dup_stdio();

        if logcat_command.pipe(stack_command).start()?.wait().is_err() {
            println!("  -- no stacktrace --");
        }
        Ok(())
    }
}