ronantakizawa/codereview-bench huggingface dataset:
Repository: tauri-apps/tauri
File: tooling/bundler/src/bundle/settings.rs (Rust)

Code before:
  }

  /// Returns the package's license.
  pub fn license(&self) -> Option<&str> {
    self.package.license.as_deref()
  }

  /// Returns the package's homepage URL, defaulting to "" if not defined.
  pub fn homepage_url(&self) -> &str {
    self.package.homepage.as_deref().unwrap_or("")
  }

  /// Returns the app's category.
  pub fn app_category(&self) -> Option<AppCategory> {
    self.bundle_settings.category
  }

  /// Return file associations.
  pub fn file_associations(&self) -> &Option<Vec<FileAssociation>> {
    &self.bundle_settings.file_associations
  }

  /// Return the list of deep link protocols to be registered for
  /// this bundle.
  pub fn deep_link_protocols(&self) -> &Option<Vec<DeepLinkProtocol>> {
    &self.bundle_settings.deep_link_protocols
  }

  /// Returns the app's short description.
  pub fn short_description(&self) -> &str {
    self
      .bundle_settings
      .short_description
      .as_ref()
      .unwrap_or(&self.package.description)
  }

  /// Returns the app's long description.
  pub fn long_description(&self) -> Option<&str> {
    self.bundle_settings.long_description.as_deref()
  }

  /// Returns the debian settings.
  pub fn deb(&self) -> &DebianSettings {
    &self.bundle_settings.deb
  }

  /// Returns the RPM settings.
  pub fn rpm(&self) -> &RpmSettings {
    &self.bundle_settings.rpm
  }

Review comment (suggestion):
Optional reference is better semantically than a reference to an option

```suggestion
  pub fn deep_link_protocols(&self) -> Option<&Vec<DeepLinkProtocol>> {
    self.bundle_settings.deep_link_protocols.as_ref()
```

Code after:
  }

  /// Returns the package's license.
  pub fn license(&self) -> Option<&str> {
    self.package.license.as_deref()
  }

  /// Returns the package's homepage URL, defaulting to "" if not defined.
  pub fn homepage_url(&self) -> &str {
    self.package.homepage.as_deref().unwrap_or("")
  }

  /// Returns the app's category.
  pub fn app_category(&self) -> Option<AppCategory> {
    self.bundle_settings.category
  }

  /// Return file associations.
  pub fn file_associations(&self) -> Option<&Vec<FileAssociation>> {
    self.bundle_settings.file_associations.as_ref()
  }

  /// Return the list of deep link protocols to be registered for
  /// this bundle.
  pub fn deep_link_protocols(&self) -> Option<&Vec<DeepLinkProtocol>> {
    self.bundle_settings.deep_link_protocols.as_ref()
  }

  /// Returns the app's short description.
  pub fn short_description(&self) -> &str {
    self
      .bundle_settings
      .short_description
      .as_ref()
      .unwrap_or(&self.package.description)
  }

  /// Returns the app's long description.
  pub fn long_description(&self) -> Option<&str> {
    self.bundle_settings.long_description.as_deref()
  }

  /// Returns the debian settings.
  pub fn deb(&self) -> &DebianSettings {
    &self.bundle_settings.deb
  }

  /// Returns the RPM settings.
  pub fn rpm(&self) -> &RpmSettings {
    &self.bundle_settings.rpm
  }
Repository: tauri-apps/tauri
File: examples/run-iteration/main.rs (Rust)

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

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use tauri::Manager;

fn main() {
  let mut app = tauri::Builder::default()
    .build(tauri::generate_context!(
      "../../examples/helloworld/tauri.conf.json"
    ))
    .expect("error while building tauri application");

  loop {
    app.run_iteration(|_app, _event| {
      //println!("{:?}", _event);
    });

    if app.webview_windows().is_empty() {
      app.cleanup_before_exit();
      break;
    }
  }
}


Review comment (suggestion):
```suggestion
      "../../examples/run-iteration/tauri.conf.json"
```

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

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use tauri::Manager;

fn main() {
  let mut app = tauri::Builder::default()
    .build(tauri::generate_context!(
      "../../examples/run-iteration/tauri.conf.json"
    ))
    .expect("error while building tauri application");

  loop {
    app.run_iteration(|_app, _event| {
      //println!("{:?}", _event);
    });

    if app.webview_windows().is_empty() {
      app.cleanup_before_exit();
      break;
    }
  }
}
Repository: tauri-apps/tauri
File: core/tauri/src/event/listener.rs (Rust)

