Struct tauri::StateManager

source ·
pub struct StateManager(_);
Expand description

The Tauri state manager.

Implementations§

Gets the state associated with the specified type.

Examples found in repository?
src/manager.rs (line 510)
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
  fn prepare_pending_window(
    &self,
    mut pending: PendingWindow<EventLoopMessage, R>,
    label: &str,
    window_labels: &[String],
    app_handle: AppHandle<R>,
    web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
  ) -> crate::Result<PendingWindow<EventLoopMessage, R>> {
    let is_init_global = self.inner.config.build.with_global_tauri;
    let plugin_init = self
      .inner
      .plugins
      .lock()
      .expect("poisoned plugin store")
      .initialization_script();

    let pattern_init = PatternJavascript {
      pattern: self.pattern().into(),
    }
    .render_default(&Default::default())?;

    let ipc_init = IpcJavascript {
      isolation_origin: &match self.pattern() {
        #[cfg(feature = "isolation")]
        Pattern::Isolation { schema, .. } => crate::pattern::format_real_schema(schema),
        _ => "".to_string(),
      },
    }
    .render_default(&Default::default())?;

    let mut webview_attributes = pending.webview_attributes;

    let mut window_labels = window_labels.to_vec();
    let l = label.to_string();
    if !window_labels.contains(&l) {
      window_labels.push(l);
    }
    webview_attributes = webview_attributes
      .initialization_script(&self.inner.invoke_initialization_script)
      .initialization_script(&format!(
        r#"
          Object.defineProperty(window, '__TAURI_METADATA__', {{
            value: {{
              __windows: {window_labels_array}.map(function (label) {{ return {{ label: label }} }}),
              __currentWindow: {{ label: {current_window_label} }}
            }}
          }})
        "#,
        window_labels_array = serde_json::to_string(&window_labels)?,
        current_window_label = serde_json::to_string(&label)?,
      ))
      .initialization_script(&self.initialization_script(&ipc_init.into_string(),&pattern_init.into_string(),&plugin_init, is_init_global)?)
      ;

    #[cfg(feature = "isolation")]
    if let Pattern::Isolation { schema, .. } = self.pattern() {
      webview_attributes = webview_attributes.initialization_script(
        &IsolationJavascript {
          origin: self.get_browser_origin(),
          isolation_src: &crate::pattern::format_real_schema(schema),
          style: tauri_utils::pattern::isolation::IFRAME_STYLE,
        }
        .render_default(&Default::default())?
        .into_string(),
      );
    }

    pending.webview_attributes = webview_attributes;

    let mut registered_scheme_protocols = Vec::new();

    for (uri_scheme, protocol) in &self.inner.uri_scheme_protocols {
      registered_scheme_protocols.push(uri_scheme.clone());
      let protocol = protocol.clone();
      let app_handle = Mutex::new(app_handle.clone());
      pending.register_uri_scheme_protocol(uri_scheme.clone(), move |p| {
        (protocol.protocol)(&app_handle.lock().unwrap(), p)
      });
    }

    let window_url = Url::parse(&pending.url).unwrap();
    let window_origin =
      if cfg!(windows) && window_url.scheme() != "http" && window_url.scheme() != "https" {
        format!("https://{}.localhost", window_url.scheme())
      } else {
        format!(
          "{}://{}{}",
          window_url.scheme(),
          window_url.host().unwrap(),
          if let Some(port) = window_url.port() {
            format!(":{}", port)
          } else {
            "".into()
          }
        )
      };

    if !registered_scheme_protocols.contains(&"tauri".into()) {
      pending.register_uri_scheme_protocol(
        "tauri",
        self.prepare_uri_scheme_protocol(&window_origin, web_resource_request_handler),
      );
      registered_scheme_protocols.push("tauri".into());
    }

    #[cfg(protocol_asset)]
    if !registered_scheme_protocols.contains(&"asset".into()) {
      use crate::api::file::SafePathBuf;
      use tokio::io::{AsyncReadExt, AsyncSeekExt};
      use url::Position;
      let asset_scope = self.state().get::<crate::Scopes>().asset_protocol.clone();
      pending.register_uri_scheme_protocol("asset", move |request| {
        let parsed_path = Url::parse(request.uri())?;
        let filtered_path = &parsed_path[..Position::AfterPath];
        let path = filtered_path
          .strip_prefix("asset://localhost/")
          // the `strip_prefix` only returns None when a request is made to `https://tauri.$P` on Windows
          // where `$P` is not `localhost/*`
          .unwrap_or("");
        let path = percent_encoding::percent_decode(path.as_bytes())
          .decode_utf8_lossy()
          .to_string();

        if let Err(e) = SafePathBuf::new(path.clone().into()) {
          debug_eprintln!("asset protocol path \"{}\" is not valid: {}", path, e);
          return HttpResponseBuilder::new().status(403).body(Vec::new());
        }

        if !asset_scope.is_allowed(&path) {
          debug_eprintln!("asset protocol not configured to allow the path: {}", path);
          return HttpResponseBuilder::new().status(403).body(Vec::new());
        }

        let path_ = path.clone();

        let mut response =
          HttpResponseBuilder::new().header("Access-Control-Allow-Origin", &window_origin);

        // handle 206 (partial range) http request
        if let Some(range) = request
          .headers()
          .get("range")
          .and_then(|r| r.to_str().map(|r| r.to_string()).ok())
        {
          #[derive(Default)]
          struct RangeMetadata {
            file: Option<tokio::fs::File>,
            range: Option<crate::runtime::http::HttpRange>,
            metadata: Option<std::fs::Metadata>,
            headers: HashMap<&'static str, String>,
            status_code: u16,
            body: Vec<u8>,
          }

          let mut range_metadata = crate::async_runtime::safe_block_on(async move {
            let mut data = RangeMetadata::default();
            // open the file
            let mut file = match tokio::fs::File::open(path_.clone()).await {
              Ok(file) => file,
              Err(e) => {
                debug_eprintln!("Failed to open asset: {}", e);
                data.status_code = 404;
                return data;
              }
            };
            // Get the file size
            let file_size = match file.metadata().await {
              Ok(metadata) => {
                let len = metadata.len();
                data.metadata.replace(metadata);
                len
              }
              Err(e) => {
                debug_eprintln!("Failed to read asset metadata: {}", e);
                data.file.replace(file);
                data.status_code = 404;
                return data;
              }
            };
            // parse the range
            let range = match crate::runtime::http::HttpRange::parse(
              &if range.ends_with("-*") {
                range.chars().take(range.len() - 1).collect::<String>()
              } else {
                range.clone()
              },
              file_size,
            ) {
              Ok(r) => r,
              Err(e) => {
                debug_eprintln!("Failed to parse range {}: {:?}", range, e);
                data.file.replace(file);
                data.status_code = 400;
                return data;
              }
            };

            // FIXME: Support multiple ranges
            // let support only 1 range for now
            if let Some(range) = range.first() {
              data.range.replace(*range);
              let mut real_length = range.length;
              // prevent max_length;
              // specially on webview2
              if range.length > file_size / 3 {
                // max size sent (400ko / request)
                // as it's local file system we can afford to read more often
                real_length = std::cmp::min(file_size - range.start, 1024 * 400);
              }

              // last byte we are reading, the length of the range include the last byte
              // who should be skipped on the header
              let last_byte = range.start + real_length - 1;

              data.headers.insert("Connection", "Keep-Alive".into());
              data.headers.insert("Accept-Ranges", "bytes".into());
              data
                .headers
                .insert("Content-Length", real_length.to_string());
              data.headers.insert(
                "Content-Range",
                format!("bytes {}-{}/{}", range.start, last_byte, file_size),
              );

              if let Err(e) = file.seek(std::io::SeekFrom::Start(range.start)).await {
                debug_eprintln!("Failed to seek file to {}: {}", range.start, e);
                data.file.replace(file);
                data.status_code = 422;
                return data;
              }

              let mut f = file.take(real_length);
              let r = f.read_to_end(&mut data.body).await;
              file = f.into_inner();
              data.file.replace(file);

              if let Err(e) = r {
                debug_eprintln!("Failed read file: {}", e);
                data.status_code = 422;
                return data;
              }
              // partial content
              data.status_code = 206;
            } else {
              data.status_code = 200;
            }

            data
          });

          for (k, v) in range_metadata.headers {
            response = response.header(k, v);
          }

          let mime_type = if let (Some(mut file), Some(metadata), Some(range)) = (
            range_metadata.file,
            range_metadata.metadata,
            range_metadata.range,
          ) {
            // if we're already reading the beginning of the file, we do not need to re-read it
            if range.start == 0 {
              MimeType::parse(&range_metadata.body, &path)
            } else {
              let (status, bytes) = crate::async_runtime::safe_block_on(async move {
                let mut status = None;
                if let Err(e) = file.rewind().await {
                  debug_eprintln!("Failed to rewind file: {}", e);
                  status.replace(422);
                  (status, Vec::with_capacity(0))
                } else {
                  // taken from https://docs.rs/infer/0.9.0/src/infer/lib.rs.html#240-251
                  let limit = std::cmp::min(metadata.len(), 8192) as usize + 1;
                  let mut bytes = Vec::with_capacity(limit);
                  if let Err(e) = file.take(8192).read_to_end(&mut bytes).await {
                    debug_eprintln!("Failed read file: {}", e);
                    status.replace(422);
                  }
                  (status, bytes)
                }
              });
              if let Some(s) = status {
                range_metadata.status_code = s;
              }
              MimeType::parse(&bytes, &path)
            }
          } else {
            MimeType::parse(&range_metadata.body, &path)
          };
          response
            .mimetype(&mime_type)
            .status(range_metadata.status_code)
            .body(range_metadata.body)
        } else {
          match crate::async_runtime::safe_block_on(async move { tokio::fs::read(path_).await }) {
            Ok(data) => {
              let mime_type = MimeType::parse(&data, &path);
              response.mimetype(&mime_type).body(data)
            }
            Err(e) => {
              debug_eprintln!("Failed to read file: {}", e);
              response.status(404).body(Vec::new())
            }
          }
        }
      });
    }

    #[cfg(feature = "isolation")]
    if let Pattern::Isolation {
      assets,
      schema,
      key: _,
      crypto_keys,
    } = &self.inner.pattern
    {
      let assets = assets.clone();
      let schema_ = schema.clone();
      let url_base = format!("{}://localhost", schema_);
      let aes_gcm_key = *crypto_keys.aes_gcm().raw();

      pending.register_uri_scheme_protocol(schema, move |request| {
        match request_to_path(request, &url_base).as_str() {
          "index.html" => match assets.get(&"index.html".into()) {
            Some(asset) => {
              let asset = String::from_utf8_lossy(asset.as_ref());
              let template = tauri_utils::pattern::isolation::IsolationJavascriptRuntime {
                runtime_aes_gcm_key: &aes_gcm_key,
              };
              match template.render(asset.as_ref(), &Default::default()) {
                Ok(asset) => HttpResponseBuilder::new()
                  .mimetype("text/html")
                  .body(asset.into_string().as_bytes().to_vec()),
                Err(_) => HttpResponseBuilder::new()
                  .status(500)
                  .mimetype("text/plain")
                  .body(Vec::new()),
              }
            }

            None => HttpResponseBuilder::new()
              .status(404)
              .mimetype("text/plain")
              .body(Vec::new()),
          },
          _ => HttpResponseBuilder::new()
            .status(404)
            .mimetype("text/plain")
            .body(Vec::new()),
        }
      });
    }

    Ok(pending)
  }

  fn prepare_ipc_handler(
    &self,
    app_handle: AppHandle<R>,
  ) -> WebviewIpcHandler<EventLoopMessage, R> {
    let manager = self.clone();
    Box::new(move |window, #[allow(unused_mut)] mut request| {
      let window = Window::new(manager.clone(), window, app_handle.clone());

      #[cfg(feature = "isolation")]
      if let Pattern::Isolation { crypto_keys, .. } = manager.pattern() {
        match RawIsolationPayload::try_from(request.as_str())
          .and_then(|raw| crypto_keys.decrypt(raw))
        {
          Ok(json) => request = json,
          Err(e) => {
            let error: crate::Error = e.into();
            let _ = window.eval(&format!(
              r#"console.error({})"#,
              JsonValue::String(error.to_string())
            ));
            return;
          }
        }
      }

      match serde_json::from_str::<InvokePayload>(&request) {
        Ok(message) => {
          let _ = window.on_message(message);
        }
        Err(e) => {
          let error: crate::Error = e.into();
          let _ = window.eval(&format!(
            r#"console.error({})"#,
            JsonValue::String(error.to_string())
          ));
        }
      }
    })
  }

  pub fn get_asset(&self, mut path: String) -> Result<Asset, Box<dyn std::error::Error>> {
    let assets = &self.inner.assets;
    if path.ends_with('/') {
      path.pop();
    }
    path = percent_encoding::percent_decode(path.as_bytes())
      .decode_utf8_lossy()
      .to_string();
    let path = if path.is_empty() {
      // if the url is `tauri://localhost`, we should load `index.html`
      "index.html".to_string()
    } else {
      // skip leading `/`
      path.chars().skip(1).collect::<String>()
    };

    let mut asset_path = AssetKey::from(path.as_str());

    let asset_response = assets
      .get(&path.as_str().into())
      .or_else(|| {
        eprintln!("Asset `{}` not found; fallback to {}.html", path, path);
        let fallback = format!("{}.html", path.as_str()).into();
        let asset = assets.get(&fallback);
        asset_path = fallback;
        asset
      })
      .or_else(|| {
        debug_eprintln!(
          "Asset `{}` not found; fallback to {}/index.html",
          path,
          path
        );
        let fallback = format!("{}/index.html", path.as_str()).into();
        let asset = assets.get(&fallback);
        asset_path = fallback;
        asset
      })
      .or_else(|| {
        debug_eprintln!("Asset `{}` not found; fallback to index.html", path);
        let fallback = AssetKey::from("index.html");
        let asset = assets.get(&fallback);
        asset_path = fallback;
        asset
      })
      .ok_or_else(|| crate::Error::AssetNotFound(path.clone()))
      .map(Cow::into_owned);

    let mut csp_header = None;
    let is_html = asset_path.as_ref().ends_with(".html");

    match asset_response {
      Ok(asset) => {
        let final_data = if is_html {
          let mut asset = String::from_utf8_lossy(&asset).into_owned();
          if let Some(csp) = self.csp() {
            csp_header.replace(set_csp(
              &mut asset,
              self.inner.assets.clone(),
              &asset_path,
              self,
              csp,
            ));
          }

          asset.as_bytes().to_vec()
        } else {
          asset
        };
        let mime_type = MimeType::parse(&final_data, &path);
        Ok(Asset {
          bytes: final_data.to_vec(),
          mime_type,
          csp_header,
        })
      }
      Err(e) => {
        debug_eprintln!("{:?}", e); // TODO log::error!
        Err(Box::new(e))
      }
    }
  }

  #[allow(clippy::type_complexity)]
  fn prepare_uri_scheme_protocol(
    &self,
    window_origin: &str,
    web_resource_request_handler: Option<
      Box<dyn Fn(&HttpRequest, &mut HttpResponse) + Send + Sync>,
    >,
  ) -> Box<dyn Fn(&HttpRequest) -> Result<HttpResponse, Box<dyn std::error::Error>> + Send + Sync>
  {
    let manager = self.clone();
    let window_origin = window_origin.to_string();
    Box::new(move |request| {
      let path = request
        .uri()
        .split(&['?', '#'][..])
        // ignore query string and fragment
        .next()
        .unwrap()
        .strip_prefix("tauri://localhost")
        .map(|p| p.to_string())
        // the `strip_prefix` only returns None when a request is made to `https://tauri.$P` on Windows
        // where `$P` is not `localhost/*`
        .unwrap_or_else(|| "".to_string());
      let asset = manager.get_asset(path)?;
      let mut builder = HttpResponseBuilder::new()
        .header("Access-Control-Allow-Origin", &window_origin)
        .mimetype(&asset.mime_type);
      if let Some(csp) = &asset.csp_header {
        builder = builder.header("Content-Security-Policy", csp);
      }
      let mut response = builder.body(asset.bytes)?;
      if let Some(handler) = &web_resource_request_handler {
        handler(request, &mut response);

        // if it's an HTML file, we need to set the CSP meta tag on Linux
        #[cfg(target_os = "linux")]
        if let Some(response_csp) = response.headers().get("Content-Security-Policy") {
          let response_csp = String::from_utf8_lossy(response_csp.as_bytes());
          let body = set_html_csp(&String::from_utf8_lossy(response.body()), &response_csp);
          *response.body_mut() = body.as_bytes().to_vec();
        }
      } else {
        #[cfg(target_os = "linux")]
        {
          if let Some(csp) = &asset.csp_header {
            let body = set_html_csp(&String::from_utf8_lossy(response.body()), csp);
            *response.body_mut() = body.as_bytes().to_vec();
          }
        }
      }
      Ok(response)
    })
  }

  fn initialization_script(
    &self,
    ipc_script: &str,
    pattern_script: &str,
    plugin_initialization_script: &str,
    with_global_tauri: bool,
  ) -> crate::Result<String> {
    #[derive(Template)]
    #[default_template("../scripts/init.js")]
    struct InitJavascript<'a> {
      origin: String,
      #[raw]
      pattern_script: &'a str,
      #[raw]
      ipc_script: &'a str,
      #[raw]
      bundle_script: &'a str,
      // A function to immediately listen to an event.
      #[raw]
      listen_function: &'a str,
      #[raw]
      core_script: &'a str,
      #[raw]
      event_initialization_script: &'a str,
      #[raw]
      plugin_initialization_script: &'a str,
      #[raw]
      freeze_prototype: &'a str,
      #[raw]
      hotkeys: &'a str,
    }

    let bundle_script = if with_global_tauri {
      include_str!("../scripts/bundle.global.js")
    } else {
      ""
    };

    let freeze_prototype = if self.inner.config.tauri.security.freeze_prototype {
      include_str!("../scripts/freeze_prototype.js")
    } else {
      ""
    };

    #[cfg(any(debug_assertions, feature = "devtools"))]
    let hotkeys = &format!(
      "
      {};
      window.hotkeys('{}', () => {{
        window.__TAURI_INVOKE__('tauri', {{
          __tauriModule: 'Window',
          message: {{
            cmd: 'manage',
            data: {{
              cmd: {{
                type: '__toggleDevtools'
              }}
            }}
          }}
        }});
      }});
    ",
      include_str!("../scripts/hotkey.js"),
      if cfg!(target_os = "macos") {
        "command+option+i"
      } else {
        "ctrl+shift+i"
      }
    );
    #[cfg(not(any(debug_assertions, feature = "devtools")))]
    let hotkeys = "";

    InitJavascript {
      origin: self.get_browser_origin(),
      pattern_script,
      ipc_script,
      bundle_script,
      listen_function: &format!(
        "function listen(eventName, cb) {{ {} }}",
        crate::event::listen_js(
          self.event_listeners_object_name(),
          "eventName".into(),
          0,
          None,
          "window['_' + window.__TAURI__.transformCallback(cb) ]".into()
        )
      ),
      core_script: include_str!("../scripts/core.js"),
      event_initialization_script: &self.event_initialization_script(),
      plugin_initialization_script,
      freeze_prototype,
      hotkeys,
    }
    .render_default(&Default::default())
    .map(|s| s.into_string())
    .map_err(Into::into)
  }

  fn event_initialization_script(&self) -> String {
    format!(
      "
      Object.defineProperty(window, '{function}', {{
        value: function (eventData) {{
          const listeners = (window['{listeners}'] && window['{listeners}'][eventData.event]) || []

          for (let i = listeners.length - 1; i >= 0; i--) {{
            const listener = listeners[i]
            if (listener.windowLabel === null || listener.windowLabel === eventData.windowLabel) {{
              eventData.id = listener.id
              listener.handler(eventData)
            }}
          }}
        }}
      }});
    ",
      function = self.event_emit_function_name(),
      listeners = self.event_listeners_object_name()
    )
  }
}

