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

Code before:

  /// Gets the window's current visibility state.
  pub fn is_visible(&self) -> crate::Result<bool> {
    self.window.dispatcher.is_visible().map_err(Into::into)
  }

  /// Gets the window's current title.
  pub fn title(&self) -> crate::Result<String> {
    self.window.dispatcher.title().map_err(Into::into)
  }

  /// Returns the monitor on which the window currently resides.
  ///
  /// Returns None if current monitor can't be detected.
  pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
    self
      .window
      .dispatcher
      .current_monitor()
      .map(|m| m.map(Into::into))
      .map_err(Into::into)
  }

  /// Returns the monitor on which the provided point is.
  ///
  /// Returns None if monitor can't be detected.
  pub fn monitor_from_point(&self, x: f64, y: f64) -> crate::Result<Option<Monitor>> {
    self
      .window
      .dispatcher
      .monitor_from_point(x, y)
      .map(|m| m.map(Into::into))
      .map_err(Into::into)
  }

  /// Returns the primary monitor of the system.
  ///
  /// Returns None if it can't identify any monitor as a primary one.
  pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
    self
      .window
      .dispatcher
      .primary_monitor()
      .map(|m| m.map(Into::into))
      .map_err(Into::into)
  }

  /// Returns the list of all the monitors available on the system.
  pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
    self
      .window

Review comment (suggestion):
```suggestion
  /// Returns the monitor that contains the given point.
```

Code after:

  /// Gets the window's current visibility state.
  pub fn is_visible(&self) -> crate::Result<bool> {
    self.window.dispatcher.is_visible().map_err(Into::into)
  }

  /// Gets the window's current title.
  pub fn title(&self) -> crate::Result<String> {
    self.window.dispatcher.title().map_err(Into::into)
  }

  /// Returns the monitor on which the window currently resides.
  ///
  /// Returns None if current monitor can't be detected.
  pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
    self
      .window
      .dispatcher
      .current_monitor()
      .map(|m| m.map(Into::into))
      .map_err(Into::into)
  }

  /// Returns the monitor that contains the given point.
  pub fn monitor_from_point(&self, x: f64, y: f64) -> crate::Result<Option<Monitor>> {
    self
      .window
      .dispatcher
      .monitor_from_point(x, y)
      .map(|m| m.map(Into::into))
      .map_err(Into::into)
  }

  /// Returns the primary monitor of the system.
  ///
  /// Returns None if it can't identify any monitor as a primary one.
  pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
    self
      .window
      .dispatcher
      .primary_monitor()
      .map(|m| m.map(Into::into))
      .map_err(Into::into)
  }

  /// Returns the list of all the monitors available on the system.
  pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
    self
      .window
      .dispatcher
      .available_monitors()
Repository: tauri-apps/tauri
File: tooling/api/src/window.ts (TypeScript)

Code before:
async function currentMonitor(): Promise<Monitor | null> {
  return invoke<Monitor | null>('plugin:window|current_monitor').then(
    mapMonitor
  )
}

/**
 * Returns the primary monitor of the system.
 * Returns `null` if it can't identify any monitor as a primary one.
 * @example
 * ```typescript
 * import { primaryMonitor } from '@tauri-apps/api/window';
 * const monitor = primaryMonitor();
 * ```
 *
 * @since 1.0.0
 */
async function primaryMonitor(): Promise<Monitor | null> {
  return invoke<Monitor | null>('plugin:window|primary_monitor').then(
    mapMonitor
  )
}

/**
 * Returns the monitor on which the given point currently resides.
 * Returns `null` if current monitor can't be detected.
 * @example
 * ```typescript
 * import { monitorFromPoint } from '@tauri-apps/api/window';
 * const monitor = monitorFromPoint();
 * ```
 *
 * @since 1.0.0
 */
async function monitorFromPoint(x: number, y: number): Promise<Monitor | null> {
  return invoke<Monitor | null>('plugin:window|monitor_from_point', {x, y}).then(
    mapMonitor
  )
}