Code before:
        if handlers.is_empty() {
          empty.replace(key.clone());
        }

        if found {
          break 'outer;
        }
      }

      if let Some(key) = &empty {
        listeners.remove(key);
      }
    }
  }

  pub(crate) fn unlisten_all_js(&self, source_webview_label: &str) {
    let inner_listeners = self.inner.as_ref();
    let mut js_listeners = inner_listeners.js_event_listeners.lock().unwrap();
    js_listeners
      .iter_mut()
      .for_each(|(webview_label, listener)| {
        if webview_label == source_webview_label {
          listener.clear()
        }
      })
  }

  pub(crate) fn has_js_listener<F: Fn(&EventTarget) -> bool>(
    &self,
    event: &str,
    filter: F,
  ) -> bool {
    let listeners = self.inner.js_event_listeners.lock().unwrap();
    listeners.values().any(|events| {
      events
        .get(event)
        .map(|handlers| handlers.iter().any(|h| filter(&h.target)))
        .unwrap_or(false)
    })
  }

  pub(crate) fn emit_js_filter<'a, R, I, F>(
    &self,
    mut webviews: I,
    event: &str,
    emit_args: &EmitArgs,
    filter: Option<&F>,
  ) -> crate::Result<()>
  where
    R: Runtime,
    I: Iterator<Item = &'a Webview<R>>,

Review comment (suggestion):
We can just call `.remove(webview_label)`
```suggestion
  pub(crate) fn unlisten_all_js(&self, webview_label: &str) {
    let inner_listeners = self.inner.as_ref();
    let mut js_listeners = inner_listeners.js_event_listeners.lock().unwrap();
    js_listeners.remvoe(webview_label);
  }
```

