ronantakizawa/codereview-bench huggingface dataset:
Repository: tauri-apps/tauri
File: core/tauri-utils/src/plugin.rs (Rust)

Code before:
        .canonicalize()
        .expect("failed to canonicalize global API script path")
        .display()
    )
  }

  /// Loads all the global API scripts defined with [`define_global_api_script_path`]
  /// and saves them to the out dir with filename [`COLLECTED_GLOBAL_API_SCRIPT_PATH`].
  pub fn load_global_api_scripts(out_dir: &Path) {
    let mut merged_script = String::new();

    for (key, value) in vars_os() {
      let key = key.to_string_lossy();

      if key.starts_with("DEP_") && key.ends_with(GLOBAL_API_SCRIPT_PATH_KEY) {
        let script_path = PathBuf::from(value);
        let script = std::fs::read_to_string(&script_path).unwrap_or_else(|e| {
          panic!(
            "failed to read global script path at {}: {e}",
            script_path.display()
          )
        });

        merged_script.push_str(";(function () {\n");
        merged_script.push_str(&script);
        merged_script.push_str("})()");
      }
    }

    std::fs::write(
      out_dir.join(COLLECTED_GLOBAL_API_SCRIPT_PATH),
      merged_script,
    )
    .expect("failed to write global API script");
  }
}


Review comment (suggestion):
This should be handled by the user, we shouldn't also merge all the plugins into a single script, instead we should save them as a vector of scripts and load them one by one so they have a different execution context, otherwise different scripts could have a similar intermediate variable and cause conflicts and errors. 

Code after:
        .canonicalize()
        .expect("failed to canonicalize global API script path")
        .display()
    )
  }

  /// Collects the path of all the global API scripts defined with [`define_global_api_script_path`]
  /// and saves them to the out dir with filename [`GLOBAL_API_SCRIPT_FILE_LIST_PATH`].
  pub fn load_global_api_scripts(out_dir: &Path) {
    let mut scripts = Vec::new();

    for (key, value) in vars_os() {
      let key = key.to_string_lossy();

      if key.starts_with("DEP_") && key.ends_with(GLOBAL_API_SCRIPT_PATH_KEY) {
        let script_path = PathBuf::from(value);
        scripts.push(script_path);
      }
    }

    std::fs::write(
      out_dir.join(GLOBAL_API_SCRIPT_FILE_LIST_PATH),
      serde_json::to_string(&scripts).expect("failed to serialize global API script paths"),
    )
    .expect("failed to write global API script");
  }
}
Repository: tauri-apps/tauri
File: tooling/api/src/path.ts (TypeScript)

Code before:
 * Returns the extension of the `path`.
 * @example
 * ```typescript
 * import { extname } from '@tauri-apps/api/path';
 * const ext = await extname('/path/to/file.html');
 * assert(ext === 'html');
 * ```
 *
 * @since 1.0.0
 */
async function extname(path: string): Promise<string> {
  return invokeTauriCommand<string>({
    __tauriModule: 'Path',
    message: {
      cmd: 'extname',
      path
    }
  })
}

/**
 * Returns the last portion of a `path`. Trailing directory separators are ignored.
 * @example
 * ```typescript
 * import { basename } from '@tauri-apps/api/path';
 * const base = await basename('path/to/app.conf');
 * ```
 *
 * @param ext An optional file extension to be removed from the returned path.
 *
 * @since 1.0.0
 */
async function basename(path: string, ext?: string): Promise<string> {
  return invokeTauriCommand<string>({
    __tauriModule: 'Path',
    message: {
      cmd: 'basename',
      path,
      ext
    }
  })
}

/**
 * Returns whether the path is absolute or not.
 * @example
 * ```typescript
 * import { isAbsolute } from '@tauri-apps/api/path';
 * assert(await isAbsolute('/home/tauri'));
 * ```
 *

Review comment (suggestion):
```suggestion
 * const base = await basename('path/to/app.conf');
 * assert(base === 'app.conf');
```

Code after:
 * Returns the extension of the `path`.
 * @example
 * ```typescript
 * import { extname } from '@tauri-apps/api/path';
 * const ext = await extname('/path/to/file.html');
 * assert(ext === 'html');
 * ```
 *
 * @since 1.0.0
 */