#[cfg(test)]
mod test {
  use crate::{generate_context, plugin::PluginStore, StateManager, Wry};

  use super::WindowManager;

  #[test]
  fn check_get_url() {
    let context = generate_context!("test/fixture/src-tauri/tauri.conf.json", crate);
    let manager: WindowManager<Wry> = WindowManager::with_handlers(
      context,
      PluginStore::default(),
      Box::new(|_| ()),
      Box::new(|_, _| ()),
      Default::default(),
      StateManager::new(),
      Default::default(),
      Default::default(),
      (std::sync::Arc::new(|_, _, _, _| ()), "".into()),
    );

    #[cfg(custom_protocol)]
    assert_eq!(manager.get_url().to_string(), "tauri://localhost");

    #[cfg(dev)]
    assert_eq!(manager.get_url().to_string(), "http://localhost:4000/");
  }
}

impl<R: Runtime> WindowManager<R> {
  pub fn run_invoke_handler(&self, invoke: Invoke<R>) {
    (self.inner.invoke_handler)(invoke);
  }

  pub fn run_on_page_load(&self, window: Window<R>, payload: PageLoadPayload) {
    (self.inner.on_page_load)(window.clone(), payload.clone());
    self
      .inner
      .plugins
      .lock()
      .expect("poisoned plugin store")
      .on_page_load(window, payload);
  }