Code after:
        if handlers.is_empty() {
          empty.replace(key.clone());
        }

        if found {
          break 'outer;
        }
      }

      if let Some(key) = &empty {
        listeners.remove(key);
      }
    }
  }

  pub(crate) fn unlisten_all_js(&self, webview_label: &str) {
    let inner_listeners = self.inner.as_ref();
    let mut js_listeners = inner_listeners.js_event_listeners.lock().unwrap();
    js_listeners.remove(webview_label);
  }

  pub(crate) fn has_js_listener<F: Fn(&EventTarget) -> bool>(
    &self,
    event: &str,
    filter: F,
  ) -> bool {
    let listeners = self.inner.js_event_listeners.lock().unwrap();
    listeners.values().any(|events| {
      events
        .get(event)
        .map(|handlers| handlers.iter().any(|h| filter(&h.target)))
        .unwrap_or(false)
    })
  }

  pub(crate) fn emit_js_filter<'a, R, I, F>(
    &self,
    mut webviews: I,
    event: &str,
    emit_args: &EmitArgs,
    filter: Option<&F>,
  ) -> crate::Result<()>
  where
    R: Runtime,
    I: Iterator<Item = &'a Webview<R>>,
    F: Fn(&EventTarget) -> bool,
  {
    let listeners = self.inner.js_event_listeners.lock().unwrap();
    webviews.try_for_each(|webview| {
      if let Some(handlers) = listeners.get(webview.label()).and_then(|s| s.get(event)) {
        for JsHandler { target, .. } in handlers {
Repository: tauri-apps/tauri
File: core/tauri/src/event/mod.rs (Rust)

Code before:
    emit_args.payload,
    target = serialized_target,
  ))
}

pub fn unlisten_js_script(
  listeners_object_name: &str,
  event_name: &str,
  event_id: EventId,
) -> String {
  format!(
    "
      (function () {{
        const listeners = (window['{listeners_object_name}'] || {{}})['{event_name}']
        if (listeners) {{
          const index = window['{listeners_object_name}']['{event_name}'].findIndex(e => e.id === {event_id})
          if (index > -1) {{
            window['{listeners_object_name}']['{event_name}'].splice(index, 1)
          }}
        }}
      }})()
    ",
  )
}

pub fn unlisten_all_js_script(listeners_object_name: &str) -> String {
  format!(
    r#"
      (function () {{
          var listenersObjectName = '{}';
          if (window[listenersObjectName]) {{
              for (var prop in window[listenersObjectName]) {{
                  if (window[listenersObjectName].hasOwnProperty(prop)) {{
                      window[listenersObjectName][prop] = undefined;
                  }}
              }}
          }}
        }})();
      "#,
    listeners_object_name
  )
}

pub fn event_initialization_script(function: &str, listeners: &str) -> String {
  format!(
    "
    Object.defineProperty(window, '{function}', {{
      value: function (eventData, target) {{
        const listeners = (window['{listeners}'] && window['{listeners}'][eventData.event]) || []
        for (let i = listeners.length - 1; i >= 0; i--) {{
          const listener = listeners[i]

Review comment (suggestion):
this shouldn't be necessary, since reloads will clear the `window` objects.

Code after:
    emit_args.payload,
    target = serialized_target,
  ))
}

pub fn unlisten_js_script(
  listeners_object_name: &str,
  event_name: &str,
  event_id: EventId,
) -> String {
  format!(
    "
      (function () {{
        const listeners = (window['{listeners_object_name}'] || {{}})['{event_name}']
        if (listeners) {{
          const index = window['{listeners_object_name}']['{event_name}'].findIndex(e => e.id === {event_id})
          if (index > -1) {{
            window['{listeners_object_name}']['{event_name}'].splice(index, 1)
          }}
        }}
      }})()
    ",
  )
}

pub fn event_initialization_script(function: &str, listeners: &str) -> String {
  format!(
    "
    Object.defineProperty(window, '{function}', {{
      value: function (eventData, target) {{
        const listeners = (window['{listeners}'] && window['{listeners}'][eventData.event]) || []
        for (let i = listeners.length - 1; i >= 0; i--) {{
          const listener = listeners[i]
          if (listener.target.kind === 'Any' || (listener.target.kind === target.kind && listener.target.label === target.label)) {{
            eventData.id = listener.id
            listener.handler(eventData)
          }}
        }}
      }}
    }});
  "
  )
}
Repository: tauri-apps/tauri
File: core/tauri/src/webview/mod.rs (Rust)

Code before:
              tauri_runtime::webview::DownloadEvent::Finished { url, path, success } => {
                DownloadEvent::Finished { url, path, success }
              }
            },
          )
        } else {
          false
        }
      }));
    }

    let label_ = pending.label.clone();
    let manager_ = manager.manager_owned();
    pending
      .on_page_load_handler
      .replace(Box::new(move |url, event| {
        if let Some(w) = manager_.get_webview(&label_) {
          if let PageLoadEvent::Finished = event {
            match w.unlisten_all_js() {
              Ok(_) => {
                // println!("Clear all residual js listeners when page load.")
              }
              Err(e) => {
                println!("Failed to clear residual js listeners when page load: {e}")
              }
            };
          }
          if let Some(handler) = self.on_page_load_handler.as_ref() {
            handler(w, PageLoadPayload { url: &url, event });
          }
        }
      }));

    manager.manager().webview.prepare_webview(
      manager,
      pending,
      window_label,
      window_labels,
      webview_labels,
    )
  }

  /// Creates a new webview on the given window.
  #[cfg(desktop)]
  pub(crate) fn build(
    self,
    window: Window<R>,
    position: Position,
    size: Size,
  ) -> crate::Result<Webview<R>> {
    let window_labels = window

Review comment (bug):
Should be okay to ignore the error here.
```suggestion
            let _ = w.unlisten_all_js();
```

Code after:
              tauri_runtime::webview::DownloadEvent::Finished { url, path, success } => {
                DownloadEvent::Finished { url, path, success }
              }
            },
          )
        } else {
          false
        }
      }));
    }

    let label_ = pending.label.clone();
    let manager_ = manager.manager_owned();
    pending
      .on_page_load_handler
      .replace(Box::new(move |url, event| {
        if let Some(w) = manager_.get_webview(&label_) {
          if let PageLoadEvent::Finished = event {
            w.unlisten_all_js();
          }
          if let Some(handler) = self.on_page_load_handler.as_ref() {
            handler(w, PageLoadPayload { url: &url, event });
          }
        }
      }));

    manager.manager().webview.prepare_webview(
      manager,
      pending,
      window_label,
      window_labels,
      webview_labels,
    )
  }

  /// Creates a new webview on the given window.
  #[cfg(desktop)]
  pub(crate) fn build(
    self,
    window: Window<R>,
    position: Position,
    size: Size,
  ) -> crate::Result<Webview<R>> {
    let window_labels = window
      .manager()
      .window
      .labels()
      .into_iter()
      .collect::<Vec<_>>();
    let webview_labels = window
      .manager()
Repository: tauri-apps/tauri
File: core/tauri/src/ipc/authority.rs (Rust)

Code before:
      identifier: identifier.into(),
      description: "".into(),
      remote: None,
      local: true,
      windows: Vec::new(),
      webviews: Vec::new(),
      permissions: Vec::new(),
      platforms: Vec::new(),
    })
  }

  /// Allows this capability to be used by a remote URL.
  pub fn remote(mut self, url: String) -> Self {
    self
      .0
      .remote
      .get_or_insert_with(Default::default)
      .urls
      .push(url);
    self
  }

  /// Do not apply this capability on local app URLs.
  pub fn skip_local(mut self) -> Self {
    self.0.local = false;
    self
  }

  /// Link this capability to the given window label.
  pub fn window(mut self, window: impl Into<String>) -> Self {
    self.0.windows.push(window.into());
    self
  }

  /// Link this capability to the given webview label.
  pub fn webview(mut self, webview: impl Into<String>) -> Self {
    self.0.webviews.push(webview.into());
    self
  }

  /// Add a new permission to this capability.
  pub fn permission(mut self, permission: impl Into<String>) -> Self {
    let permission = permission.into();
    self.0.permissions.push(PermissionEntry::PermissionRef(
      permission
        .clone()
        .try_into()
        .unwrap_or_else(|_| panic!("invalid permission identifier '{permission}'")),
    ));
    self
  }