async function extname(path: string): Promise<string> {
  return invokeTauriCommand<string>({
    __tauriModule: 'Path',
    message: {
      cmd: 'extname',
      path
    }
  })
}

/**
 * Returns the last portion of a `path`. Trailing directory separators are ignored.
 * @example
 * ```typescript
 * import { basename } from '@tauri-apps/api/path';
 * const base = await basename('path/to/app.conf');
 * assert(base === 'app.conf');
 * ```
 *
 * @param ext An optional file extension to be removed from the returned path.
 *
 * @since 1.0.0
 */
async function basename(path: string, ext?: string): Promise<string> {
  return invokeTauriCommand<string>({
    __tauriModule: 'Path',
    message: {
      cmd: 'basename',
      path,
      ext
    }
  })
}

/**
 * Returns whether the path is absolute or not.
 * @example
 * ```typescript
 * import { isAbsolute } from '@tauri-apps/api/path';
 * assert(await isAbsolute('/home/tauri'));
 * ```
Repository: tauri-apps/tauri
File: core/tauri-runtime-wry/src/lib.rs (Rust)

Code before:
  window.inner_size()
}

#[cfg(windows)]
fn clear_window_surface(
  window: &Window,
  surface: &mut softbuffer::Surface<Arc<Window>, Arc<Window>>,
) {
  let size = window.inner_size();
  if let (Some(width), Some(height)) = (
    std::num::NonZeroU32::new(size.width),
    std::num::NonZeroU32::new(size.height),
  ) {
    surface.resize(width, height).unwrap();
    let mut buffer = surface.buffer_mut().unwrap();
    buffer.fill(0);
    let _ = buffer.present();
  }
}

#[cfg(windows)]
fn update_webview_visibility(
  window: &Window,
  webviews: &[WebviewWrapper],
) -> windows::core::Result<()> {
  let is_visible = window.is_visible() && !window.is_minimized();
  for webview in webviews {
    let controller = webview.controller();
    unsafe { controller.SetIsVisible(is_visible) }?;
  }
  Ok(())
}


Review comment (suggestion):
I think this should be passed `is_visible` as an argument, because in the case of when calling `window.hide()` we already know that it is not visible and so we don't need to call `window.is_visible()`

Code after:
) -> TaoPhysicalSize<u32> {
  window.inner_size()
}

#[cfg(windows)]
fn clear_window_surface(
  window: &Window,
  surface: &mut softbuffer::Surface<Arc<Window>, Arc<Window>>,
) {
  let size = window.inner_size();
  if let (Some(width), Some(height)) = (
    std::num::NonZeroU32::new(size.width),
    std::num::NonZeroU32::new(size.height),
  ) {
    surface.resize(width, height).unwrap();
    let mut buffer = surface.buffer_mut().unwrap();
    buffer.fill(0);
    let _ = buffer.present();
  }
}

#[cfg(windows)]
fn set_webview_visibility(
  webviews: &[WebviewWrapper],
  is_visible: bool,
) -> windows::core::Result<()> {
  for webview in webviews {
    let controller = webview.controller();
    unsafe { controller.SetIsVisible(is_visible) }?;
  }
  Ok(())
}
Repository: tauri-apps/tauri
File: core/tauri/src/webview/webview_window.rs (Rust)

Code before:
  pub fn incognito(mut self, incognito: bool) -> Self {
    self.webview_builder = self.webview_builder.incognito(incognito);
    self
  }

  /// Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
  #[must_use]
  pub fn auto_resize(mut self) -> Self {
    self.webview_builder = self.webview_builder.auto_resize();
    self
  }

  /// Set a proxy URL for the WebView for all network requests.
  ///
  /// Must be either a `http://` or a `socks5://` URL.
  #[must_use]
  pub fn proxy_url(mut self, url: Url) -> Self {
    self.webview_builder = self.webview_builder.proxy_url(url);
    self
  }

  /// Whether page zooming by hotkeys is enabled
  ///
  /// ## Platform-specific
  ///
  /// **macOS / Linux / Android / iOS**: Unsupported
  #[must_use]
  pub fn zoom_hotkeys_enabled(mut self, enabled: bool) -> Self {
    self.webview_builder = self.webview_builder.zoom_hotkeys_enabled(enabled);
    self
  }
}

/// A type that wraps a [`Window`] together with a [`Webview`].
#[default_runtime(crate::Wry, wry)]
#[derive(Debug)]
pub struct WebviewWindow<R: Runtime> {
  pub(crate) webview: Webview<R>,
}

impl<R: Runtime> AsRef<Webview<R>> for WebviewWindow<R> {
  fn as_ref(&self) -> &Webview<R> {
    &self.webview
  }
}

impl<R: Runtime> Clone for WebviewWindow<R> {
  fn clone(&self) -> Self {
    Self {
      webview: self.webview.clone(),
    }

Review comment (suggestion):
```suggestion
  /// Whether page zooming by hotkeys is enabled **Windows only**
```

Code after:
  pub fn incognito(mut self, incognito: bool) -> Self {
    self.webview_builder = self.webview_builder.incognito(incognito);
    self
  }

  /// Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
  #[must_use]
  pub fn auto_resize(mut self) -> Self {
    self.webview_builder = self.webview_builder.auto_resize();
    self
  }

  /// Set a proxy URL for the WebView for all network requests.
  ///
  /// Must be either a `http://` or a `socks5://` URL.
  #[must_use]
  pub fn proxy_url(mut self, url: Url) -> Self {
    self.webview_builder = self.webview_builder.proxy_url(url);
    self
  }

  /// Whether page zooming by hotkeys is enabled **Windows only**
  #[must_use]
  pub fn zoom_hotkeys_enabled(mut self, enabled: bool) -> Self {
    self.webview_builder = self.webview_builder.zoom_hotkeys_enabled(enabled);
    self
  }
}

/// A type that wraps a [`Window`] together with a [`Webview`].
#[default_runtime(crate::Wry, wry)]
#[derive(Debug)]
pub struct WebviewWindow<R: Runtime> {
  pub(crate) webview: Webview<R>,
}

impl<R: Runtime> AsRef<Webview<R>> for WebviewWindow<R> {
  fn as_ref(&self) -> &Webview<R> {
    &self.webview
  }
}

impl<R: Runtime> Clone for WebviewWindow<R> {
  fn clone(&self) -> Self {
    Self {
      webview: self.webview.clone(),
    }
  }
}

impl<R: Runtime> Eq for WebviewWindow<R> {}
Repository: tauri-apps/tauri
File: tooling/api/src/webview.ts (TypeScript)

Code before:
   */
  userAgent?: string
  /**
   * Whether or not the webview should be launched in incognito mode.
   *
   * #### Platform-specific
   *
   * - **Android:** Unsupported.
   */
  incognito?: boolean
  /**
   * The proxy URL for the WebView for all network requests.
   *
   * Must be either a `http://` or a `socks5://` URL.
   *
   * #### Platform-specific
   *
   * - **macOS**: Requires the `macos-proxy` feature flag and only compiles for macOS 14+.
   * */
  proxyUrl?: string
  /**
   * Whether page zooming by hotkeys or gestures is enabled
   *
   * ## Platform-specific
   *
   * - **macOS / Linux / Android / iOS**: Unsupported
   */
  zoomHotkeysEnabled?: boolean
}

