ronantakizawa/codereview-bench huggingface dataset:
Repository: tauri-apps/tauri
File: core/tauri/scripts/core.js (JavaScript)

Code before:
        }
      }
    )
  }

  if (
    document.readyState === 'complete' ||
    document.readyState === 'interactive'
  ) {
    __openLinks()
  } else {
    window.addEventListener(
      'DOMContentLoaded',
      function () {
        __openLinks()
      },
      true
    )
  }

  //-----------------------//
  // data-tauri-drag-region
  //
  // drag on mousedown and maximize on double click on Windows and Linux
  // while macOS macos maximization should be on mouseup and if the mouse
  // moves after the double click, it should be cancelled
  //-----------------------//
  const TAURI_DRAG_REGION_ATTR = 'data-tauri-drag-region';
  let x = 0, y = 0;
  document.addEventListener('mousedown', (e) => {
    if (
      // element has the magic data attribute
      e.target.hasAttribute(TAURI_DRAG_REGION_ATTR) &&
      // and was left mouse button
      e.button === 0 &&
      // and was normal click to drag or double click to maximize
      (e.detail === 1 || e.detail === 2)
      ) {

      // macOS maximization happens on `mouseup`,
      // so we save needed state and early return
      if (osName === 'macos' && e.detail == 2) {
        x = e.clientX
        y = e.clientY
        return
      }

      // prevents text cursor
      e.preventDefault()

      // fix #2549: double click on drag region edge causes content to maximize without window sizing change

Review comment (suggestion):
```suggestion
  // moves after the double click, it should be cancelled (see https://github.com/tauri-apps/tauri/issues/8306)
```

Code after:
        }
      }
    )
  }

  if (
    document.readyState === 'complete' ||
    document.readyState === 'interactive'
  ) {
    __openLinks()
  } else {
    window.addEventListener(
      'DOMContentLoaded',
      function () {
        __openLinks()
      },
      true
    )
  }

  //-----------------------//
  // data-tauri-drag-region
  //
  // drag on mousedown and maximize on double click on Windows and Linux
  // while macOS macos maximization should be on mouseup and if the mouse
  // moves after the double click, it should be cancelled (see https://github.com/tauri-apps/tauri/issues/8306)
  //-----------------------//
  const TAURI_DRAG_REGION_ATTR = 'data-tauri-drag-region';
  let x = 0, y = 0;
  document.addEventListener('mousedown', (e) => {
    if (
      // element has the magic data attribute
      e.target.hasAttribute(TAURI_DRAG_REGION_ATTR) &&
      // and was left mouse button
      e.button === 0 &&
      // and was normal click to drag or double click to maximize
      (e.detail === 1 || e.detail === 2)
      ) {

      // macOS maximization happens on `mouseup`,
      // so we save needed state and early return
      if (osName === 'macos' && e.detail == 2) {
        x = e.clientX
        y = e.clientY
        return
      }

      // prevents text cursor
      e.preventDefault()

      // fix #2549: double click on drag region edge causes content to maximize without window sizing change
Repository: tauri-apps/tauri
File: tooling/cli/src/interface/rust.rs (Rust)

Code before:
    );

    if options.no_watch {
      runner(options)?;
      Ok(())
    } else {
      let config = options.config.clone();
      let run = Arc::new(|_rust: &mut Rust| runner(options.clone()));
      self.run_dev_watcher(config, run)
    }
  }

  fn env(&self) -> HashMap<&str, String> {
    let mut env = HashMap::new();
    env.insert(
      "TAURI_ENV_TARGET_TRIPLE",
      self.app_settings.target_triple.clone(),
    );

    let target_triple = self.app_settings.target_triple.clone();
    let target_components: Vec<&str> = target_triple.split('-').collect();

    let (arch, _, host) = match target_components.as_slice() {
      [arch, _, host] => (arch, _, host),
      _ => {
        eprintln!("Invalid Target Tuple: {}", target_triple);
        return env;
      }
    };
    env.insert(
      "TAURI_ENV_ARCH",
      match arch {
        // keeps compatibility with old `std::env::consts::ARCH` implementation
        "i686" | "i586" => "x86".into(),
        a => a.into(),
      },
    );
    env.insert(
      "TAURI_ENV_PLATFORM",
      match host {
        // keeps compatibility with old `std::env::consts::OS` implementation
        "darwin" => "macos".into(),
        "ios-sim" => "ios".into(),
        "androideabi" => "android".into(),
        h => h.into(),
      },
    );

    env.insert(
      "TAURI_ENV_FAMILY",
      match host {

Review comment (suggestion):
```suggestion
        log::warn!("Invalid target triple: {}", target_triple);
```

Code after:
    );

    if options.no_watch {
      runner(options)?;
      Ok(())
    } else {
      let config = options.config.clone();
      let run = Arc::new(|_rust: &mut Rust| runner(options.clone()));
      self.run_dev_watcher(config, run)
    }
  }

  fn env(&self) -> HashMap<&str, String> {
    let mut env = HashMap::new();
    env.insert(
      "TAURI_ENV_TARGET_TRIPLE",
      self.app_settings.target_triple.clone(),
    );

    let target_triple = &self.app_settings.target_triple;
    let target_components: Vec<&str> = target_triple.split('-').collect();
    let (arch, host) = match target_components.as_slice() {
      [arch, _, host] => (*arch, *host),
      _ => {
        log::warn!("Invalid target triple: {}", target_triple);
        return env;
      }
    };

    env.insert(
      "TAURI_ENV_ARCH",
      match arch {
        // keeps compatibility with old `std::env::consts::ARCH` implementation
        "i686" | "i586" => "x86".into(),
        a => a.into(),
      },
    );
    env.insert(
      "TAURI_ENV_PLATFORM",
      match host {
        // keeps compatibility with old `std::env::consts::OS` implementation
        "darwin" => "macos".into(),
        "ios-sim" => "ios".into(),
        "androideabi" => "android".into(),
        h => h.into(),
      },
    );

    env.insert(
      "TAURI_ENV_FAMILY",
      match host {
Repository: tauri-apps/tauri
File: tooling/cli/src/interface/rust.rs (Rust)

Code before:
    dev_options(
      true,
      &mut options.args,
      &mut run_args,
      &mut options.features,
      &self.app_settings,
    );

    if options.no_watch {
      runner(options)?;
      Ok(())
    } else {
      let config = options.config.clone();
      let run = Arc::new(|_rust: &mut Rust| runner(options.clone()));
      self.run_dev_watcher(config, run)
    }
  }

  fn env(&self) -> HashMap<&str, String> {
    let mut env = HashMap::new();
    env.insert(
      "TAURI_ENV_TARGET_TRIPLE",
      self.app_settings.target_triple.clone(),
    );

    let target_triple = self.app_settings.target_triple.clone();
    let target_components: Vec<&str> = target_triple.split('-').collect();

    let (arch, _, host) = match target_components.as_slice() {
      [arch, _, host] => (arch, _, host),
      _ => {
        eprintln!("Invalid Target Tuple: {}", target_triple);
        return env;
      }
    };
    env.insert(
      "TAURI_ENV_ARCH",
      match arch {
        // keeps compatibility with old `std::env::consts::ARCH` implementation
        "i686" | "i586" => "x86".into(),
        a => a.into(),
      },
    );
    env.insert(
      "TAURI_ENV_PLATFORM",
      match host {
        // keeps compatibility with old `std::env::consts::OS` implementation
        "darwin" => "macos".into(),
        "ios-sim" => "ios".into(),
        "androideabi" => "android".into(),
        h => h.into(),

Review comment (suggestion):
I think you shouldn't need to clone here
```suggestion
    let target_triple = self.app_settings.target_triple;
```

Code after:
    dev_options(
      true,
      &mut options.args,
      &mut run_args,
      &mut options.features,
      &self.app_settings,
    );

    if options.no_watch {
      runner(options)?;
      Ok(())
    } else {
      let config = options.config.clone();
      let run = Arc::new(|_rust: &mut Rust| runner(options.clone()));
      self.run_dev_watcher(config, run)
    }
  }

  fn env(&self) -> HashMap<&str, String> {
    let mut env = HashMap::new();
    env.insert(
      "TAURI_ENV_TARGET_TRIPLE",
      self.app_settings.target_triple.clone(),
    );

    let target_triple = &self.app_settings.target_triple;
    let target_components: Vec<&str> = target_triple.split('-').collect();
    let (arch, host) = match target_components.as_slice() {
      [arch, _, host] => (*arch, *host),
      _ => {
        log::warn!("Invalid target triple: {}", target_triple);
        return env;
      }
    };

    env.insert(
      "TAURI_ENV_ARCH",
      match arch {
        // keeps compatibility with old `std::env::consts::ARCH` implementation
        "i686" | "i586" => "x86".into(),
        a => a.into(),
      },
    );
    env.insert(
      "TAURI_ENV_PLATFORM",
      match host {
        // keeps compatibility with old `std::env::consts::OS` implementation
        "darwin" => "macos".into(),
        "ios-sim" => "ios".into(),
        "androideabi" => "android".into(),
        h => h.into(),
Repository: tauri-apps/tauri
File: core/tauri/src/window/mod.rs (Rust)

Code before:
  }

  /// Enables clipboard access for the page rendered on **Linux** and **Windows**.
  ///
  /// **macOS** doesn't provide such method and is always enabled by default,
  /// but you still need to add menu item accelerators to use shortcuts.
  #[must_use]
  pub fn enable_clipboard_access(mut self) -> Self {
    self.webview_attributes.clipboard = true;
    self
  }

  /// Enable or disable incognito mode for the WebView..
  ///
  ///  ## Platform-specific:
  ///
  ///  **Android**: Unsupported.
  #[must_use]
  pub fn incognito(mut self, incognito: bool) -> Self {
    self.webview_attributes.incognito = incognito;
    self
  }

  /// Enable proxy for the WebView
  #[must_use]
  pub fn proxy_config(mut self, proxy: &str) -> Self {
    self.webview_attributes.proxy = Some(proxy.to_string());
    self
  }
}

/// Key for a JS event listener.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct JsEventListenerKey {
  /// The associated window label.
  pub window_label: Option<String>,
  /// The event name.
  pub event: String,
}

/// The IPC invoke request.
#[derive(Debug)]
pub struct InvokeRequest {
  /// The invoke command.
  pub cmd: String,
  /// The success callback.
  pub callback: CallbackFn,
  /// The error callback.
  pub error: CallbackFn,
  /// The body of the request.
  pub body: InvokeBody,

Review comment (suggestion):
Let's rename this and accept a `Url` instead of `&str`
```suggestion
  pub fn proxy_url(mut self, url: Url) -> Self {
```

Code after:
impl<R: Runtime> ManagerBase<R> for Window<R> {
  fn manager(&self) -> &AppManager<R> {
    &self.manager
  }

  fn manager_owned(&self) -> Arc<AppManager<R>> {
    self.manager.clone()
  }

  fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
    RuntimeOrDispatch::Dispatch(self.window.dispatcher.clone())
  }

  fn managed_app_handle(&self) -> &AppHandle<R> {
    &self.app_handle
  }
}

impl<'de, R: Runtime> CommandArg<'de, R> for Window<R> {
  /// Grabs the [`Window`] from the [`CommandItem`]. This will never fail.
  fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
    Ok(command.message.webview().window().clone())
  }
}

/// Base window functions.
impl<R: Runtime> Window<R> {
  /// Create a new window that is attached to the manager.
  pub(crate) fn new(
    manager: Arc<AppManager<R>>,
    window: DetachedWindow<EventLoopMessage, R>,
    app_handle: AppHandle<R>,
    #[cfg(desktop)] menu: Option<WindowMenu<R>>,
    webview_window: bool,
  ) -> Self {
    Self {
      window,
      manager,
      app_handle,
      #[cfg(desktop)]
      menu: Arc::new(std::sync::Mutex::new(menu)),
      webview_window,
    }
  }

  /// Initializes a window builder with the given window label.
  ///
  /// Data URLs are only supported with the `webview-data-url` feature flag.
  #[cfg(feature = "unstable")]
  #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
  pub fn builder<M: Manager<R>, L: Into<String>>(manager: &M, label: L) -> WindowBuilder<'_, R, M> {
Repository: tauri-apps/tauri
File: core/tauri-runtime/src/webview.rs (Rust)

Code before:
  }

  /// Sets additional browser arguments. **Windows Only**
  #[must_use]
  pub fn additional_browser_args(mut self, additional_args: &str) -> Self {
    self.additional_browser_args = Some(additional_args.to_string());
    self
  }

  /// Sets window effects
  #[must_use]
  pub fn window_effects(mut self, effects: WindowEffectsConfig) -> Self {
    self.window_effects = Some(effects);
    self
  }

  /// Enable or disable incognito mode for the WebView.
  #[must_use]
  pub fn incognito(mut self, incognito: bool) -> Self {
    self.incognito = incognito;
    self
  }

  /// Enable proxy for the WebView
  #[must_use]
  pub fn proxy_config(mut self, proxy: &str) -> Self {
    self.proxy = Some(proxy.to_string());
    self
  }
}

/// Do **NOT** implement this trait except for use in a custom [`Runtime`](crate::Runtime).
///
/// This trait is separate from [`WindowBuilder`] to prevent "accidental" implementation.
pub trait WindowBuilderBase: fmt::Debug + Clone + Sized {}

/// A builder for all attributes related to a single webview.
///
/// This trait is only meant to be implemented by a custom [`Runtime`](crate::Runtime)
/// and not by applications.
pub trait WindowBuilder: WindowBuilderBase {
  /// Initializes a new window attributes builder.
  fn new() -> Self;

  /// Initializes a new webview builder from a [`WindowConfig`]
  fn with_config(config: WindowConfig) -> Self;

  /// Show window in the center of the screen.
  #[must_use]
  fn center(self) -> Self;


Review comment (suggestion):
same
```suggestion
  pub fn proxy_url(mut self, proxy: Url) -> Self {
```

Code after:
        uri_scheme_protocols: Default::default(),
        label,
        ipc_handler: None,
        navigation_handler: None,
        url: "tauri://localhost".to_string(),
        #[cfg(target_os = "android")]
        on_webview_created: None,
        web_resource_request_handler: None,
        on_page_load_handler: None,
        download_handler: None,
      })
    }
  }

  pub fn register_uri_scheme_protocol<
    N: Into<String>,
    H: Fn(http::Request<Vec<u8>>, Box<dyn FnOnce(http::Response<Cow<'static, [u8]>>) + Send>)
      + Send
      + Sync
      + 'static,
  >(
    &mut self,
    uri_scheme: N,
    protocol: H,
  ) {
    let uri_scheme = uri_scheme.into();
    self
      .uri_scheme_protocols
      .insert(uri_scheme, Box::new(protocol));
  }

  #[cfg(target_os = "android")]
  pub fn on_webview_created<
    F: Fn(CreationContext<'_, '_>) -> Result<(), jni::errors::Error> + Send + 'static,
  >(
    mut self,
    f: F,
  ) -> Self {
    self.on_webview_created.replace(Box::new(f));
    self
  }
}

/// A webview that is not yet managed by Tauri.
#[derive(Debug)]
pub struct DetachedWebview<T: UserEvent, R: Runtime<T>> {
  /// Name of the window
  pub label: String,

  /// The [`crate::WebviewDispatch`] associated with the window.
  pub dispatcher: R::WebviewDispatcher,
Repository: tauri-apps/tauri
File: core/tauri/src/window/mod.rs (Rust)

Code before:
  }
}

impl<R: Runtime> Clone for Window<R> {
  fn clone(&self) -> Self {
    Self {
      window: self.window.clone(),
      manager: self.manager.clone(),
      app_handle: self.app_handle.clone(),
      js_event_listeners: self.js_event_listeners.clone(),
      #[cfg(desktop)]
      menu: self.menu.clone(),
    }
  }
}

impl<R: Runtime> Hash for Window<R> {
  /// Only use the [`Window`]'s label to represent its hash.
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.window.label.hash(state)
  }
}