Review comment (suggestion):
Probably better to just call it local and take a bool?
```suggestion
  pub fn local(mut self, local: bool) -> Self {
    self.0.local = local;
    self
```

Code after:
      identifier: identifier.into(),
      description: "".into(),
      remote: None,
      local: true,
      windows: Vec::new(),
      webviews: Vec::new(),
      permissions: Vec::new(),
      platforms: Vec::new(),
    })
  }

  /// Allows this capability to be used by a remote URL.
  pub fn remote(mut self, url: String) -> Self {
    self
      .0
      .remote
      .get_or_insert_with(Default::default)
      .urls
      .push(url);
    self
  }

  /// Whether this capability is applied on local app URLs or not. Defaults to `true`.
  pub fn local(mut self, local: bool) -> Self {
    self.0.local = local;
    self
  }

  /// Link this capability to the given window label.
  pub fn window(mut self, window: impl Into<String>) -> Self {
    self.0.windows.push(window.into());
    self
  }

  /// Link this capability to the a list of window labels.
  pub fn windows(mut self, windows: impl IntoIterator<Item = impl Into<String>>) -> Self {
    self.0.windows.extend(windows.into_iter().map(|w| w.into()));
    self
  }

  /// Link this capability to the given webview label.
  pub fn webview(mut self, webview: impl Into<String>) -> Self {
    self.0.webviews.push(webview.into());
    self
  }

  /// Link this capability to the a list of window labels.
  pub fn webviews(mut self, webviews: impl IntoIterator<Item = impl Into<String>>) -> Self {
    self
      .0
      .webviews
Repository: tauri-apps/tauri
File: tooling/api/src/core.ts (TypeScript)

Code before:
  private readonly __TAURI_CHANNEL_MARKER__ = true
  #onmessage: (response: T) => void = () => {
    // no-op
  }

  constructor() {
    this.id = transformCallback((response: T) => {
      this.#onmessage(response)
    })
  }

  set onmessage(handler: (response: T) => void) {
    this.#onmessage = handler
  }

  get onmessage(): (response: T) => void {
    return this.#onmessage
  }

  toJSON(): string {
    return `__CHANNEL__:${this.id}`
  }
}

class PluginListener {
  plugin: string
  event: string
  channelId: number

  constructor(plugin: string, event: string, channelId: number) {
    this.plugin = plugin
    this.event = event
    this.channelId = channelId
  }

  async unregister(): Promise<void> {
    return invoke(`plugin:${this.plugin}|remove_listener`, {
      event: this.event,
      channelId: this.channelId
    })
  }
}

/**
 * Adds a listener to a plugin event.
 *
 * @returns The listener object to stop listening to the events.
 *
 * @since 2.0.0
 */