/**
 * Returns the list of all the monitors available on the system.
 * @example
 * ```typescript
 * import { availableMonitors } from '@tauri-apps/api/window';
 * const monitors = availableMonitors();
 * ```
 *
 * @since 1.0.0
 */
async function availableMonitors(): Promise<Monitor[]> {

Review comment (suggestion):
```suggestion
  * Returns the monitor that contains the given point. Returns `null` if can't find any.
```

Code after:
async function currentMonitor(): Promise<Monitor | null> {
  return invoke<Monitor | null>('plugin:window|current_monitor').then(
    mapMonitor
  )
}

/**
 * Returns the primary monitor of the system.
 * Returns `null` if it can't identify any monitor as a primary one.
 * @example
 * ```typescript
 * import { primaryMonitor } from '@tauri-apps/api/window';
 * const monitor = primaryMonitor();
 * ```
 *
 * @since 1.0.0
 */
async function primaryMonitor(): Promise<Monitor | null> {
  return invoke<Monitor | null>('plugin:window|primary_monitor').then(
    mapMonitor
  )
}

/**
 * Returns the monitor that contains the given point. Returns `null` if can't find any.
 * @example
 * ```typescript
 * import { monitorFromPoint } from '@tauri-apps/api/window';
 * const monitor = monitorFromPoint();
 * ```
 *
 * @since 1.0.0
 */
async function monitorFromPoint(x: number, y: number): Promise<Monitor | null> {
  return invoke<Monitor | null>('plugin:window|monitor_from_point', {
    x,
    y
  }).then(mapMonitor)
}

/**
 * Returns the list of all the monitors available on the system.
 * @example
 * ```typescript
 * import { availableMonitors } from '@tauri-apps/api/window';
 * const monitors = availableMonitors();
 * ```
 *
 * @since 1.0.0
 */
async function availableMonitors(): Promise<Monitor[]> {
Repository: tauri-apps/tauri
File: core/tauri/src/window/mod.rs (Rust)

Code before:
      .map_err(Into::into)
  }

  /// Sets the taskbar progress state.
  ///
  /// ## Platform-specific
  ///
  /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window.
  /// - **Linux**: Only supported desktop environments with `libunity` (e.g. GNOME).
  /// - **iOS / Android:** Unsupported.
  pub fn set_progress_bar(&self, progress_state: ProgressBarState) -> crate::Result<()> {
    self
      .window
      .dispatcher
      .set_progress_bar(crate::runtime::ProgressBarState {
        status: progress_state.status,
        progress: progress_state.progress,
        desktop_filename: Some(format!("{}.desktop", self.package_info().crate_name)),
      })
      .map_err(Into::into)
  }
  /// Sets the title bar style. Available on macOS only.
  ///
  /// ## Platform-specific
  ///
  /// - **Linux / Windows / iOS / Android:** Unsupported.
  pub fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> crate::Result<()> {
    self
      .window
      .dispatcher
      .set_title_bar_style(style)
      .map_err(Into::into)
  }
}

/// Progress bar state.
#[cfg(desktop)]
#[cfg_attr(
  docsrs,
  doc(cfg(any(target_os = "macos", target_os = "linux", windows)))
)]
#[derive(serde::Deserialize)]
pub struct ProgressBarState {
  /// The progress bar status.
  pub status: Option<ProgressBarStatus>,
  /// The progress bar progress. This can be a value ranging from `0` to `100`
  pub progress: Option<u64>,
}

