Bug 1966586 - Reuse other browser windows when opening _blank links in Taskbar Tabs windows. r=nrishel
This doesn't affect other tab additions, nor does it stop the tab bar
from appearing altogether. The idea is that _if_ another tab is somehow
made, the user should see it; but we should not create new tabs if we
can avoid it.
This also adds tests for opening URIs in popups and taskbar tabs to make
it less likely that this breaks in future.
Differential Revision: https://phabricator.services.mozilla.com/D253726
// -*- mode: Rust -*-// AUTOGENERATED BY glean_parser. DO NOT EDIT.{# The rendered source is autogenerated, but thisJinja2 template is not. Please file bugs! #}/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */{% macro generate_structure(name, struct) %}{% if struct.type == "array" %} pub type {{ name }} = Vec<{{ name }}Item>; {{ generate_structure(name ~ "Item", struct["items"]) -}}{% elif struct.type == "object" %} #[derive(Debug, Hash, Eq, PartialEq, Clone, ::glean::traits::__serde::Serialize, ::glean::traits::__serde::Deserialize)] #[allow(non_snake_case)] #[serde(deny_unknown_fields)] pub struct {{ name }} { {% for itemname, val in struct.properties.items() %} {% if val.type == "object" %} #[serde(skip_serializing_if = "Option::is_none")] pub {{itemname|snake_case}}: Option<{{ name ~ "Item" ~ itemname|Camelize ~ "Object" }}>, {% elif val.type == "array" %} #[serde(skip_serializing_if = "Vec::is_empty", default = "Vec::new")] pub {{itemname|snake_case}}: {{ name ~ "Item" ~ itemname|Camelize }}, {% else %} #[serde(skip_serializing_if = "Option::is_none")] pub {{itemname|snake_case}}: Option<{{val.type|structure_type_name}}>, {% endif %} {% endfor %} } {% for itemname, val in struct.properties.items() %} {% if val.type == "array" %} {% set nested_name = name ~ "Item" ~ itemname|Camelize %} {{ generate_structure(nested_name, val) -}} {% elif val.type == "object" %} {% set nested_name = name ~ "Item" ~ itemname|Camelize ~ "Object" %} {{ generate_structure(nested_name, val) -}} {% endif %} {% endfor %}{% else %}pub type {{ name }} = {{ struct.type|structure_type_name }};{% endif %}{% endmacro %}{% macro generate_extra_keys(obj) -%}{% for name, _ in obj["_generate_enums"] %}{# we always use the `extra` suffix, because we only expose the new event API #}{% set suffix = "Extra" %}{% if obj|attr(name)|length %} {{ extra_keys_with_types(obj, name, suffix)|indent }}{% endif %}{% endfor %}{%- endmacro -%}{%- macro extra_keys_with_types(obj, name, suffix) -%}#[derive(Default, Debug, Clone, Hash, Eq, PartialEq)]#[allow(non_snake_case)]pub struct {{ obj.name|Camelize }}{{ suffix }} { {% for item, type in obj|attr(name) %} pub r#{{ item }}: Option<{{type|extra_type_name}}>, {% endfor %}}impl ExtraKeys for {{ obj.name|Camelize }}{{ suffix }} { const ALLOWED_KEYS: &'static [&'static str] = {{ obj.allowed_extra_keys|extra_keys }}; fn into_ffi_extra(self) -> ::std::collections::HashMap<String, String> { let mut map = ::std::collections::HashMap::new(); {% for key, _ in obj|attr(name) %} self.r#{{key|snake_case}}.and_then(|val| map.insert("{{key|snake_case}}".into(), val.to_string())); {% endfor %} map }}{%- endmacro -%}{% macro generate_label_enum(obj) %}#[repr(u16)]pub enum {{ obj.name|Camelize }}Label { {% for label in obj.ordered_labels %} {# Specifically _not_ using r# as C++ doesn't have it #} E{{ label|Camelize }} = {{loop.index0}}, {% endfor %} __Other__,}impl From<u16> for {{ obj.name|Camelize }}Label { fn from(v: u16) -> Self { match v { {% for label in obj.ordered_labels %} {{ loop.index0 }} => Self::E{{ label|Camelize }}, {% endfor %} _ => Self::__Other__, } }}impl Into<&'static str> for {{ obj.name|Camelize }}Label { fn into(self) -> &'static str { match self { {% for label in obj.ordered_labels %} Self::E{{ label| Camelize }} => "{{label}}", {% endfor %} Self::__Other__ => "__other__", } }}{%- endmacro -%}{% macro common_metric_data(obj) %}CommonMetricData { {% for arg_name in common_metric_data_args if obj[arg_name] is defined %} {{ arg_name }}: {{ obj[arg_name]|rust }}, {% endfor %} ..Default::default()}{%- endmacro -%}pub enum DynamicLabel { }{% for category_name, objs in all_objs.items() %}pub mod {{ category_name|snake_case }} { use crate::private::*; #[allow(unused_imports)] // CommonMetricData might be unused, let's avoid warnings use glean::CommonMetricData; #[allow(unused_imports)] // HistogramType might be unusued, let's avoid warnings use glean::HistogramType; use once_cell::sync::Lazy; {% for obj in objs.values() %} {% if obj|attr("_generate_enums") %}{{ generate_extra_keys(obj) }} {%- endif %} {% if obj.labeled and obj.labels and obj.labels|length %} {{ generate_label_enum(obj)|indent }} {% endif %} {% if obj|attr("_generate_structure") %} {{ generate_structure(obj.name|Camelize ~ "Object", obj._generate_structure) -}} {% endif %} #[allow(non_upper_case_globals)] /// generated from {{ category_name }}.{{ obj.name }} /// /// {{ obj.description|trim | replace('\n', '\n /// ') }} {% if obj.type == "counter" and obj.send_in_pings|length == 1 and obj.lifetime|rust == "Lifetime::Ping" %} {# Use optimized CounterMetric ctor in a common case (esp. for Use Counters) #} pub static {{ obj.name|snake_case }}: Lazy<{{ obj|type_name }}> = Lazy::new(|| { CounterMetric::codegen_{{ "disabled_" if obj.disabled }}new( {{obj|metric_id}}, "{{obj.category}}", "{{obj.name}}", "{{obj.send_in_pings[0]}}" ) }); {% else %} pub static {{ obj.name|snake_case }}: Lazy<{{ obj|type_name }}> = Lazy::new(|| { let meta = {% if obj.type == "labeled_custom_distribution" %} LabeledMetricData::CustomDistribution { cmd: {{ common_metric_data(obj)|indent(16) }} {%- for arg_name in extra_args if obj[arg_name] is defined and arg_name not in common_metric_data_args and arg_name != 'allowed_extra_keys' -%} , {{ arg_name }}: {{ obj[arg_name]|rust }} {%- endfor -%} }; {% elif obj.type == "labeled_memory_distribution" %} LabeledMetricData::MemoryDistribution { cmd: {{ common_metric_data(obj)|indent(16) }} {%- for arg_name in extra_args if obj[arg_name] is defined and arg_name not in common_metric_data_args and arg_name != 'allowed_extra_keys' -%} , {{ "unit" if arg_name == "memory_unit" else arg_name }}: {{ obj[arg_name]|rust }} {%- endfor -%} }; {% elif obj.type == "labeled_timing_distribution" %} LabeledMetricData::TimingDistribution { cmd: {{ common_metric_data(obj)|indent(16) }} {%- for arg_name in extra_args if obj[arg_name] is defined and arg_name not in common_metric_data_args and arg_name != 'allowed_extra_keys' -%} , {{ "unit" if arg_name == "time_unit" else arg_name }}: {{ obj[arg_name]|rust }} {%- endfor -%} }; {% elif obj.labeled %} LabeledMetricData::Common { cmd: {{ common_metric_data(obj)|indent(16) }}, }; {% else %} {{ common_metric_data(obj)|indent(12) }}; {% endif %} let metric = {{ obj|ctor }}(BaseMetricId({{obj|metric_id}}), meta {%- for arg_name in extra_args if not obj.labeled and obj[arg_name] is defined and arg_name not in common_metric_data_args and arg_name != 'allowed_extra_keys' -%} , {{ obj[arg_name]|rust }} {%- endfor -%} {{ ", " if obj.labeled or obj.dual_labeled else ")\n" }} {%- if obj.labeled -%} {%- if obj.labels -%} Some({{ obj.labels|rust }})) {%- else -%} None) {%- endif -%} {%- elif obj.dual_labeled -%} {{ "Some(" ~ obj.keys|rust ~ ")" if obj.keys else "None" }}, {{ "Some(" ~ obj.categories|rust ~ ")" if obj.categories else "None" }}) {%- endif -%}; {% if obj.type == "event" or obj.type == "object" %} {# event/object metrics don't have a map. They don't allocate anymore after instantiation, so it's enough to measure once. #} #[cfg(feature = "with_gecko")] { crate::metrics::METRIC_MEM_OPS.with_borrow_mut(|ops| { use malloc_size_of::MallocSizeOf; super::count_memory_usage(metric.size_of(ops)); }); } {% endif %} metric }); {% endif %} {% endfor %}}{% endfor %}{% if metric_by_type|length > 0 %}#[allow(dead_code)]pub(crate) mod __glean_metric_maps { use std::collections::HashMap; use std::sync::Arc; use crate::metrics::extra_keys_len; use crate::private::*; use malloc_size_of::MallocSizeOf; use once_cell::sync::Lazy; /// Measure the allocation size of all labeled metrics. /// /// Labeled metrics do allocate additional memory at runtime for the cache of instantiated submetrics. /// These are included in the `size_of` measurement automatically. /// /// **Note**: This function grows with the number of labeled metrics! /// If it becomes too big we need to think about further optimizations. fn fog_labeled_alloc_size(ops: &mut malloc_size_of::MallocSizeOfOps) -> usize { let mut n = 0; {% for labeled_type, labeleds_by_id in labeleds_by_id_by_type.items() %} {% for metric_id, (labeled, _) in labeleds_by_id.items() %} n += super::{{labeled}}.size_of(ops); {% endfor %} {% endfor %} n } fn fog_submetric_alloc_size(ops: &mut malloc_size_of::MallocSizeOfOps) -> usize { let mut n = 0; n += once_cell::sync::Lazy::get(&submetric_maps::LABELED_METRICS_TO_IDS).map(|m| { let lock = m.read().unwrap(); (*lock).size_of(ops) }).unwrap_or(0); n += once_cell::sync::Lazy::get(&submetric_maps::LABELED_ENUMS_TO_IDS).map(|m| { let lock = m.read().unwrap(); (*lock).size_of(ops) }).unwrap_or(0); {% for typ, metrics in metric_by_type.items() %} {% if typ.0 in ('BOOLEAN_MAP', 'COUNTER_MAP', 'CUSTOM_DISTRIBUTION_MAP', 'MEMORY_DISTRIBUTION_MAP', 'QUANTITY_MAP', 'STRING_MAP', 'TIMING_DISTRIBUTION_MAP') %} n += once_cell::sync::Lazy::get(&submetric_maps::{{typ.0}}).map(|m| { // The values are behind an `Arc`. We don't want to measure them. // We only measure the enclosing size of the values. let lock = m.read().unwrap(); malloc_size_of::MallocShallowSizeOf::shallow_size_of(&*lock, ops) }).unwrap_or(0); {% endif %} {% endfor%} n } pub fn fog_map_alloc_size(ops: &mut malloc_size_of::MallocSizeOfOps) -> usize { let mut n = 0; {% for typ, metrics in metric_by_type.items() %} n += {{typ.0}}.size_of(ops); {% endfor %} n += fog_labeled_alloc_size(ops); n += fog_submetric_alloc_size(ops); n }{% for typ, metrics in metric_by_type.items() %} pub static {{typ.0}}: Lazy<HashMap<BaseMetricId, &Lazy<{{typ.1}}>>> = Lazy::new(|| { let mut map = HashMap::with_capacity({{metrics|length}}); {% for metric in metrics %} map.insert(BaseMetricId({{metric.0}}), &super::{{metric.1}}); {% endfor %} map });{% endfor %} pub(crate) fn set_object_by_id(metric_id: u32, value: String) -> Result<(), ()> { match metric_id {{% for metric_id, object in objects_by_id.items() %} {{metric_id}} => { super::{{object}}.set_string(value); Ok(()) }{% endfor %} _ => Err(()), } } /// Wrapper to get the currently stored object for object metric as a string. /// /// # Arguments /// /// * `metric_id` - The metric's ID to look up /// * `ping_name` - (Optional) The ping name to look into. /// Defaults to the first value in `send_in_pings`. /// /// # Returns /// /// Returns the recorded object serialized as a JSON string or `None` if nothing stored. /// /// # Panics /// /// Panics if no object by the given metric ID could be found. pub(crate) fn object_test_get_value(metric_id: u32, ping_name: Option<String>) -> Option<String> { match metric_id {{% for metric_id, object in objects_by_id.items() %} {{metric_id}} => super::{{object}}.test_get_value_as_str(ping_name.as_deref()),{% endfor %} _ => panic!("No object for metric id {}", metric_id), } } /// Check the provided object for errors. /// /// # Arguments /// /// * `metric_id` - The metric's ID to look up /// /// # Returns /// /// Returns a string for the recorded error or `None`. /// /// # Panics /// /// Panics if no object by the given metric ID could be found. #[allow(unused_variables)] pub(crate) fn object_test_get_error(metric_id: u32) -> Option<String> { #[cfg(feature = "with_gecko")] match metric_id {{% for metric_id, object in objects_by_id.items() %} {{metric_id}} => test_get_errors!(super::{{object}}),{% endfor %} _ => panic!("No object for metric id {}", metric_id), } #[cfg(not(feature = "with_gecko"))] { return None; } } /// Wrapper to record an event based on its metric ID. /// /// # Arguments /// /// * `metric_id` - The metric's ID to look up /// * `extra` - An map of (extra key id, string) pairs. /// The map will be decoded into the appropriate `ExtraKeys` type. /// # Returns /// /// Returns `Ok(())` if the event was found and `record` was called with the given `extra`, /// or an `EventRecordingError::InvalidId` if no event by that ID exists /// or an `EventRecordingError::InvalidExtraKey` if the `extra` map could not be deserialized. pub(crate) fn record_event_by_id(metric_id: u32, extra: HashMap<String, String>) -> Result<(), EventRecordingError> { match metric_id {{% for metric_id, event in events_by_id.items() %} {{metric_id}} => { super::{{event}}.record_raw(extra); Ok(()) }{% endfor %} _ => Err(EventRecordingError::InvalidId), } } /// Wrapper to record an event based on its metric ID, with a provided timestamp. /// /// # Arguments /// /// * `metric_id` - The metric's ID to look up /// * `timestamp` - The time at which this event was recorded. /// * `extra` - An map of (extra key id, string) pairs. /// The map will be decoded into the appropriate `ExtraKeys` type. /// # Returns /// /// Returns `Ok(())` if the event was found and `record` was called with the given `extra`, /// or an `EventRecordingError::InvalidId` if no event by that ID exists /// or an `EventRecordingError::InvalidExtraKey` if the event doesn't take extra pairs, /// but some are passed in. pub(crate) fn record_event_by_id_with_time(metric_id: BaseMetricId, timestamp: u64, extra: HashMap<String, String>) -> Result<(), EventRecordingError> { match metric_id {{% for metric_id, event in events_by_id.items() %} BaseMetricId({{metric_id}}) => { if extra_keys_len(&super::{{event}}) == 0 && !extra.is_empty() { return Err(EventRecordingError::InvalidExtraKey); } super::{{event}}.record_with_time(timestamp, extra); Ok(()) }{% endfor %} _ => Err(EventRecordingError::InvalidId), } } /// Wrapper to get the currently stored events for event metric. /// /// # Arguments /// /// * `metric_id` - The metric's ID to look up /// * `ping_name` - (Optional) The ping name to look into. /// Defaults to the first value in `send_in_pings`. /// /// # Returns /// /// Returns the recorded events or `None` if nothing stored. /// /// # Panics /// /// Panics if no event by the given metric ID could be found. pub(crate) fn event_test_get_value_wrapper(metric_id: u32, ping_name: Option<String>) -> Option<Vec<RecordedEvent>> { match metric_id {{% for metric_id, event in events_by_id.items() %} {{metric_id}} => super::{{event}}.test_get_value(ping_name.as_deref()),{% endfor %} _ => panic!("No event for metric id {}", metric_id), } } /// Check the provided event for errors. /// /// # Arguments /// /// * `metric_id` - The metric's ID to look up /// * `ping_name` - (Optional) The ping name to look into. /// Defaults to the first value in `send_in_pings`. /// /// # Returns /// /// Returns a string for the recorded error or `None`. /// /// # Panics /// /// Panics if no event by the given metric ID could be found. #[allow(unused_variables)] pub(crate) fn event_test_get_error(metric_id: u32) -> Option<String> { #[cfg(feature = "with_gecko")] match metric_id {{% for metric_id, event in events_by_id.items() %} {{metric_id}} => test_get_errors!(super::{{event}}),{% endfor %} _ => panic!("No event for metric id {}", metric_id), } #[cfg(not(feature = "with_gecko"))] { return None; } }{% for labeled_type, labeleds_by_id in labeleds_by_id_by_type.items() %} /// Gets the submetric from the specified labeled_{{labeled_type}} metric. /// /// # Arguments /// /// * `metric_id` - The metric's ID to look up /// * `label` - The label identifying the {{labeled_type}} submetric. /// /// # Returns /// /// Returns the {{labeled_type}} submetric. /// /// # Panics /// /// Panics if no labeled_{{labeled_type}} by the given metric ID could be found. #[allow(unused_variables)] pub(crate) fn labeled_{{labeled_type}}_get(metric_id: u32, label: &str) -> Arc<Labeled{{labeled_type|Camelize}}Metric> { match metric_id {{% for metric_id, (labeled, _) in labeleds_by_id.items() %} {{metric_id}} => super::{{labeled}}.get(label),{% endfor %} _ => panic!("No labeled_{{labeled_type}} for metric id {}", metric_id), } }{% endfor %} pub(crate) fn labeled_enum_to_str(metric_id: u32, label: u16) -> &'static str { match metric_id {{% for category_name, objs in all_objs.items() %}{% for obj in objs.values() %}{% if obj.labeled and obj.labels and obj.labels|length %} {{obj|metric_id}} => super::{{category_name|snake_case}}::{{obj.name|Camelize}}Label::from(label).into(),{% endif %}{% endfor %}{% endfor %} _ => panic!("Can't turn label enum to string for metric {} which isn't a labeled metric with static labels", metric_id), } } pub(crate) fn labeled_submetric_id_get(metric_id: u32, label: &str) -> u32 { match metric_id {{% for category_name, objs in all_objs.items() %}{% for obj in objs.values() %}{% if obj.labeled %} {{obj|metric_id}} => super::{{category_name|snake_case}}::{{obj.name|snake_case}}.get_submetric_id(label),{% endif %}{% endfor %}{% endfor %} _ => panic!("No labeled metric for id {}", metric_id), } }{# dual_labeled type support. Only need dual_labeled_counter for now, so specialize. #} pub(crate) fn dual_labeled_counter_get(metric_id: u32, key: &str, category: &str) -> Arc<DualLabeledCounterSubMetric> { match metric_id {{% for metric_id, dlc in dual_labeled_counters_by_id.items() %} {{metric_id}} => super::{{dlc}}.get(key, category),{% endfor %} _ => panic!("No dual_labeled_counter for metric id {}", metric_id), } } pub(crate) fn dual_labeled_submetric_id_get(metric_id: u32, key: &str, category: &str) -> u32 { match metric_id {{% for metric_id, dlc in dual_labeled_counters_by_id.items() %} {{metric_id}} => super::{{dlc}}.get_submetric_id(key, category),{% endfor %} _ => panic!("No dual-labeled metric for id {}", metric_id), } } pub(crate) mod submetric_maps { use std::sync::{ atomic::AtomicU32, Arc, RwLock, }; use super::*; pub(crate) const SUBMETRIC_BIT: u32 = {{submetric_bit}}; pub(crate) static NEXT_LABELED_SUBMETRIC_ID: AtomicU32 = AtomicU32::new((1 << SUBMETRIC_BIT) + 1); pub(crate) static LABELED_METRICS_TO_IDS: Lazy<RwLock<HashMap<(BaseMetricId, String), SubMetricId>>> = Lazy::new(|| RwLock::new(HashMap::new()) ); pub(crate) static LABELED_ENUMS_TO_IDS: Lazy<RwLock<HashMap<(u32, u16), u32>>> = Lazy::new(|| RwLock::new(HashMap::new()) );{% for typ, metrics in metric_by_type.items() %}{% if typ.0 in ('BOOLEAN_MAP', 'COUNTER_MAP', 'CUSTOM_DISTRIBUTION_MAP', 'MEMORY_DISTRIBUTION_MAP', 'QUANTITY_MAP', 'STRING_MAP', 'TIMING_DISTRIBUTION_MAP') %} pub static {{typ.0}}: Lazy<RwLock<HashMap<SubMetricId, Arc<Labeled{{typ.1}}>>>> = Lazy::new(|| RwLock::new(HashMap::new()) );{% endif %}{% endfor%} pub static DUAL_COUNTER_MAP: Lazy<RwLock<HashMap<SubMetricId, Arc<DualLabeledCounterSubMetric>>>> = Lazy::new(|| RwLock::new(HashMap::new()) ); }}{% endif %}