File: audio_selection_notification_handler.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (437 lines) | stat: -rw-r--r-- 18,839 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/audio/audio_selection_notification_handler.h"

#include <cstring>
#include <optional>

#include "ash/strings/grit/ash_strings.h"
#include "base/functional/bind.h"
#include "base/notreached.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "chromeos/ash/components/audio/audio_device.h"
#include "chromeos/ash/components/audio/cras_audio_handler.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/public/cpp/notification.h"
#include "ui/message_center/public/cpp/notification_delegate.h"
#include "ui/message_center/vector_icons.h"

namespace ash {

namespace {

// Separator used to split the audio device name.
constexpr char kAudioDeviceNameSeparator[] = ":";

// Extracts the audio device source name of an audio device. e.g. the source
// name for "Razer USB Sound Card: USB Audio:2,0: Mic" would be "Razer USB Sound
// Card". The source name for "Airpods" would be "Airpods".
std::string ExtractDeviceSourceName(const AudioDevice& device) {
  std::vector<std::string> parts =
      base::SplitString(device.display_name, kAudioDeviceNameSeparator,
                        base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
  return parts.front();
}

// Checks if a given device is in a device list
bool IsDeviceInList(const AudioDevice& target_device,
                    const AudioDeviceList& device_list) {
  for (const AudioDevice& device : device_list) {
    if (target_device.stable_device_id == device.stable_device_id) {
      return true;
    }
  }
  return false;
}

}  // namespace

AudioSelectionNotificationHandler::AudioSelectionNotificationHandler() =
    default;
AudioSelectionNotificationHandler::~AudioSelectionNotificationHandler() =
    default;

AudioSelectionNotificationHandler::NotificationTemplate::NotificationTemplate(
    NotificationType type,
    std::optional<std::string> input_device_name,
    std::optional<std::string> output_device_name)
    : type(type),
      input_device_name(input_device_name),
      output_device_name(output_device_name) {}

AudioSelectionNotificationHandler::NotificationTemplate::
    ~NotificationTemplate() = default;

bool AudioSelectionNotificationHandler::AudioNodesBelongToSameSource(
    const AudioDevice& input_device,
    const AudioDevice& output_device) {
  CHECK(input_device.is_input);
  CHECK(!output_device.is_input);

  // Handle internal audio device.
  if ((input_device.type == AudioDeviceType::kInternalMic ||
       input_device.type == AudioDeviceType::kFrontMic ||
       input_device.type == AudioDeviceType::kRearMic) &&
      output_device.type == AudioDeviceType::kInternalSpeaker) {
    return true;
  }

  // Handle special cases where input and output device are the same source but
  // different device types. kMic and kHeadphone are the types for 3.5mm jack
  // headphone's input and output. Similarly, kBluetoothNbMic and kBluetooth are
  // the types for a bluetooth device.
  if ((input_device.type == AudioDeviceType::kMic &&
       output_device.type == AudioDeviceType::kHeadphone) ||
      (input_device.type == AudioDeviceType::kBluetoothNbMic &&
       output_device.type == AudioDeviceType::kBluetooth)) {
    return true;
  }

  // For other devices, different device types indicate different device
  // sources.
  if (input_device.type != output_device.type) {
    return false;
  }

  // With same device type, checks their device source name.
  return ExtractDeviceSourceName(input_device)
             .compare(ExtractDeviceSourceName(output_device)) == 0;
}

void AudioSelectionNotificationHandler::ShowAudioSelectionNotification(
    const AudioDeviceList& hotplug_input_devices,
    const AudioDeviceList& hotplug_output_devices,
    const std::optional<std::string>& active_input_device_name,
    const std::optional<std::string>& active_output_device_name,
    SwitchToDeviceCallback switch_to_device_callback,
    OpenSettingsAudioPageCallback open_settings_audio_page_callback) {
  // At least input or output has hotplug device.
  CHECK(!hotplug_input_devices.empty() || !hotplug_output_devices.empty());

  // If show_notification callback is already in the queue, stop it and append
  // new hot plugged devices to the existing list, so that the notification can
  // handle them together. Otherwise, reset the existing hot plugged list.
  if (show_notification_debounce_timer_.IsRunning()) {
    show_notification_debounce_timer_.Stop();
    for (const AudioDevice& device : hotplug_input_devices) {
      hotplug_input_devices_.push_back(device);
    }
    for (const AudioDevice& device : hotplug_output_devices) {
      hotplug_output_devices_.push_back(device);
    }
  } else {
    hotplug_input_devices_.clear();
    hotplug_input_devices_ = hotplug_input_devices;
    hotplug_output_devices_.clear();
    hotplug_output_devices_ = hotplug_output_devices;
  }

  show_notification_debounce_timer_.Start(
      FROM_HERE, kDebounceTime,
      base::BindRepeating(&AudioSelectionNotificationHandler::ShowNotification,
                          weak_ptr_factory_.GetWeakPtr(),
                          active_input_device_name, active_output_device_name,
                          switch_to_device_callback,
                          open_settings_audio_page_callback));
}

void AudioSelectionNotificationHandler::ShowNotification(
    const std::optional<std::string>& active_input_device_name,
    const std::optional<std::string>& active_output_device_name,
    SwitchToDeviceCallback switch_to_device_callback,
    OpenSettingsAudioPageCallback open_settings_audio_page_callback) {
  AudioDeviceList devices_to_activate;
  std::u16string title_message_id;
  std::u16string body_message_id;
  std::vector<message_center::ButtonInfo> buttons_info;
  AudioDeviceMetricsHandler::AudioSelectionNotificationEvents
      notification_event;

  NotificationTemplate notification_template = GetNotificationTemplate(
      hotplug_input_devices_, hotplug_output_devices_, active_input_device_name,
      active_output_device_name);

  // Use different notification titles and messages based on notification types.
  switch (notification_template.type) {
    case NotificationType::kSingleSourceWithInputOnly:
      title_message_id =
          l10n_util::GetStringUTF16(IDS_ASH_AUDIO_SELECTION_SWITCH_INPUT_TITLE);
      body_message_id = l10n_util::GetStringFUTF16(
          IDS_ASH_AUDIO_SELECTION_SWITCH_INPUT_OR_OUTPUT_BODY,
          base::UTF8ToUTF16(hotplug_input_devices_.front().display_name));
      devices_to_activate.push_back(hotplug_input_devices_.front());
      buttons_info.emplace_back(
          l10n_util::GetStringUTF16(IDS_ASH_AUDIO_SELECTION_BUTTON_SWITCH));
      notification_event =
          AudioDeviceMetricsHandler::AudioSelectionNotificationEvents::
              kNotificationWithInputOnlyDeviceShowsUp;
      break;
    case NotificationType::kSingleSourceWithOutputOnly:
      title_message_id = l10n_util::GetStringUTF16(
          IDS_ASH_AUDIO_SELECTION_SWITCH_OUTPUT_TITLE);
      body_message_id = l10n_util::GetStringFUTF16(
          IDS_ASH_AUDIO_SELECTION_SWITCH_INPUT_OR_OUTPUT_BODY,
          base::UTF8ToUTF16(hotplug_output_devices_.front().display_name));
      devices_to_activate.push_back(hotplug_output_devices_.front());
      buttons_info.emplace_back(
          l10n_util::GetStringUTF16(IDS_ASH_AUDIO_SELECTION_BUTTON_SWITCH));
      notification_event =
          AudioDeviceMetricsHandler::AudioSelectionNotificationEvents::
              kNotificationWithOutputOnlyDeviceShowsUp;
      break;
    case NotificationType::kSingleSourceWithInputAndOutput:
      title_message_id = l10n_util::GetStringUTF16(
          IDS_ASH_AUDIO_SELECTION_SWITCH_SOURCE_TITLE);
      body_message_id = l10n_util::GetStringFUTF16(
          IDS_ASH_AUDIO_SELECTION_SWITCH_INPUT_AND_OUTPUT_BODY,
          base::UTF8ToUTF16(
              ExtractDeviceSourceName(hotplug_output_devices_.front())));
      devices_to_activate.push_back(hotplug_input_devices_.front());
      devices_to_activate.push_back(hotplug_output_devices_.front());
      buttons_info.emplace_back(
          l10n_util::GetStringUTF16(IDS_ASH_AUDIO_SELECTION_BUTTON_SWITCH));
      notification_event =
          AudioDeviceMetricsHandler::AudioSelectionNotificationEvents::
              kNotificationWithBothInputAndOutputDevicesShowsUp;
      break;
    case NotificationType::kMultipleSources:
      title_message_id = l10n_util::GetStringUTF16(
          IDS_ASH_AUDIO_SELECTION_MULTIPLE_DEVICES_TITLE);
      body_message_id =
          active_input_device_name.has_value() &&
                  active_output_device_name.has_value()
              ? l10n_util::GetStringFUTF16(
                    IDS_ASH_AUDIO_SELECTION_MULTIPLE_DEVICES_BODY,
                    base::UTF8ToUTF16(active_input_device_name.value()),
                    base::UTF8ToUTF16(active_output_device_name.value()))
              : l10n_util::GetStringUTF16(
                    IDS_ASH_AUDIO_SELECTION_MULTIPLE_DEVICES_BODY_WITH_NAME_UNAVAILABLE);
      buttons_info.emplace_back(
          l10n_util::GetStringUTF16(IDS_ASH_AUDIO_SELECTION_BUTTON_SETTINGS));
      notification_event =
          AudioDeviceMetricsHandler::AudioSelectionNotificationEvents::
              kNotificationWithMultipleSourcesDevicesShowsUp;
      break;
  }

  audio_device_metrics_handler_.RecordNotificationEvents(notification_event);

  message_center::RichNotificationData optional_fields;
  optional_fields.buttons = buttons_info;

  // If notification type is kMultipleSources, show Settings button and pass
  // HandleSettingsButtonClicked function.
  auto notification_delegate =
      notification_template.type == NotificationType::kMultipleSources
          ? base::BindRepeating(
                &AudioSelectionNotificationHandler::HandleSettingsButtonClicked,
                weak_ptr_factory_.GetWeakPtr(),
                open_settings_audio_page_callback)
          : base::BindRepeating(
                &AudioSelectionNotificationHandler::HandleSwitchButtonClicked,
                weak_ptr_factory_.GetWeakPtr(), devices_to_activate,
                switch_to_device_callback, notification_template.type);

  message_center::Notification notification{
      /*type=*/message_center::NOTIFICATION_TYPE_SIMPLE,
      /*id=*/kAudioSelectionNotificationId,
      /*title=*/title_message_id,
      /*message=*/body_message_id, ui::ImageModel(),
      /*display_source=*/
      l10n_util::GetStringUTF16(IDS_ASH_AUDIO_SELECTION_SOURCE),
      /*origin_url=*/GURL(),
      /*notifier_id=*/
      message_center::NotifierId(message_center::NotifierType::SYSTEM_COMPONENT,
                                 kAudioSelectionNotifierId,
                                 NotificationCatalogName::kAudioSelection),
      optional_fields,
      /*delegate=*/
      base::MakeRefCounted<message_center::HandleNotificationClickDelegate>(
          notification_delegate)};
  auto* message_center = message_center::MessageCenter::Get();
  message_center->RemoveNotification(notification.id(),
                                     /*by_user=*/false);
  message_center->AddNotification(
      std::make_unique<message_center::Notification>(notification));
}

void AudioSelectionNotificationHandler::HandleSwitchButtonClicked(
    const AudioDeviceList& devices_to_activate,
    SwitchToDeviceCallback switch_to_device_callback,
    NotificationType notification_type,
    std::optional<int> button_index) {
  if (!button_index.has_value()) {
    // Do not do anything when notification body is clicked. If the button is
    // clicked, the button_index will have a value.
    return;
  }

  switch (notification_type) {
    case NotificationType::kSingleSourceWithInputOnly:
      audio_device_metrics_handler_.RecordNotificationEvents(
          AudioDeviceMetricsHandler::AudioSelectionNotificationEvents::
              kNotificationWithInputOnlyDeviceClicked);
      break;
    case NotificationType::kSingleSourceWithOutputOnly:
      audio_device_metrics_handler_.RecordNotificationEvents(
          AudioDeviceMetricsHandler::AudioSelectionNotificationEvents::
              kNotificationWithOutputOnlyDeviceClicked);
      break;
    case NotificationType::kSingleSourceWithInputAndOutput:
      audio_device_metrics_handler_.RecordNotificationEvents(
          AudioDeviceMetricsHandler::AudioSelectionNotificationEvents::
              kNotificationWithBothInputAndOutputDevicesClicked);
      break;
    case NotificationType::kMultipleSources:
      // Do not record in this case. When the notification type is
      // kMultipleSources, notification with settings button should display.
      NOTREACHED();
  }

  // Activate audio devices.
  for (const AudioDevice& device : devices_to_activate) {
    switch_to_device_callback.Run(device, /*notify=*/true,
                                  DeviceActivateType::kActivateByUser);
  }

  // Remove notification and hotplug_input/output_devices_.
  auto* message_center = message_center::MessageCenter::Get();
  message_center->RemoveNotification(kAudioSelectionNotificationId,
                                     /*by_user=*/true);
  hotplug_input_devices_.clear();
  hotplug_output_devices_.clear();
}

void AudioSelectionNotificationHandler::HandleSettingsButtonClicked(
    base::RepeatingCallback<void()> open_settigns_callback,
    std::optional<int> button_index) {
  if (!button_index.has_value()) {
    // Do not do anything when notification body is clicked. If the button is
    // clicked, the button_index will have a value.
    return;
  }

  audio_device_metrics_handler_.RecordNotificationEvents(
      AudioDeviceMetricsHandler::AudioSelectionNotificationEvents::
          kNotificationWithMultipleSourcesDevicesClicked);

  // Open OS Settings audio page.
  open_settigns_callback.Run();

  // Remove notification.
  auto* message_center = message_center::MessageCenter::Get();
  message_center->RemoveNotification(kAudioSelectionNotificationId,
                                     /*by_user=*/true);
}

AudioSelectionNotificationHandler::NotificationTemplate
AudioSelectionNotificationHandler::GetNotificationTemplate(
    const AudioDeviceList& hotplug_input_devices,
    const AudioDeviceList& hotplug_output_devices,
    const std::optional<std::string>& active_input_device_name,
    const std::optional<std::string>& active_output_device_name) {
  // There must be either hotplug input devices, or hotplug output devices, or
  // both. Otherwise, this function shouldn't be called.
  CHECK(!hotplug_input_devices.empty() || !hotplug_output_devices.empty());

  // Hot plugged devices that are used to determine notification type must be
  // simple usage audio devices.
  for (const AudioDevice& device : hotplug_input_devices) {
    CHECK(device.is_for_simple_usage());
  }
  for (const AudioDevice& device : hotplug_output_devices) {
    CHECK(device.is_for_simple_usage());
  }

  // If there are more than one input devices, or more than one output devices,
  // they must come from multiple audio sources.
  if (hotplug_input_devices.size() > 1 || hotplug_output_devices.size() > 1) {
    return {
        AudioSelectionNotificationHandler::NotificationType::kMultipleSources,
        active_input_device_name, active_output_device_name};
  }

  CHECK(hotplug_input_devices.size() <= 1 &&
        hotplug_output_devices.size() <= 1);

  // If there is exactly one input and one output device, check if they belong
  // to the same source.
  if (hotplug_input_devices.size() == 1 && hotplug_output_devices.size() == 1) {
    if (AudioSelectionNotificationHandler::AudioNodesBelongToSameSource(
            hotplug_input_devices.front(), hotplug_output_devices.front())) {
      return {AudioSelectionNotificationHandler::NotificationType::
                  kSingleSourceWithInputAndOutput,
              hotplug_input_devices.front().display_name,
              hotplug_output_devices.front().display_name};
    } else {
      return {
          AudioSelectionNotificationHandler::NotificationType::kMultipleSources,
          active_input_device_name, active_output_device_name};
    }
  }

  CHECK(hotplug_input_devices.size() + hotplug_output_devices.size() == 1);

  // If there is exactly one input device and no output device, it's
  // kSingleSourceWithInputOnly notification type.
  if (hotplug_input_devices.size() == 1) {
    return {AudioSelectionNotificationHandler::NotificationType::
                kSingleSourceWithInputOnly,
            hotplug_input_devices.front().display_name, std::nullopt};
  }

  // If there is exactly one output device and no input device, it's
  // kSingleSourceWithOutputOnly notification type.
  return {AudioSelectionNotificationHandler::NotificationType::
              kSingleSourceWithOutputOnly,
          std::nullopt, hotplug_output_devices.front().display_name};
}

void AudioSelectionNotificationHandler::
    RemoveNotificationIfHotpluggedDeviceActivated(
        const AudioDeviceList& activated_devices) {
  const AudioDeviceList& hotplug_devices = activated_devices.front().is_input
                                               ? hotplug_input_devices_
                                               : hotplug_output_devices_;
  for (const AudioDevice& device : activated_devices) {
    if (IsDeviceInList(device, hotplug_devices)) {
      // Remove notification and hotplug_input/output_devices_.
      auto* message_center = message_center::MessageCenter::Get();
      message_center->RemoveNotification(kAudioSelectionNotificationId,
                                         /*by_user=*/false);

      hotplug_input_devices_.clear();
      hotplug_output_devices_.clear();
      return;
    }
  }
}

void AudioSelectionNotificationHandler::
    RemoveNotificationIfHotpluggedDeviceDisconnected(
        bool is_input,
        const AudioDeviceList& current_devices) {
  const AudioDeviceList& hotplug_devices =
      is_input ? hotplug_input_devices_ : hotplug_output_devices_;

  // If hotplugged devices that trigger the notification does not exist in
  // current devices, remove the notification.
  for (const AudioDevice& device : hotplug_devices) {
    if (!IsDeviceInList(device, current_devices)) {
      // Remove notification and hotplug_input/output_devices_.
      auto* message_center = message_center::MessageCenter::Get();
      message_center->RemoveNotification(kAudioSelectionNotificationId,
                                         /*by_user=*/false);

      hotplug_input_devices_.clear();
      hotplug_output_devices_.clear();
      return;
    }
  }
}

}  // namespace ash