/// Event system APIs.
impl<R: Runtime> Window<R> {

Review comment (suggestion):
```suggestion
  /// Sets the title bar style. **macOS only**.
```

Code after:
      .map_err(Into::into)
  }

  /// Sets the taskbar progress state.
  ///
  /// ## Platform-specific
  ///
  /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window.
  /// - **Linux**: Only supported desktop environments with `libunity` (e.g. GNOME).
  /// - **iOS / Android:** Unsupported.
  pub fn set_progress_bar(&self, progress_state: ProgressBarState) -> crate::Result<()> {
    self
      .window
      .dispatcher
      .set_progress_bar(crate::runtime::ProgressBarState {
        status: progress_state.status,
        progress: progress_state.progress,
        desktop_filename: Some(format!("{}.desktop", self.package_info().crate_name)),
      })
      .map_err(Into::into)
  }
  /// Sets the title bar style. **macOS only**.
  pub fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> crate::Result<()> {
    self
      .window
      .dispatcher
      .set_title_bar_style(style)
      .map_err(Into::into)
  }
}

/// Progress bar state.
#[cfg(desktop)]
#[cfg_attr(
  docsrs,
  doc(cfg(any(target_os = "macos", target_os = "linux", windows)))
)]
#[derive(serde::Deserialize)]
pub struct ProgressBarState {
  /// The progress bar status.
  pub status: Option<ProgressBarStatus>,
  /// The progress bar progress. This can be a value ranging from `0` to `100`
  pub progress: Option<u64>,
}

/// Event system APIs.
impl<R: Runtime> Window<R> {
  /// Listen to an event on this window.
  ///
  /// # Examples
  #[cfg_attr(
Repository: tauri-apps/tauri
File: tooling/api/src/window.ts (TypeScript)

Code before:
    })
  }

  /**
   * Sets whether the window should be visible on all workspaces or virtual desktops.
   *
   * ## Platform-specific
   *
   * - **Windows / iOS / Android:** Unsupported.
   *
   * @since 2.0.0
   */
  async setVisibleOnAllWorkspaces(visible: boolean): Promise<void> {
    return invoke('plugin:window|set_visible_on_all_workspaces', {
      label: this.label,
      value: visible
    })
  }

  /**
   * Sets the title bar style. Available on macOS only.
   *
   * ## Platform-specific
   *
   * - **Linux / Windows / iOS / Android:**: Unsupported.
   *
   * @since 2.0.0
   */
  async setTitleBarStyle(style: TitleBarStyle): Promise<void> {
    return invoke('plugin:window|set_title_bar_style', {
      label: this.label,
      value: style
    })
  }

  // Listeners

  /**
   * Listen to window resize.
   *
   * @example
   * ```typescript
   * import { getCurrent } from "@tauri-apps/api/window";
   * const unlisten = await getCurrent().onResized(({ payload: size }) => {
   *  console.log('Window resized', size);
   * });
   *
   * // you need to call unlisten if your handler goes out of scope e.g. the component is unmounted
   * unlisten();
   * ```
   *

Review comment (suggestion):
```suggestion
   * Sets the title bar style. **macOS only**.
   *
```

Code after:
    })
  }

  /**
   * Sets whether the window should be visible on all workspaces or virtual desktops.
   *
   * ## Platform-specific
   *
   * - **Windows / iOS / Android:** Unsupported.
   *
   * @since 2.0.0
   */
  async setVisibleOnAllWorkspaces(visible: boolean): Promise<void> {
    return invoke('plugin:window|set_visible_on_all_workspaces', {
      label: this.label,
      value: visible
    })
  }

  /**
   * Sets the title bar style. **macOS only**.
   *
   * @since 2.0.0
   */
  async setTitleBarStyle(style: TitleBarStyle): Promise<void> {
    return invoke('plugin:window|set_title_bar_style', {
      label: this.label,
      value: style
    })
  }

  // Listeners

  /**
   * Listen to window resize.
   *
   * @example
   * ```typescript
   * import { getCurrent } from "@tauri-apps/api/window";
   * const unlisten = await getCurrent().onResized(({ payload: size }) => {
   *  console.log('Window resized', size);
   * });
   *
   * // you need to call unlisten if your handler goes out of scope e.g. the component is unmounted
   * unlisten();
   * ```
   *
   * @returns A promise resolving to a function to unlisten to the event.
   * Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.
   */
  async onResized(handler: EventCallback<PhysicalSize>): Promise<UnlistenFn> {
Repository: tauri-apps/tauri
File: core/tauri/src/window/scripts/drag.js (JavaScript)

Code before:
      const cmd = e.detail === 2 ? 'internal_toggle_maximize' : 'start_dragging'
      window.__TAURI_INTERNALS__.invoke('plugin:window|' + cmd)
    }
  })
  // on macOS we maximze on mouseup instead, to match the system behavior where maximization can be canceled
  // if the mouse moves outside the data-tauri-drag-region
  if (osName === 'macos') {
    document.addEventListener('mouseup', (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 double click
        e.detail === 2 &&
        // and the cursor hasn't moved from initial mousedown
        e.clientX === x &&
        e.clientY === y
      ) {
        window.__TAURI_INTERNALS__.invoke(
          'plugin:window|internal_toggle_maximize'
        )
      }
    })
  }
  if ('adoptedStyleSheets' in document) {
    const sheet = new CSSStyleSheet()
    sheet.replaceSync('*[data-tauri-drag-region] { app-region: drag; }')
    document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]
  }
})()