export { Webview, getCurrent, getAll }

export type { DragDropEvent, DragDropPayload, WebviewOptions }


Review comment (suggestion):
```suggestion
   * Whether page zooming by hotkeys or gestures is enabled **Windows Only**
```

Code after:
   */
  userAgent?: string
  /**
   * Whether or not the webview should be launched in incognito mode.
   *
   * #### Platform-specific
   *
   * - **Android:** Unsupported.
   */
  incognito?: boolean
  /**
   * The proxy URL for the WebView for all network requests.
   *
   * Must be either a `http://` or a `socks5://` URL.
   *
   * #### Platform-specific
   *
   * - **macOS**: Requires the `macos-proxy` feature flag and only compiles for macOS 14+.
   * */
  proxyUrl?: string
  /**
   * Whether page zooming by hotkeys or gestures is enabled **Windows Only**
   */
  zoomHotkeysEnabled?: boolean
}

export { Webview, getCurrent, getAll }

export type { DragDropEvent, DragDropPayload, WebviewOptions }
Repository: tauri-apps/tauri
File: core/tauri-runtime/src/webview.rs (Rust)

Code before:
    self.transparent = transparent;
    self
  }

  /// Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
  #[must_use]
  pub fn auto_resize(mut self) -> Self {
    self.auto_resize = true;
    self
  }

  /// Enable proxy for the WebView
  #[must_use]
  pub fn proxy_url(mut self, url: Url) -> Self {
    self.proxy_url = Some(url);
    self
  }

  /// Whether page zooming by hotkeys is enabled
  ///
  /// ## Platform-specific:
  ///
  /// - **Windows**: Controls WebView2's [`IsZoomControlEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2settings?view=webview2-winrt-1.0.2420.47#iszoomcontrolenabled) setting.
  /// - **MacOS / Linux / Android / iOS**: Requires `webview:allow-set-webview-zoom` permission,
  /// we'll inject a polyfill that zooms in and out with `ctrl`/`command` + `-`/`=`,
  /// 20% in each step, ranging from 20% to 1000%.
  #[must_use]
  pub fn zoom_hotkeys_enabled(mut self, enabled: bool) -> Self {
    self.zoom_hotkeys_enabled = enabled;
    self
  }
}