  pub fn extend_api(&self, invoke: Invoke<R>) {
    self
      .inner
      .plugins
      .lock()
      .expect("poisoned plugin store")
      .extend_api(invoke);
  }

  pub fn initialize_plugins(&self, app: &AppHandle<R>) -> crate::Result<()> {
    self
      .inner
      .plugins
      .lock()
      .expect("poisoned plugin store")
      .initialize(app, &self.inner.config.plugins)
  }

  pub fn prepare_window(
    &self,
    app_handle: AppHandle<R>,
    mut pending: PendingWindow<EventLoopMessage, R>,
    window_labels: &[String],
    web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
  ) -> crate::Result<PendingWindow<EventLoopMessage, R>> {
    if self.windows_lock().contains_key(&pending.label) {
      return Err(crate::Error::WindowLabelAlreadyExists(pending.label));
    }
    #[allow(unused_mut)] // mut url only for the data-url parsing
    let (is_local, mut url) = match &pending.webview_attributes.url {
      WindowUrl::App(path) => {
        let url = self.get_url();
        (
          true,
          // ignore "index.html" just to simplify the url
          if path.to_str() != Some("index.html") {
            url
              .join(&path.to_string_lossy())
              .map_err(crate::Error::InvalidUrl)
              // this will never fail
              .unwrap()
          } else {
            url.into_owned()
          },
        )
      }
      WindowUrl::External(url) => {
        let config_url = self.get_url();
        (config_url.make_relative(url).is_some(), url.clone())
      }
      _ => unimplemented!(),
    };

    #[cfg(not(feature = "window-data-url"))]
    if url.scheme() == "data" {
      return Err(crate::Error::InvalidWindowUrl(
        "data URLs are not supported without the `window-data-url` feature.",
      ));
    }

    #[cfg(feature = "window-data-url")]
    if let Some(csp) = self.csp() {
      if url.scheme() == "data" {
        if let Ok(data_url) = data_url::DataUrl::process(url.as_str()) {
          let (body, _) = data_url.decode_to_vec().unwrap();
          let html = String::from_utf8_lossy(&body).into_owned();
          // naive way to check if it's an html
          if html.contains('<') && html.contains('>') {
            let mut document = tauri_utils::html::parse(html);
            tauri_utils::html::inject_csp(&mut document, &csp.to_string());
            url.set_path(&format!("text/html,{}", document.to_string()));
          }
        }
      }
    }

    pending.url = url.to_string();

    if !pending.window_builder.has_icon() {
      if let Some(default_window_icon) = self.inner.default_window_icon.clone() {
        pending.window_builder = pending
          .window_builder
          .icon(default_window_icon.try_into()?)?;
      }
    }

    if pending.window_builder.get_menu().is_none() {
      if let Some(menu) = &self.inner.menu {
        pending = pending.set_menu(menu.clone());
      }
    }

    if is_local {
      let label = pending.label.clone();
      pending = self.prepare_pending_window(
        pending,
        &label,
        window_labels,
        app_handle.clone(),
        web_resource_request_handler,
      )?;
      pending.ipc_handler = Some(self.prepare_ipc_handler(app_handle));
    }

    // in `Windows`, we need to force a data_directory
    // but we do respect user-specification
    #[cfg(any(target_os = "linux", target_os = "windows"))]
    if pending.webview_attributes.data_directory.is_none() {
      let local_app_data = resolve_path(
        &self.inner.config,
        &self.inner.package_info,
        self.inner.state.get::<crate::Env>().inner(),
        &self.inner.config.tauri.bundle.identifier,
        Some(BaseDirectory::LocalData),
      );
      if let Ok(user_data_dir) = local_app_data {
        pending.webview_attributes.data_directory = Some(user_data_dir);
      }
    }

    // make sure the directory is created and available to prevent a panic
    if let Some(user_data_dir) = &pending.webview_attributes.data_directory {
      if !user_data_dir.exists() {
        create_dir_all(user_data_dir)?;
      }
    }

    Ok(pending)
  }

Gets the state associated with the specified type.

Examples found in repository?
src/lib.rs (line 758)
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
  fn state<T>(&self) -> State<'_, T>
  where
    T: Send + Sync + 'static,
  {
    self
      .manager()
      .inner
      .state
      .try_get()
      .expect("state() called before manage() for given type")
  }

  /// Attempts to retrieve the managed state for the type `T`.
  ///
  /// Returns `Some` if the state has previously been [managed](Self::manage). Otherwise returns `None`.
  fn try_state<T>(&self) -> Option<State<'_, T>>
  where
    T: Send + Sync + 'static,
  {
    self.manager().inner.state.try_get()
  }
More examples
Hide additional examples
src/state.rs (line 50)
49
50
51
52
53
54
55
56
  fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
    Ok(command.message.state_ref().try_get().unwrap_or_else(|| {
      panic!(
        "state not managed for field `{}` on command `{}`. You must call `.manage()` before using this command",
        command.key, command.name
      )
    }))
  }

Trait Implementations§

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more