Review comment (suggestion):
```suggestion
  if (osName === 'windows' && 'adoptedStyleSheets' in document) {
```

Code after:
      const cmd = e.detail === 2 ? 'internal_toggle_maximize' : 'start_dragging'
      window.__TAURI_INTERNALS__.invoke('plugin:window|' + cmd)
    }
  })
  // on macOS we maximze on mouseup instead, to match the system behavior where maximization can be canceled
  // if the mouse moves outside the data-tauri-drag-region
  if (osName === 'macos') {
    document.addEventListener('mouseup', (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 double click
        e.detail === 2 &&
        // and the cursor hasn't moved from initial mousedown
        e.clientX === x &&
        e.clientY === y
      ) {
        window.__TAURI_INTERNALS__.invoke(
          'plugin:window|internal_toggle_maximize'
        )
      }
    })
  }
  if (osName === 'windows' && 'adoptedStyleSheets' in document) {
    const sheet = new CSSStyleSheet()
    sheet.replaceSync('*[data-tauri-drag-region] { app-region: drag; }')
    document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]
  }
})()
Repository: tauri-apps/tauri
File: core/tauri/src/updater/core.rs (Rust)

Code before:

      powershell_cmd
        .args(["-NoProfile", "-WindowStyle", "Hidden"])
        .args([
          "Start-Process",
          "-Wait",
          "-FilePath",
          "$Env:SYSTEMROOT\\System32\\msiexec.exe",
          "-ArgumentList",
        ])
        .arg("/i,")
        .arg(&msi_path)
        .arg(format!(", {}, /promptrestart;", installer_args.join(", ")))
        .arg("Start-Process")
        .arg(current_executable);

      if !current_exe_args.is_empty() {
        powershell_cmd
          .arg("-ArgumentList")
          .arg(current_exe_args.join(", "));
      }

      let powershell_install_res = powershell_cmd.spawn();
      if powershell_install_res.is_err() {
        // fallback to running msiexec directly - relaunch won't be available
        installer_args_common.extend(config.tauri.updater.windows.install_mode.msiexec_args().iter().map(OsStr::new));
        installer_args_common.push(OsStr::new("/promptrestart"));
      } else {
        exit(0);
      }
    } else {
      continue;
    }
    let file = encode_wide(found_path.as_os_str());
    let parameters = encode_wide(installer_args_common.join(OsStr::new(" ")).as_os_str());

    let ret = unsafe {
      ShellExecuteW(
        HWND(0),
        w!("open"),
        PCWSTR(file.as_ptr()),
        PCWSTR(parameters.as_ptr()),
        PCWSTR::null(),
        std::mem::transmute(SW_SHOW),
      )
    };
    if ret.0 <= 32 {
      return Err(Error::Io(std::io::Error::last_os_error()));
    }
    exit(0);
  }