/// IPC handler.
pub type WebviewIpcHandler<T, R> = Box<dyn Fn(DetachedWebview<T, R>, Request<String>) + Send>;


Review comment (security):
```suggestion
  /// - **MacOS / Linux **: Injects a polyfill that zooms in and out with `ctrl/command` + `-/=`,
  /// 20% in each step, ranging from 20% to 1000%. Requires `webview:allow-set-webview-zoom` permission
  ///
  /// - **Android / iOS **: Unsupported.
```

Code after:
    self.transparent = transparent;
    self
  }

  /// Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
  #[must_use]
  pub fn auto_resize(mut self) -> Self {
    self.auto_resize = true;
    self
  }

  /// Enable proxy for the WebView
  #[must_use]
  pub fn proxy_url(mut self, url: Url) -> Self {
    self.proxy_url = Some(url);
    self
  }

  /// Whether page zooming by hotkeys is enabled
  ///
  /// ## Platform-specific:
  ///
  /// - **Windows**: Controls WebView2's [`IsZoomControlEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2settings?view=webview2-winrt-1.0.2420.47#iszoomcontrolenabled) setting.
  /// - **MacOS / Linux**: Injects a polyfill that zooms in and out with `ctrl/command` + `-/=`,
  /// 20% in each step, ranging from 20% to 1000%. Requires `webview:allow-set-webview-zoom` permission
  ///
  /// - **Android / iOS**: Unsupported.
  #[must_use]
  pub fn zoom_hotkeys_enabled(mut self, enabled: bool) -> Self {
    self.zoom_hotkeys_enabled = enabled;
    self
  }
}

/// IPC handler.
pub type WebviewIpcHandler<T, R> = Box<dyn Fn(DetachedWebview<T, R>, Request<String>) + Send>;
Repository: tauri-apps/tauri
File: core/tauri/src/webview/scripts/zoom-hotkey.js (JavaScript)

Code before:
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

const OS_NAME = __TEMPLATE_os_name__

let zoomLevel = 1

const MAX_ZOOM_LEVEL = 10
const MIN_ZOOM_LEVEL = 0.2

window.addEventListener('keydown', (event) => {
  if (event.defaultPrevented) {
    return
  }
  if (OS_NAME === 'macos' ? event.metaKey : event.ctrlKey) {
    if (event.key === '-') {
      zoomLevel -= 0.2
    } else if (event.key === '=') {
      zoomLevel += 0.2
    } else {
      return
    }
    zoomLevel = Math.min(Math.max(zoomLevel, MIN_ZOOM_LEVEL), MAX_ZOOM_LEVEL)
    window.__TAURI_INTERNALS__.invoke('plugin:webview|set_webview_zoom', {
      value: zoomLevel
    })
  }
})


Review comment (suggestion):
we should also support `ctrl+0` to reset it to `1`

Code after:
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

const OS_NAME = __TEMPLATE_os_name__

let zoomLevel = 1

const MAX_ZOOM_LEVEL = 10
const MIN_ZOOM_LEVEL = 0.2