impl<R: Runtime> Eq for Window<R> {}
impl<R: Runtime> PartialEq for Window<R> {
  /// Only use the [`Window`]'s label to compare equality.
  fn eq(&self, other: &Self) -> bool {
    self.window.label.eq(&other.window.label)
  }
}

impl<R: Runtime> Manager<R> for Window<R> {
  #[cfg_attr(
    feature = "tracing",
    tracing::instrument("window::emit", skip(self, payload))
  )]
  fn emit<S: Serialize + Clone>(&self, event: &str, payload: S) -> crate::Result<()> {
    self.manager().emit(event, Some(self.label()), payload)?;
    Ok(())
  }

  fn emit_to<S: Serialize + Clone>(
    &self,
    label: &str,
    event: &str,
    payload: S,
  ) -> crate::Result<()> {
    self
      .manager()
      .emit_filter(event, Some(self.label()), payload, |w| label == w.label())
  }

Review comment (suggestion):
```suggestion
  /// Set a proxy URL for the WebView for all network requests.
```

Code after:
      .window
      .dispatcher
      .on_window_event(move |event| f(&event.clone().into()));
  }
}

/// Menu APIs
#[cfg(desktop)]
impl<R: Runtime> Window<R> {
  /// Registers a global menu event listener.
  ///
  /// Note that this handler is called for any menu event,
  /// whether it is coming from this window, another window or from the tray icon menu.
  ///
  /// Also note that this handler will not be called if
  /// the window used to register it was closed.
  ///
  /// # Examples
  #[cfg_attr(
    feature = "unstable",
    doc = r####"
```
use tauri::menu::{Menu, Submenu, MenuItem};
tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle();
    let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
    let menu = Menu::with_items(handle, &[
      &Submenu::with_items(handle, "File", true, &[
        &save_menu_item,
      ])?,
    ])?;
    let window = tauri::window::WindowBuilder::new(app, "editor")
      .menu(menu)
      .build()
      .unwrap();

    window.on_menu_event(move |window, event| {
      if event.id == save_menu_item.id() {
          // save menu item
      }
    });

    Ok(())
  });
```
  "####
  )]
  pub fn on_menu_event<F: Fn(&Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
    &self,
    f: F,
Repository: tauri-apps/tauri
File: core/tauri-runtime/src/webview.rs (Rust)

Code before:

  /// Sets additional browser arguments. **Windows Only**
  #[must_use]
  pub fn additional_browser_args(mut self, additional_args: &str) -> Self {
    self.additional_browser_args = Some(additional_args.to_string());
    self
  }

  /// Sets window effects
  #[must_use]
  pub fn window_effects(mut self, effects: WindowEffectsConfig) -> Self {
    self.window_effects = Some(effects);
    self
  }

  /// Enable or disable incognito mode for the WebView.
  #[must_use]
  pub fn incognito(mut self, incognito: bool) -> Self {
    self.incognito = incognito;
    self
  }

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

/// Do **NOT** implement this trait except for use in a custom [`Runtime`](crate::Runtime).
///
/// This trait is separate from [`WindowBuilder`] to prevent "accidental" implementation.
pub trait WindowBuilderBase: fmt::Debug + Clone + Sized {}

/// A builder for all attributes related to a single webview.
///
/// This trait is only meant to be implemented by a custom [`Runtime`](crate::Runtime)
/// and not by applications.
pub trait WindowBuilder: WindowBuilderBase {
  /// Initializes a new window attributes builder.
  fn new() -> Self;

  /// Initializes a new webview builder from a [`WindowConfig`]
  fn with_config(config: WindowConfig) -> Self;

  /// Show window in the center of the screen.
  #[must_use]
  fn center(self) -> Self;

  /// The initial position of the window's.

Review comment (suggestion):
```suggestion
    self.proxy_url = Some(url);
```

Code after:
        ipc_handler: None,
        navigation_handler: None,
        url: "tauri://localhost".to_string(),
        #[cfg(target_os = "android")]
        on_webview_created: None,
        web_resource_request_handler: None,
        on_page_load_handler: None,
        download_handler: None,
      })
    }
  }

  pub fn register_uri_scheme_protocol<
    N: Into<String>,
    H: Fn(http::Request<Vec<u8>>, Box<dyn FnOnce(http::Response<Cow<'static, [u8]>>) + Send>)
      + Send
      + Sync
      + 'static,
  >(
    &mut self,
    uri_scheme: N,
    protocol: H,
  ) {
    let uri_scheme = uri_scheme.into();
    self
      .uri_scheme_protocols
      .insert(uri_scheme, Box::new(protocol));
  }

  #[cfg(target_os = "android")]
  pub fn on_webview_created<
    F: Fn(CreationContext<'_, '_>) -> Result<(), jni::errors::Error> + Send + 'static,
  >(
    mut self,
    f: F,
  ) -> Self {
    self.on_webview_created.replace(Box::new(f));
    self
  }
}

/// A webview that is not yet managed by Tauri.
#[derive(Debug)]
pub struct DetachedWebview<T: UserEvent, R: Runtime<T>> {
  /// Name of the window
  pub label: String,

  /// The [`crate::WebviewDispatch`] associated with the window.
  pub dispatcher: R::WebviewDispatcher,
}
Repository: tauri-apps/tauri
File: core/tauri/src/window/mod.rs (Rust)

Code before:

  /// Enables clipboard access for the page rendered on **Linux** and **Windows**.
  ///
  /// **macOS** doesn't provide such method and is always enabled by default,
  /// but you still need to add menu item accelerators to use shortcuts.
  #[must_use]
  pub fn enable_clipboard_access(mut self) -> Self {
    self.webview_attributes.clipboard = true;
    self
  }

  /// Enable or disable incognito mode for the WebView..
  ///
  ///  ## Platform-specific:
  ///
  ///  **Android**: Unsupported.
  #[must_use]
  pub fn incognito(mut self, incognito: bool) -> Self {
    self.webview_attributes.incognito = incognito;
    self
  }

  /// Set a proxy URL for the WebView for all network requests.
  #[must_use]
  pub fn proxy_url(mut self, url: Url) -> Self {
    self.webview_attributes.proxy = Some(url);
    self
  }
}