Review comment (suggestion):
same as above, can't use extend, order of arguments is important and `install_mode.msiexec_args()` should be first

Code after:
        .args(["-NoProfile", "-WindowStyle", "Hidden"])
        .args([
          "Start-Process",
          "-Wait",
          "-FilePath",
          "$Env:SYSTEMROOT\\System32\\msiexec.exe",
          "-ArgumentList",
        ])
        .arg("/i,")
        .arg(&msi_path)
        .arg(format!(
          ", {}, /promptrestart;",
          msi_installer_args.join(", ")
        ))
        .arg("Start-Process")
        .arg(current_executable);

      if !env.args.is_empty() {
        powershell_cmd.arg("-ArgumentList").arg(env.args.join(", "));
      }

      let powershell_install_res = powershell_cmd.spawn();
      if powershell_install_res.is_err() {
        installer_args_shellexecute = [
          config
            .tauri
            .updater
            .windows
            .install_mode
            .msiexec_args()
            .iter()
            .map(|a| a.to_string())
            .collect(),
          config.tauri.updater.windows.installer_args.clone(),
        ]
        .concat();
        installer_args_shellexecute.push("/promptrestart".to_string());
      } else {
        exit(0);
      }
    } else {
      continue;
    }

    let file = HSTRING::from(found_path.as_os_str());
    let parameters = HSTRING::from(installer_args_shellexecute.join(" "));
    let ret = unsafe {
      ShellExecuteW(
        HWND(0),
        w!("open"),
        &file,
Repository: tauri-apps/tauri
File: core/tauri/src/updater/core.rs (Rust)

Code before:
      } else {
        exit(0);
      }
    } else {
      continue;
    }
    let file = encode_wide(found_path.as_os_str());
    let parameters = encode_wide(
      installer_args_common
        .iter()
        .map(|&arg| arg.to_string_lossy().into_owned())
        .collect::<Vec<String>>()
        .join(" ")
        .as_str(),
    );

    let ret = unsafe {
      ShellExecuteW(
        HWND(0),
        w!("open"),
        PCWSTR(file.as_ptr()),
        PCWSTR(parameters.as_ptr()),
        PCWSTR::null(),
        SW_SHOW.0.try_into().unwrap(),
      )
    };
    if ret.0 <= 32 {
      return Err(Error::Io(std::io::Error::last_os_error()));
    }
    exit(0);
  }

  Ok(())
}

#[cfg(target_os = "windows")]
fn encode_wide(string: impl AsRef<OsStr>) -> Vec<u16> {
  use std::os::windows::ffi::OsStrExt;
  string
    .as_ref()
    .encode_wide()
    .chain(std::iter::once(0))
    .collect()
}

// MacOS
// ### Expected structure:
// ├── [AppName]_[version]_x64.app.tar.gz       # GZ generated by tauri-bundler
// │   └──[AppName].app                         # Main application
// │      └── Contents                          # Application contents...
// │          └── ...

Review comment (suggestion):
```suggestion
    let ret = unsafe {
      ShellExecuteW(
        HWND(0),
        w!("open"),
        &file,
        &parameters,
        PCWSTR::null(),
        SW_SHOW.0 as _,
      )
    };
```

Code after:

    let file = HSTRING::from(found_path.as_os_str());
    let parameters = HSTRING::from(installer_args_shellexecute.join(" "));
    let ret = unsafe {
      ShellExecuteW(
        HWND(0),
        w!("open"),
        &file,
        &parameters,
        PCWSTR::null(),
        SW_SHOW.0 as _,
      )
    };
    if ret.0 <= 32 {
      return Err(Error::Io(std::io::Error::last_os_error()));
    }

    exit(0);
  }

  Ok(())
}