window.addEventListener('keydown', (event) => {
  if (OS_NAME === 'macos' ? event.metaKey : event.ctrlKey) {
    if (event.key === '-') {
      zoomLevel -= 0.2
    } else if (event.key === '=') {
      zoomLevel += 0.2
    } else if (event.key === '0') {
      zoomLevel = 1
    } else {
      return
    }
    zoomLevel = Math.min(Math.max(zoomLevel, MIN_ZOOM_LEVEL), MAX_ZOOM_LEVEL)
    window.__TAURI_INTERNALS__.invoke('plugin:webview|set_webview_zoom', {
      value: zoomLevel
    })
  }
})
Repository: tauri-apps/tauri
File: core/tauri/src/tray/mod.rs (Rust)

Code before:

  /// Disable or enable showing the tray menu on left click. **macOS only**.
  pub fn set_show_menu_on_left_click(&self, #[allow(unused)] enable: bool) -> crate::Result<()> {
    #[cfg(target_os = "macos")]
    run_item_main_thread!(self, |self_: Self| self_
      .inner
      .set_show_menu_on_left_click(enable))?;
    Ok(())
  }

  /// Get tray icon frame when available, otherwise `None`.
  pub fn rect(&self) -> crate::Result<Option<crate::Rect>> {
    run_item_main_thread!(self, |self_: Self| self_.inner.rect().map(
      |frame| {
        Rect {
          position: frame.position.into(),
          size: frame.size.into(),
        }
      }
    ))
  }
}

impl<R: Runtime> Resource for TrayIcon<R> {
  fn close(self: std::sync::Arc<Self>) {
    self.app_handle.remove_tray_by_id(&self.id);
  }
}


Review comment (suggestion):
```suggestion
  
  /// Get tray icon rect.
  ///
  /// ## Platform-specific:
  ///
  /// - **Linux**: Unsupported, always returns `None`.
  pub fn rect(&self) -> crate::Result<Option<crate::Rect>> {
    run_item_main_thread!(self, |self_: Self| self_.inner.rect().map(
      |rect| {
        Rect {
          position: rect.position.into(),
          size: rect.size.into(),
        }
      }
    ))
  }
```

Code after:
  }

  /// Disable or enable showing the tray menu on left click. **macOS only**.
  pub fn set_show_menu_on_left_click(&self, #[allow(unused)] enable: bool) -> crate::Result<()> {
    #[cfg(target_os = "macos")]
    run_item_main_thread!(self, |self_: Self| self_
      .inner
      .set_show_menu_on_left_click(enable))?;
    Ok(())
  }

  /// Get tray icon rect.
  ///
  /// ## Platform-specific:
  ///
  /// - **Linux**: Unsupported, always returns `None`.
  pub fn rect(&self) -> crate::Result<Option<crate::Rect>> {
    run_item_main_thread!(self, |self_: Self| self_.inner.rect().map(|rect| {
      Rect {
        position: rect.position.into(),
        size: rect.size.into(),
      }
    }))
  }
}

impl<R: Runtime> Resource for TrayIcon<R> {
  fn close(self: std::sync::Arc<Self>) {
    self.app_handle.remove_tray_by_id(&self.id);
  }
}
Repository: tauri-apps/tauri
File: core/tauri-runtime-wry/src/lib.rs (Rust)

Code before:
    )?;

    let dispatcher = WryWebviewDispatcher {
      window_id: window_id_wrapper,
      webview_id,
      context: self.clone(),
    };

    Ok(DetachedWebview { label, dispatcher })
  }
}

#[cfg(feature = "tracing")]
#[derive(Debug, Clone, Default)]
pub struct ActiveTraceSpanStore(Rc<RefCell<Vec<ActiveTracingSpan>>>);

#[cfg(feature = "tracing")]
impl ActiveTraceSpanStore {
  pub fn remove_window_draw(&self) {
    let mut store = self.0.borrow_mut();
    while let Some(index) = store
      .iter()
      .position(|t| matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ }))
    {
      store.remove(index);
    }
  }
}

#[cfg(feature = "tracing")]
#[derive(Debug)]
pub enum ActiveTracingSpan {
  WindowDraw {
    id: TaoWindowId,
    span: tracing::span::EnteredSpan,
  },
}

#[derive(Debug)]
pub struct WindowsStore(RefCell<BTreeMap<WindowId, WindowWrapper>>);

// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for WindowsStore {}

// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Sync for WindowsStore {}