/// Key for a JS event listener.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct JsEventListenerKey {
  /// The associated window label.
  pub window_label: Option<String>,
  /// The event name.
  pub event: String,
}

/// The IPC invoke request.
#[derive(Debug)]
pub struct InvokeRequest {
  /// The invoke command.
  pub cmd: String,
  /// The success callback.
  pub callback: CallbackFn,
  /// The error callback.
  pub error: CallbackFn,
  /// The body of the request.
  pub body: InvokeBody,
  /// The request headers.

Review comment (suggestion):
```suggestion
    self.webview_attributes.proxy_url = Some(url);
```

Code after:
  }
}

/// Menu APIs
#[cfg(desktop)]
impl<R: Runtime> Window<R> {
  /// Registers a global menu event listener.
  ///
  /// Note that this handler is called for any menu event,
  /// whether it is coming from this window, another window or from the tray icon menu.
  ///
  /// Also note that this handler will not be called if
  /// the window used to register it was closed.
  ///
  /// # Examples
  #[cfg_attr(
    feature = "unstable",
    doc = r####"
```
use tauri::menu::{Menu, Submenu, MenuItem};
tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle();
    let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
    let menu = Menu::with_items(handle, &[
      &Submenu::with_items(handle, "File", true, &[
        &save_menu_item,
      ])?,
    ])?;
    let window = tauri::window::WindowBuilder::new(app, "editor")
      .menu(menu)
      .build()
      .unwrap();

    window.on_menu_event(move |window, event| {
      if event.id == save_menu_item.id() {
          // save menu item
      }
    });

    Ok(())
  });
```
  "####
  )]
  pub fn on_menu_event<F: Fn(&Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
    &self,
    f: F,
  ) {
    self
      .manager