async function addPluginListener<T>(

Review comment (performance):
delete is advised against for performance reasons, you might consider setting it to null instead.

Code after:
  private readonly __TAURI_CHANNEL_MARKER__ = true
  #onmessage: (response: T) => void = () => {
    // no-op
  }
  #nextMessageId = 0
  #pendingMessages: Record<string, T> = {}

  constructor() {
    this.id = transformCallback(
      ({ message, id }: { message: T; id: number }) => {
        // the id is used as a mechanism to preserve message order
        if (id === this.#nextMessageId) {
          this.#nextMessageId = id + 1
          this.#onmessage(message)

          // process pending messages
          const pendingMessageIds = Object.keys(this.#pendingMessages)
          if (pendingMessageIds.length > 0) {
            let nextId = id + 1
            for (const pendingId of pendingMessageIds.sort()) {
              // if we have the next message, process it
              if (parseInt(pendingId) === nextId) {
                // eslint-disable-next-line security/detect-object-injection
                const message = this.#pendingMessages[pendingId]
                // eslint-disable-next-line security/detect-object-injection
                delete this.#pendingMessages[pendingId]

                this.#onmessage(message)

                // move the id counter to the next message to check
                nextId += 1
              } else {
                // we do not have the next message, let's wait
                break
              }
            }
          }
        } else {
          this.#pendingMessages[id.toString()] = message
        }
      }
    )
  }

  set onmessage(handler: (response: T) => void) {
    this.#onmessage = handler
  }

  get onmessage(): (response: T) => void {
    return this.#onmessage
  }
Repository: tauri-apps/tauri
File: core/tauri/src/manager/mod.rs (Rust)

Code before:

#[default_runtime(crate::Wry, wry)]
pub struct AppManager<R: Runtime> {
  pub runtime_authority: Mutex<RuntimeAuthority>,
  pub window: window::WindowManager<R>,
  pub webview: webview::WebviewManager<R>,
  #[cfg(all(desktop, feature = "tray-icon"))]
  pub tray: tray::TrayManager<R>,
  #[cfg(desktop)]
  pub menu: menu::MenuManager<R>,

  pub(crate) plugins: Mutex<PluginStore<R>>,
  pub listeners: Listeners,
  pub state: Arc<StateManager>,
  pub config: Config,
  pub assets: Box<dyn Assets<R>>,

  pub app_icon: Option<Vec<u8>>,

  pub package_info: PackageInfo,

  /// Application pattern.
  pub pattern: Arc<Pattern>,

  /// Global API script.
  pub global_api_script: Arc<Option<String>>,

  /// Application Resources Table
  pub(crate) resources_table: Arc<Mutex<ResourceTable>>,
}

impl<R: Runtime> fmt::Debug for AppManager<R> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let mut d = f.debug_struct("AppManager");

    d.field("window", &self.window)
      .field("plugins", &self.plugins)
      .field("state", &self.state)
      .field("config", &self.config)
      .field("app_icon", &self.app_icon)
      .field("package_info", &self.package_info)
      .field("pattern", &self.pattern);

    #[cfg(all(desktop, feature = "tray-icon"))]
    {
      d.field("tray", &self.tray);
    }

    d.finish()
  }
}

Review comment (suggestion):
should probably prefeix with `plugin` like this `plugin_global_api_script` to make it clear that these are collected from plugins which is separate from global api defined by tauri crate itself.

Code after:

#[default_runtime(crate::Wry, wry)]
pub struct AppManager<R: Runtime> {
  pub runtime_authority: Mutex<RuntimeAuthority>,
  pub window: window::WindowManager<R>,
  pub webview: webview::WebviewManager<R>,
  #[cfg(all(desktop, feature = "tray-icon"))]
  pub tray: tray::TrayManager<R>,
  #[cfg(desktop)]
  pub menu: menu::MenuManager<R>,

  pub(crate) plugins: Mutex<PluginStore<R>>,
  pub listeners: Listeners,
  pub state: Arc<StateManager>,
  pub config: Config,
  pub assets: Box<dyn Assets<R>>,

  pub app_icon: Option<Vec<u8>>,

  pub package_info: PackageInfo,

  /// Application pattern.
  pub pattern: Arc<Pattern>,

  /// Global API scripts collected from plugins.
  pub plugin_global_api_scripts: Arc<Option<&'static [&'static str]>>,

  /// Application Resources Table
  pub(crate) resources_table: Arc<Mutex<ResourceTable>>,
}

impl<R: Runtime> fmt::Debug for AppManager<R> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let mut d = f.debug_struct("AppManager");

    d.field("window", &self.window)
      .field("plugins", &self.plugins)
      .field("state", &self.state)
      .field("config", &self.config)
      .field("app_icon", &self.app_icon)
      .field("package_info", &self.package_info)
      .field("pattern", &self.pattern);

    #[cfg(all(desktop, feature = "tray-icon"))]
    {
      d.field("tray", &self.tray);
    }

    d.finish()
  }
}