Struct tauri::Context

source ·
pub struct Context<A: Assets> { /* private fields */ }
Expand description

User supplied data required inside of a Tauri application.

Stability

This is the output of the generate_context macro, and is not considered part of the stable API. Unless you know what you are doing and are prepared for this type to have breaking changes, do not create it yourself.

Implementations§

The config the application was prepared with.

A mutable reference to the config the application was prepared with.

The assets to be served directly by Tauri.

A mutable reference to the assets to be served directly by Tauri.

The default window icon Tauri should use when creating windows.

A mutable reference to the default window icon Tauri should use when creating windows.

The icon to use on the system tray UI.

A mutable reference to the icon to use on the system tray UI.

Package information.

Examples found in repository?
src/app.rs (line 1348)
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
  pub fn build<A: Assets>(mut self, context: Context<A>) -> crate::Result<App<R>> {
    #[cfg(target_os = "macos")]
    if self.menu.is_none() && self.enable_macos_default_menu {
      self.menu = Some(Menu::os_default(&context.package_info().name));
    }

    #[cfg(feature = "system-tray")]
    let system_tray_icon = context.system_tray_icon.clone();

    #[cfg(all(feature = "system-tray", target_os = "macos"))]
    let (system_tray_icon_as_template, system_tray_menu_on_left_click) = context
      .config
      .tauri
      .system_tray
      .as_ref()
      .map(|t| (t.icon_as_template, t.menu_on_left_click))
      .unwrap_or_default();

    #[cfg(shell_scope)]
    let shell_scope = context.shell_scope.clone();

    let manager = WindowManager::with_handlers(
      context,
      self.plugins,
      self.invoke_handler,
      self.on_page_load,
      self.uri_scheme_protocols,
      self.state,
      self.window_event_listeners,
      (self.menu, self.menu_event_listeners),
      (self.invoke_responder, self.invoke_initialization_script),
    );

    // set up all the windows defined in the config
    for config in manager.config().tauri.windows.clone() {
      let url = config.url.clone();
      let label = config.label.clone();
      let file_drop_enabled = config.file_drop_enabled;

      let mut webview_attributes = WebviewAttributes::new(url);
      if !file_drop_enabled {
        webview_attributes = webview_attributes.disable_file_drop_handler();
      }

      self.pending_windows.push(PendingWindow::with_config(
        config,
        webview_attributes,
        label,
      )?);
    }

    #[cfg(any(windows, target_os = "linux"))]
    let runtime = if self.runtime_any_thread {
      R::new_any_thread()?
    } else {
      R::new()?
    };
    #[cfg(not(any(windows, target_os = "linux")))]
    let runtime = R::new()?;

    let runtime_handle = runtime.handle();

    #[cfg(feature = "global-shortcut")]
    let global_shortcut_manager = runtime.global_shortcut_manager();

    #[cfg(feature = "clipboard")]
    let clipboard_manager = runtime.clipboard_manager();

    let mut app = App {
      runtime: Some(runtime),
      manager: manager.clone(),
      #[cfg(feature = "global-shortcut")]
      global_shortcut_manager: global_shortcut_manager.clone(),
      #[cfg(feature = "clipboard")]
      clipboard_manager: clipboard_manager.clone(),
      #[cfg(feature = "system-tray")]
      tray_handle: None,
      handle: AppHandle {
        runtime_handle,
        manager,
        #[cfg(feature = "global-shortcut")]
        global_shortcut_manager,
        #[cfg(feature = "clipboard")]
        clipboard_manager,
        #[cfg(feature = "system-tray")]
        tray_handle: None,
        #[cfg(updater)]
        updater_settings: self.updater_settings,
      },
    };

    let env = Env::default();
    app.manage(Scopes {
      fs: FsScope::for_fs_api(
        &app.manager.config(),
        app.package_info(),
        &env,
        &app.config().tauri.allowlist.fs.scope,
      )?,
      #[cfg(protocol_asset)]
      asset_protocol: FsScope::for_fs_api(
        &app.manager.config(),
        app.package_info(),
        &env,
        &app.config().tauri.allowlist.protocol.asset_scope,
      )?,
      #[cfg(http_request)]
      http: crate::scope::HttpScope::for_http_api(&app.config().tauri.allowlist.http.scope),
      #[cfg(shell_scope)]
      shell: ShellScope::new(shell_scope),
    });
    app.manage(env);

    #[cfg(windows)]
    {
      if let crate::utils::config::WebviewInstallMode::FixedRuntime { path } = &app
        .manager
        .config()
        .tauri
        .bundle
        .windows
        .webview_install_mode
      {
        if let Some(resource_dir) = app.path_resolver().resource_dir() {
          std::env::set_var(
            "WEBVIEW2_BROWSER_EXECUTABLE_FOLDER",
            resource_dir.join(path),
          );
        } else {
          #[cfg(debug_assertions)]
          eprintln!(
            "failed to resolve resource directory; fallback to the installed Webview2 runtime."
          );
        }
      }
    }

    #[cfg(feature = "system-tray")]
    if let Some(system_tray) = self.system_tray {
      let mut ids = HashMap::new();
      if let Some(menu) = system_tray.menu() {
        tray::get_menu_ids(&mut ids, menu);
      }
      let tray_icon = if let Some(icon) = system_tray.icon {
        Some(icon)
      } else if let Some(tray_icon) = system_tray_icon {
        Some(tray_icon.try_into()?)
      } else {
        None
      };
      let mut tray = tray::SystemTray::new()
        .with_icon(tray_icon.expect("tray icon not found; please configure it on tauri.conf.json"));
      if let Some(menu) = system_tray.menu {
        tray = tray.with_menu(menu);
      }
      #[cfg(target_os = "macos")]
      let tray = tray
        .with_icon_as_template(system_tray_icon_as_template)
        .with_menu_on_left_click(system_tray_menu_on_left_click);

      let tray_handler = app
        .runtime
        .as_ref()
        .unwrap()
        .system_tray(tray)
        .expect("failed to run tray");

      let tray_handle = tray::SystemTrayHandle {
        ids: Arc::new(std::sync::Mutex::new(ids)),
        inner: tray_handler,
      };
      let ids = tray_handle.ids.clone();
      app.tray_handle.replace(tray_handle.clone());
      app.handle.tray_handle.replace(tray_handle);
      for listener in self.system_tray_event_listeners {
        let app_handle = app.handle();
        let ids = ids.clone();
        let listener = Arc::new(std::sync::Mutex::new(listener));
        app
          .runtime
          .as_mut()
          .unwrap()
          .on_system_tray_event(move |event| {
            let app_handle = app_handle.clone();
            let event = match event {
              RuntimeSystemTrayEvent::MenuItemClick(id) => tray::SystemTrayEvent::MenuItemClick {
                id: ids.lock().unwrap().get(id).unwrap().clone(),
              },
              RuntimeSystemTrayEvent::LeftClick { position, size } => {
                tray::SystemTrayEvent::LeftClick {
                  position: *position,
                  size: *size,
                }
              }
              RuntimeSystemTrayEvent::RightClick { position, size } => {
                tray::SystemTrayEvent::RightClick {
                  position: *position,
                  size: *size,
                }
              }
              RuntimeSystemTrayEvent::DoubleClick { position, size } => {
                tray::SystemTrayEvent::DoubleClick {
                  position: *position,
                  size: *size,
                }
              }
            };
            let listener = listener.clone();
            listener.lock().unwrap()(&app_handle, event);
          });
      }
    }

    app.manager.initialize_plugins(&app.handle())?;

    let window_labels = self
      .pending_windows
      .iter()
      .map(|p| p.label.clone())
      .collect::<Vec<_>>();

    for pending in self.pending_windows {
      let pending =
        app
          .manager
          .prepare_window(app.handle.clone(), pending, &window_labels, None)?;
      let detached = app.runtime.as_ref().unwrap().create_window(pending)?;
      let _window = app.manager.attach_window(app.handle(), detached);
    }

    (self.setup)(&mut app).map_err(|e| crate::Error::Setup(e.into()))?;

    #[cfg(updater)]
    app.run_updater();

    Ok(app)
  }

A mutable reference to the package information.

The application pattern.

The scoped shell commands, where the HashMap key is the name each configuration.

Create a new Context from the minimal required items.

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