asset.rs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. use std::path::PathBuf;
  2. use webview_official::Webview;
  3. #[allow(clippy::option_env_unwrap)]
  4. pub fn load(
  5. webview: &mut Webview<'_>,
  6. asset: String,
  7. asset_type: String,
  8. callback: String,
  9. error: String,
  10. ) {
  11. let mut webview_mut = webview.as_mut();
  12. crate::execute_promise(
  13. webview,
  14. move || {
  15. let mut path = PathBuf::from(if asset.starts_with('/') {
  16. asset.replacen("/", "", 1)
  17. } else {
  18. asset.clone()
  19. });
  20. let mut read_asset;
  21. loop {
  22. read_asset = crate::assets::ASSETS.get(&format!(
  23. "{}/{}",
  24. option_env!("TAURI_DIST_DIR")
  25. .expect("tauri apps should be built with the TAURI_DIST_DIR environment variable"),
  26. path.to_string_lossy()
  27. ));
  28. if read_asset.is_err() {
  29. match path.iter().next() {
  30. Some(component) => {
  31. let first_component = component.to_str().expect("failed to read path component");
  32. path = PathBuf::from(path.to_string_lossy().replacen(
  33. format!("{}/", first_component).as_str(),
  34. "",
  35. 1,
  36. ));
  37. }
  38. None => {
  39. return Err(anyhow::anyhow!("Asset '{}' not found", asset));
  40. }
  41. }
  42. } else {
  43. break;
  44. }
  45. }
  46. if asset_type == "image" {
  47. let ext = if asset.ends_with("gif") {
  48. "gif"
  49. } else if asset.ends_with("png") {
  50. "png"
  51. } else {
  52. "jpeg"
  53. };
  54. Ok(format!(
  55. r#""data:image/{};base64,{}""#,
  56. ext,
  57. base64::encode(&read_asset.expect("Failed to read asset type").into_owned())
  58. ))
  59. } else {
  60. let asset_bytes = read_asset.expect("Failed to read asset type");
  61. webview_mut.dispatch(move |webview_ref| {
  62. let asset_str =
  63. std::str::from_utf8(&asset_bytes).expect("failed to convert asset bytes to u8 slice");
  64. if asset_type == "stylesheet" {
  65. webview_ref.eval(&format!(
  66. r#"
  67. (function (content) {{
  68. var css = document.createElement('style')
  69. css.type = 'text/css'
  70. if (css.styleSheet)
  71. css.styleSheet.cssText = content
  72. else
  73. css.appendChild(document.createTextNode(content))
  74. document.getElementsByTagName("head")[0].appendChild(css);
  75. }})(`{css}`)
  76. "#,
  77. // Escape octal sequences, which aren't allowed in template literals
  78. css = asset_str.replace("\\", "\\\\").as_str()
  79. ));
  80. } else {
  81. webview_ref.eval(asset_str);
  82. }
  83. })?;
  84. Ok("Asset loaded successfully".to_string())
  85. }
  86. },
  87. callback,
  88. error,
  89. );
  90. }