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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
use std::collections::{
	HashMap,
	HashSet,
};

use ::uni_components::ui_page::UiPage;

use crate::{
	Architecture,
	SimpleUiPage,
};

mod manifest_parsing;
mod template_instantiation;

const ADB: &'static str = "$ADB$";
const DIR: &'static str = "$DIR$";

/// Builds list of ui-crates into APK
///
/// Each ui-crate should use [uniui_gui::u_main!] to identify main funciton.
///
/// [[package.metadata.uni_android]] section shuld be configured inside crate's
/// Cargo.toml. It may contains few sub-sections:
/// * main_function - name of the main function marked by [uniui_gui::u_main!]
/// * java_files - the files will be copied into APK tree for the package which name will
///   be the same as the crate name
/// * export_func_file - path to `export_func.json` file.
///
/// `export_func.json` file - array of [manifest_parsing::Func]. All functions
/// from the file will be reexported with related `Func::export` name.
pub struct AndroidBuilder {
	pages: Vec<(SimpleUiPage, bool)>,
	path_to_icon: String,
	app_id: String,
	sdk_location: String,
	min_sdk: String,
	target_sdk: String,
	ndk_locaiton: String,
	app_name: String,
	version: String,
	version_code: u32,
	manifest_processor: crate::manifest_processor::ManifestProcessor,
	architecture: HashSet<Architecture>,
	release_mode: bool,
}

impl AndroidBuilder {
	/// Creates new instance of `AndroidBuilder`
	pub fn new(
		path_to_icon: String,
		app_id: String,
		sdk_location: String,
		min_sdk: String,
		target_sdk: String,
		ndk_locaiton: String,
		app_name: String,
	) -> Self {
		let manifest_processor = crate::manifest_processor::ManifestProcessor::new();
		let version = std::env::var("CARGO_PKG_VERSION")
			.expect("Error while retrieving CARGO_PKG_VERSION");
		let cargo_major = std::env::var("CARGO_PKG_VERSION_MAJOR")
			.expect("Error while retrieving CARGO_PKG_VERSION_MAJOR")
			.parse::<u32>()
			.expect("Incorrect variable value CARGO_PKG_VERSION_MAJOR");
		let cargo_minor = std::env::var("CARGO_PKG_VERSION_MINOR")
			.expect("Error while retrieving CARGO_PKG_VERSION_MINOR")
			.parse::<u32>()
			.expect("Incorrect variable value CARGO_PKG_VERSION_MINOR");
		let cargo_patch = std::env::var("CARGO_PKG_VERSION_PATCH")
			.expect("Error while retrieving CARGO_PKG_VERSION_PATCH")
			.parse::<u32>()
			.expect("Incorrect variable value CARGO_PKG_VERSION_PATCH");

		let version_code = (cargo_major * 1000 + cargo_minor) * 1000 + cargo_patch;

		let release_mode = std::env::var("PROFILE") == Ok("release".to_owned());

		return Self {
			pages: Vec::new(),
			path_to_icon,
			app_id,
			sdk_location,
			min_sdk,
			target_sdk,
			ndk_locaiton,
			app_name,
			version,
			version_code,
			manifest_processor,
			architecture: Architecture::all(),
			release_mode,
		};
	}

	pub fn set_architecture(
		&mut self,
		archs: HashSet<Architecture>,
	) {
		self.architecture = archs;
	}

	/// Specify string used as the version number shown to users
	///
	/// By default the version of your android-crate will be used.
	pub fn set_version(
		&mut self,
		version: String,
	) {
		self.version = version;
	}

	/// Specify value used as an internal version number
	///
	/// Higher numbers indicating more recent versions
	/// Each successive release of app should use a greater value
	///
	/// By default it'll be calculated based on the version of your android-crate as
	/// `(ver_major * 1000 + ver_minor) * 1000 + ver_patch`
	/// ```
	pub fn set_version_code(
		&mut self,
		version_code: u32,
	) {
		self.version_code = version_code;
	}

	/// Specify if release mode should be used
	///
	/// By default builder will use the mode from PROFILE env variable which
	/// will be set by cargo.
	pub fn set_release_mode(
		&mut self,
		is_release: bool,
	) {
		self.release_mode = is_release;
	}