#[derive(Debug, Clone)]
pub struct DispatcherMainThreadContext<T: UserEvent> {

Review comment (suggestion):
should probably use `store.retain(|t| !matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ }))` for more efficiency 

Code after:
    )?;

    let dispatcher = WryWebviewDispatcher {
      window_id: window_id_wrapper,
      webview_id,
      context: self.clone(),
    };

    Ok(DetachedWebview { label, dispatcher })
  }
}

#[cfg(feature = "tracing")]
#[derive(Debug, Clone, Default)]
pub struct ActiveTraceSpanStore(Rc<RefCell<Vec<ActiveTracingSpan>>>);

#[cfg(feature = "tracing")]
impl ActiveTraceSpanStore {
  pub fn remove_window_draw(&self) {
    self
      .0
      .borrow_mut()
      .retain(|t| !matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ }));
  }
}

#[cfg(feature = "tracing")]
#[derive(Debug)]
pub enum ActiveTracingSpan {
  WindowDraw {
    id: TaoWindowId,
    span: tracing::span::EnteredSpan,
  },
}

#[derive(Debug)]
pub struct WindowsStore(RefCell<BTreeMap<WindowId, WindowWrapper>>);

// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for WindowsStore {}

// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Sync for WindowsStore {}

#[derive(Debug, Clone)]
pub struct DispatcherMainThreadContext<T: UserEvent> {
  pub window_target: EventLoopWindowTarget<Message<T>>,
  pub web_context: WebContextStore,
  // changing this to an Rc will cause frequent app crashes.
Repository: tauri-apps/tauri
File: core/tauri-runtime-wry/src/lib.rs (Rust)

Code before:
      window_id,
      context: self.clone(),
    };
    Ok(DetachedWindow {
      label,
      dispatcher,
      menu_ids,
      js_event_listeners,
    })
  }
}

#[cfg(feature = "tracing")]
#[derive(Debug, Clone, Default)]
pub struct ActiveTraceSpanStore(Rc<RefCell<Vec<ActiveTracingSpan>>>);

#[cfg(feature = "tracing")]
impl ActiveTraceSpanStore {
  pub fn remove_window_draw(&self) {
    let mut store = self.0.borrow_mut();
    while let Some(index) = store
      .iter()
      .position(|t| matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ }))
    {
      store.remove(index);
    }
  }
}

#[cfg(feature = "tracing")]
#[derive(Debug)]
pub enum ActiveTracingSpan {
  WindowDraw {
    id: WindowId,
    span: tracing::span::EnteredSpan,
  },
}

#[derive(Debug)]
pub struct WindowsStore(RefCell<BTreeMap<WebviewId, WindowWrapper>>);

// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for WindowsStore {}

// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Sync for WindowsStore {}

#[derive(Debug, Clone)]
pub struct DispatcherMainThreadContext<T: UserEvent> {

Review comment (suggestion):
should probably use `store.retain(|t| !matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ }))` for more efficiency 

Code after:
      window_id,
      context: self.clone(),
    };
    Ok(DetachedWindow {
      label,
      dispatcher,
      menu_ids,
      js_event_listeners,
    })
  }
}

#[cfg(feature = "tracing")]
#[derive(Debug, Clone, Default)]
pub struct ActiveTraceSpanStore(Rc<RefCell<Vec<ActiveTracingSpan>>>);

#[cfg(feature = "tracing")]
impl ActiveTraceSpanStore {
  pub fn remove_window_draw(&self) {
    self
      .0
      .borrow_mut()
      .retain(|t| !matches!(t, ActiveTracingSpan::WindowDraw { id: _, span: _ }));
  }
}

#[cfg(feature = "tracing")]
#[derive(Debug)]
pub enum ActiveTracingSpan {
  WindowDraw {
    id: WindowId,
    span: tracing::span::EnteredSpan,
  },
}

#[derive(Debug)]
pub struct WindowsStore(RefCell<BTreeMap<WebviewId, WindowWrapper>>);

// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for WindowsStore {}

// SAFETY: we ensure this type is only used on the main thread.
#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Sync for WindowsStore {}

#[derive(Debug, Clone)]
pub struct DispatcherMainThreadContext<T: UserEvent> {
  pub window_target: EventLoopWindowTarget<Message<T>>,
  pub web_context: WebContextStore,
  #[cfg(all(desktop, feature = "global-shortcut"))]