// MacOS
// ### Expected structure:
// ├── [AppName]_[version]_x64.app.tar.gz       # GZ generated by tauri-bundler
// │   └──[AppName].app                         # Main application
// │      └── Contents                          # Application contents...
// │          └── ...
// └── ...
#[cfg(target_os = "macos")]
fn copy_files_and_run<R: Read + Seek>(archive_buffer: R, extract_path: &Path) -> Result {
  let mut extracted_files: Vec<PathBuf> = Vec::new();

  // extract the buffer to the tmp_dir
  // we extract our signed archive into our final directory without any temp file
  let mut extractor =
    Extract::from_cursor(archive_buffer, ArchiveFormat::Tar(Some(Compression::Gz)));
  // the first file in the tar.gz will always be
  // <app_name>/Contents
  let tmp_dir = tempfile::Builder::new()
    .prefix("tauri_current_app")
    .tempdir()?;

  // create backup of our current app
  Move::from_source(extract_path).to_dest(tmp_dir.path())?;

  // extract all the files
  extractor.with_files(|entry| {
    let path = entry.path()?;
    // skip the first folder (should be the app name)
Repository: tauri-apps/tauri
File: core/tauri/src/updater/core.rs (Rust)

Code before:
          .arg(current_exe_args.join(", "));
      }

      let powershell_install_res = powershell_cmd.spawn();
      if powershell_install_res.is_err() {
        // fallback to running msiexec directly - relaunch won't be available
        installer_args_common.splice(
          0..0,
          config
            .tauri
            .updater
            .windows
            .install_mode
            .msiexec_args()
            .iter()
            .map(OsStr::new),
        );
        installer_args_common.push(OsStr::new("/promptrestart"));
      } else {
        exit(0);
      }
    } else {
      continue;
    }
    let file = encode_wide(found_path.as_os_str());
    let parameters = encode_wide(
      installer_args_common
        .iter()
        .map(|&arg| arg.to_string_lossy().into_owned())
        .collect::<Vec<String>>()
        .join(" ")
        .as_str(),
    );

    let ret = unsafe {
      ShellExecuteW(
        HWND(0),
        w!("open"),
        PCWSTR(file.as_ptr()),
        PCWSTR(parameters.as_ptr()),
        PCWSTR::null(),
        SW_SHOW.0.try_into().unwrap(),
      )
    };
    if ret.0 <= 32 {
      return Err(Error::Io(std::io::Error::last_os_error()));
    }
    exit(0);
  }

  Ok(())

Review comment (suggestion):
```suggestion
    let file = HSTRING::from(found_path.as_os_str());
    let parameters = HSTRING::from(
```

Code after:
            .tauri
            .updater
            .windows
            .install_mode
            .msiexec_args()
            .iter()
            .map(|a| a.to_string())
            .collect(),
          config.tauri.updater.windows.installer_args.clone(),
        ]
        .concat();
        installer_args_shellexecute.push("/promptrestart".to_string());
      } else {
        exit(0);
      }
    } else {
      continue;
    }

    let file = HSTRING::from(found_path.as_os_str());
    let parameters = HSTRING::from(installer_args_shellexecute.join(" "));
    let ret = unsafe {
      ShellExecuteW(
        HWND(0),
        w!("open"),
        &file,
        &parameters,
        PCWSTR::null(),
        SW_SHOW.0 as _,
      )
    };
    if ret.0 <= 32 {
      return Err(Error::Io(std::io::Error::last_os_error()));
    }

    exit(0);
  }

  Ok(())
}

// MacOS
// ### Expected structure:
// ├── [AppName]_[version]_x64.app.tar.gz       # GZ generated by tauri-bundler
// │   └──[AppName].app                         # Main application
// │      └── Contents                          # Application contents...
// │          └── ...
// └── ...
#[cfg(target_os = "macos")]
fn copy_files_and_run<R: Read + Seek>(archive_buffer: R, extract_path: &Path) -> Result {
  let mut extracted_files: Vec<PathBuf> = Vec::new();