	/// Specify UiPage and module_name which implements the page
	///
	/// The crate_name should be the same as the crate name in
	/// [build-dependencies] secion of Cargo.toml
	///
	/// The crate should use [uniui_gui::u_main!] to identify main funciton.
	///
	/// [[package.metadata.uni_android.main_function]] section shuld be configured inside
	/// crate's Cargo.toml.
	pub fn add_page<T>(
		&mut self,
		page: &'static dyn UiPage<Data = T>,
		crate_name: &str,
	) {
		self.add_path(page.path(), crate_name, false);
	}

	/// Specify Launcher UiPage and module_name which implements the page
	///
	/// The crate_name should be the same as the crate name in
	/// [build-dependencies] secion of Cargo.toml
	///
	/// The crate should use [uniui_gui::u_main!] to identify main funciton.
	///
	/// [[package.metadata.uni_android.main_function]] section shuld be configured inside
	/// crate's Cargo.toml.
	///
	/// Provided UiPage will be used as an entry point into the app.
	/// Theoretically it's possible to have multiple entry points but it's not
	/// a common case.
	pub fn add_launcher<T>(
		&mut self,
		page: &'static dyn UiPage<Data = T>,
		crate_name: &str,
	) {
		self.add_path(page.path(), crate_name, true);
	}

	pub fn execute(self) {
		let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR have to be setted up");

		let jni_crate_name = "uni_tmp_jni";
		let jni_crate_info;

		// contains all packages (including transitive dependency) which has
		// configured [[package.metadata.uni_android]] section.
		let map: HashMap<_, _> = {
			let mut map = HashMap::new();

			let resolved = {
				let config = cargo::util::config::Config::default()
					.expect("Config creation failed");

				let mut pr = cargo::core::registry::PackageRegistry::new(&config)
					.expect("Package registry failed");
				pr.lock_patches();

				let path_to_cargotoml =
					format!("{}/Cargo.toml", self.manifest_processor.manifest_path());
				let path = std::path::Path::new(&path_to_cargotoml);

				let source_id = cargo::core::SourceId::for_path(path.clone())
					.expect("Source id creation failed");


				let (manifest, _) =
					cargo::util::toml::read_manifest(&path, source_id, &config).unwrap();
				let m = match manifest {
					cargo::core::manifest::EitherManifest::Real(m) => m,
					cargo::core::manifest::EitherManifest::Virtual(v) => {
						panic!("virtual manifest:{:?}", v);
					},
				};
				let pkg = cargo::core::package::Package::new(m, path);
				let summary = pkg.summary().clone();
				let resolve_ops = cargo::core::resolver::ResolveOpts::everything();

				let try_to_use = std::collections::HashSet::new();

				let _lock = config
					.acquire_package_cache_lock()
					.expect("package cache lock failed");
				cargo::core::resolver::resolve(
					&[(summary, resolve_ops)], // summaries: &[(Summary, ResolveOpts)],
					&[],                       /* replacements: &[(PackageIdSpec,
					                            * Dependency)], */
					&mut pr,     // registry: &mut dyn Registry,
					&try_to_use, // try_to_use: &HashSet<PackageId>,
					None,        // config: Option<&Config>,
					false,       // check_public_visible_dependencies: bool
				)
				.expect("Resolve failed")
			};

			for pkg in resolved.iter() {
				let sumary = resolved.summary(pkg);
				let name: String = sumary.name().to_string();
				let may_be_path = self.manifest_processor.get_manifest_path(&name);
				match may_be_path {
					None => {
						log::error!(
							"Crate path not found for `{}`. Sounds unsoundness",
							name
						);
					},
					Some(path) => {
						manifest_parsing::process_manifest(name, path, &mut map);
					},
				}
			}

			let jni_crate_pkgid = resolved.query(jni_crate_name).expect(&format!(
				"package {} not found in dependencies list",
				jni_crate_name,
			));
			let sumary = resolved.summary(jni_crate_pkgid);
			let source = sumary.source_id();
			match source.is_path() {
				true => jni_crate_info = format!("{{ path=\"{}\"}}", source.url().path()),
				false => jni_crate_info = format!("\"{}\"", sumary.version().to_string()),
			}

			map.iter().filter_map(|(x, c)| c.clone().map(|c| (x.clone(), c))).collect()
		};

		// construct list with dependencies
		//
		// we should add all packages with configured [[package.metadata.uni_android]]
		// to our dependencies list because we will reexport it's functions
		let deps = map
			.iter()
			.map(|(n, c)| format!("{} = {{ path=\"{}\" }}", n, c.manifest_path))
			.collect::<Vec<_>>()
			.join("\n");

		let deps = format!("{}\n{} = {}\n", deps, jni_crate_name, jni_crate_info,);

		// generate reexports for all functions from
		// [[package.metadata.uni_android.export_func_file]]
		let lib_content = map
			.iter()
			.flat_map(|(name, config)| {
				config.funcs.iter().flat_map(move |funcs| {
					funcs.iter().map(move |f| {
						let params = f
							.params
							.iter()
							.enumerate()
							.map(|(id, t)| format!("_a{}: {}", id, t))
							.collect::<Vec<_>>()
							.join(",");
						let params_2 = f
							.params
							.iter()
							.enumerate()
							.map(|(id, _)| format!("_a{}", id))
							.collect::<Vec<_>>()
							.join(",");
						format!(
							"
						#[no_mangle]
						#[allow(non_snake_case)]
						pub extern \"C\" fn {}(
							{}
						) -> {} {{
							return {}::{}({});
						}}
					",
							f.export, params, f.result, name, f.name, params_2
						)
					})
				})
			})
			.collect::<Vec<_>>()
			.join("\n");

		// collect all activities
		let activities = {
			let mut activities = Vec::new();
			for (page, is_launcher) in self.pages.iter() {
				activities.push(template_instantiation::ActivityInfo {
					name: activity_name_for(&page),
					is_launcher: *is_launcher,
				});
			}

			activities
		};

		// the name for new package which will contain generic java classes
		let package = format!("com.uniuirust.buildfor.{}", self.app_id);

		// Generate reexports for uniui_gui::AndroidApplication for each activity
		let lib_content_2 = self
			.pages
			.iter()
			.map(|(s, _)| {
				let m_path = s.module_path().to_owned();
				let config = manifest_parsing::get_config(m_path.clone());
				let main = config
					.expect(&format!("UI crates without metadata.uni_android:{}", m_path))
					.main_function
					.expect(&format!(
						"uni_android.main_function not specified in manifest:{}",
						m_path
					));
				let on_create_name = format!(
					"Java_{}_{}_onCreateNative",
					package.clone().replace("_", "_1").replace(".", "_"),
					activity_name_for(&s).replace("_", "_1"),
				);

				let on_tick_name = format!(
					"Java_{}_{}_onTickNative",
					package.clone().replace("_", "_1").replace(".", "_"),
					activity_name_for(&s).replace("_", "_1"),
				);

				let on_cleanup_name = format!(
					"Java_{}_{}_onCleanupNative",
					package.clone().replace("_", "_1").replace(".", "_"),
					activity_name_for(&s).replace("_", "_1"),
				);

				format!(
					"
					#[no_mangle]
					#[allow(non_snake_case)]
					pub extern \"C\" fn {}(
						env: jni::JNIEnv,
						activity: jni::objects::JObject
					) {{
						{}::{}::{}(env, activity);
					}}

					#[no_mangle]
					#[allow(non_snake_case)]
					pub extern \"C\" fn {}(
						env: jni::JNIEnv,
						activity: jni::objects::JObject,
						addr: jni::sys::jlong,
					) -> jni::sys::jlong {{
						return {}::{}::{}(env, activity, addr);
					}}

					#[no_mangle]
					#[allow(non_snake_case)]
					pub extern \"C\" fn {}(
						env: jni::JNIEnv,
						activity: jni::objects::JObject,
						addr: jni::sys::jlong,
					) {{
						{}::{}::{}(env, activity, addr);
					}}
				",
					on_create_name,
					s.module_name(),
					crate::android_module_name(main.clone()),
					crate::RUN_FUNCTION_NAME,
					on_tick_name,
					s.module_name(),
					crate::android_module_name(main.clone()),
					crate::TICK_FUNCTION_NAME,
					on_cleanup_name,
					s.module_name(),
					crate::android_module_name(main),
					crate::CLEANUP_FUNCTION_NAME,
				)
			})
			.collect::<Vec<_>>()
			.join("\n");


		let lib_content = format!(
			"extern crate uni_tmp_jni as jni;\n{}",
			vec![lib_content, lib_content_2].join("\n")
		);


		let dir = format!("{}/android", std::env::var("OUT_DIR").unwrap());

		let arch_list = self
			.architecture
			.into_iter()
			.map(|x| x.as_quoted_string())
			.collect::<Vec<_>>()
			.join(", ");

		template_instantiation::instantiate_for(
			&dir,
			&deps,
			&arch_list,
			&self.app_id,
			&self.min_sdk,
			&self.target_sdk,
			&self.sdk_location,
			&self.ndk_locaiton,
			&package,
			&self.app_name,
			&self.version,
			&self.version_code.to_string(),
			&lib_content,
			activities,
			self.release_mode,
		)
		.expect("Template instantiation failed");

		// copy all [[package.metadata.uni_android.java_files]]
		{
			for (name, config) in map.iter() {
				if let Some(files_list) = config.java_files.as_ref() {
					for file in files_list {
						let dest_dir = format!("{}/app/src/main/java/{}", dir, name);
						{
							// Otherwise canonicalize will fail
							std::fs::create_dir_all(&dest_dir)
								.expect(&format!("Can't create dir:{}", dest_dir,));

							let dest_dir = std::path::Path::new(&dest_dir);
							let dest_dir =
								dest_dir.canonicalize().expect("Canonicalization failed");
							match dest_dir.starts_with(&out_dir) {
								true => {
									// we believe it's safe because we checked that the
									// directory is a part of "OUT_DIR".
									// Hope nobody will create a bug where the script
									// will delete User's content.
									// I have no idea how to fix the problem with old
									// files in the java directory in the other way.

									// Finally it looks like it's only affect native
									// developers. Commented for now to prevent potential
									// data lost
									//
									// std::fs::remove_dir_all(&dest_dir).expect(&format!
									// { 	"Can't remove directory {}",
									// 	dest_dir.display(),
									// });
								},
								false => {
									panic!(
										"Java direcotry for crate:{} is not a part of \
										 OUT directory subtree. Dir:{}",
										name,
										dest_dir.display(),
									);
								},
							}
						}

						std::fs::create_dir_all(&dest_dir)
							.expect(&format!("Can't create dir:{}", dest_dir,));

						let file_last_name = std::path::Path::new(file)
							.file_name()
							.expect(&format!("Can't extract filename from:{}", file))
							.to_str()
							.expect(&format!(
								"Can't extract filename as string from:{}",
								file
							));

						let source = format!("{}/{}", config.manifest_path, file);
						let destination = format!("{}/{}", dest_dir, file_last_name);

						std::fs::copy(&source, &destination).expect(&format!(
							"Copy failed source:{} destination:{}",
							source, destination,
						));
					}
				}
			}
		}

		let gradle_command = match self.release_mode {
			true => "assembleRelease",
			false => "assembleDebug",
		};

		// run gradle:
		// * compile all crates for `android` into .so library
		// * compile all java/kotlin files
		let gradle_status = std::process::Command::new("./gradlew")
			.arg("--no-daemon")
			.arg(gradle_command)
			.current_dir(&dir)
			.status()
			.expect("Gradle build failed. Please see error above");

		if !gradle_status.success() {
			panic!("Gradle build failed. Please see error above");
		}

		// generate templates for application start simplification
		let file_name = format!("{}/uni_build_generated.rs", out_dir);
		let rust = std::include_str!("./build_android/templates/rust.rs")
			.replace(ADB, &format!("{}/platform-tools/adb", self.sdk_location))
			.replace(DIR, &dir);
		std::fs::write(&file_name, &rust).expect("Rust helpers write failed");

		// to suppress `unused` warning
		let _ = self.path_to_icon.clone();
	}

	fn add_path(
		&mut self,
		path: &str,
		crate_name: &str,
		is_launcher: bool,
	) {
		let manifest_path =
			self.manifest_processor.get_manifest_path(crate_name).expect(&format!(
				"Crate:{} not found in manifest:{}. Please add the crate into \
				 [build-dependencies] list",
				crate_name,
				self.manifest_processor.manifest_path(),
			));

		self.pages.push((
			SimpleUiPage::new(path.to_owned(), crate_name.to_owned(), manifest_path),
			is_launcher,
		));
	}
}

fn activity_name_for(s: &SimpleUiPage) -> String {
	return s.module_name().to_owned();
}