File: web_app_install_dialog_delegate.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; 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,811; 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 (347 lines) | stat: -rw-r--r-- 13,249 bytes parent folder | download | duplicates (2)
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
// 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 "chrome/browser/ui/views/web_apps/web_app_install_dialog_delegate.h"

#include <memory>

#include "base/functional/callback_helpers.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/observer_list_internal.h"
#include "base/task/sequenced_task_runner.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/page_action/page_action_icon_type.h"
#include "chrome/browser/ui/views/extensions/security_dialog_tracker.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/toolbar_button_provider.h"
#include "chrome/browser/ui/views/page_action/page_action_icon_view.h"
#include "chrome/browser/ui/web_applications/web_app_dialogs.h"
#include "chrome/browser/web_applications/web_app_helpers.h"
#include "chrome/browser/web_applications/web_app_install_info.h"
#include "chrome/browser/web_applications/web_app_pref_guardrails.h"
#include "components/feature_engagement/public/event_constants.h"
#include "components/feature_engagement/public/tracker.h"
#include "components/prefs/pref_service.h"
#include "components/webapps/browser/installable/ml_install_operation_tracker.h"
#include "content/public/browser/page.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/view_utils.h"
#include "ui/views/widget/widget.h"

#if BUILDFLAG(IS_CHROMEOS)
// TODO(crbug.com/40147906): Enable gn check once it learns about conditional
// includes.
#include "components/metrics/structured/structured_events.h"  // nogncheck
#include "components/metrics/structured/structured_metrics_client.h"  // nogncheck
#endif

namespace web_app {

namespace {

#if BUILDFLAG(IS_CHROMEOS)
namespace cros_events = metrics::structured::events::v2::cr_os_events;

int64_t ToLong(web_app::WebAppInstallStatus web_app_install_status) {
  return static_cast<int64_t>(web_app_install_status);
}
#endif

}  // namespace

constexpr int kMinBoundsForInstallDialog = 50;

std::u16string NormalizeSuggestedAppTitle(const std::u16string& title) {
  std::u16string normalized = title;
  if (base::StartsWith(normalized, u"https://")) {
    normalized = normalized.substr(8);
  }
  if (base::StartsWith(normalized, u"http://")) {
    normalized = normalized.substr(7);
  }
  return normalized;
}

bool IsWidgetCurrentSizeSmallerThanPreferredSize(views::Widget* widget) {
  const gfx::Size& current_size = widget->GetSize();
  const gfx::Size& preferred_size =
      widget->GetContentsView()->GetPreferredSize();
  int min_width = preferred_size.width() - kMinBoundsForInstallDialog;
  int min_height = preferred_size.height() - kMinBoundsForInstallDialog;
  return current_size.width() < min_width || current_size.height() < min_height;
}

DEFINE_CLASS_ELEMENT_IDENTIFIER_VALUE(WebAppInstallDialogDelegate,
                                      kDiyAppsDialogOkButtonId);
DEFINE_CLASS_ELEMENT_IDENTIFIER_VALUE(WebAppInstallDialogDelegate,
                                      kPwaInstallDialogInstallButton);
DEFINE_CLASS_CUSTOM_ELEMENT_EVENT_TYPE(WebAppInstallDialogDelegate,
                                       kInstalledPWAEventId);

WebAppInstallDialogDelegate::WebAppInstallDialogDelegate(
    content::WebContents* web_contents,
    std::unique_ptr<web_app::WebAppInstallInfo> web_app_info,
    std::unique_ptr<webapps::MlInstallOperationTracker> install_tracker,
    AppInstallationAcceptanceCallback callback,
    PwaInProductHelpState iph_state,
    PrefService* prefs,
    feature_engagement::Tracker* tracker,
    InstallDialogType dialog_type)
    : content::WebContentsObserver(web_contents),
      web_contents_(web_contents),
      install_info_(std::move(web_app_info)),
      install_tracker_(std::move(install_tracker)),
      callback_(std::move(callback)),
      iph_state_(std::move(iph_state)),
      prefs_(prefs),
      tracker_(tracker),
      dialog_type_(dialog_type) {
  CHECK(install_info_);
  CHECK(install_tracker_);
  CHECK(prefs_);
}

WebAppInstallDialogDelegate::~WebAppInstallDialogDelegate() {
  // TODO(crbug.com/40841129): move this to dialog->SetHighlightedButton.
  Browser* browser = chrome::FindBrowserWithTab(web_contents_);
  if (!browser) {
    return;
  }

  BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);

  if (browser_view && browser_view->toolbar_button_provider()) {
    PageActionIconView* install_icon =
        browser_view->toolbar_button_provider()->GetPageActionIconView(
            PageActionIconType::kPwaInstall);
    if (install_icon) {
      // Dehighlight the install icon when this dialog is closed.
      install_icon->SetHighlighted(false);
    }
  }
}

void WebAppInstallDialogDelegate::OnWidgetShownStartTracking(
    views::Widget* install_dialog_widget) {
  occlusion_observation_.Observe(install_dialog_widget);
  widget_observation_.Observe(install_dialog_widget);
  extensions::SecurityDialogTracker::GetInstance()->AddSecurityDialog(
      install_dialog_widget);
}

void WebAppInstallDialogDelegate::OnAccept() {
  MeasureAcceptUserActionsForInstallDialog();
  if (iph_state_ == PwaInProductHelpState::kShown) {
    webapps::AppId app_id =
        GenerateAppIdFromManifestId(install_info_->manifest_id());
    WebAppPrefGuardrails::GetForDesktopInstallIph(prefs_).RecordAccept(app_id);
    tracker_->NotifyEvent(feature_engagement::events::kDesktopPwaInstalled);
  }

#if BUILDFLAG(IS_CHROMEOS)
  const webapps::AppId app_id =
      web_app::GenerateAppIdFromManifestId(install_info_->manifest_id());
  metrics::structured::StructuredMetricsClient::Record(
      cros_events::AppDiscovery_Browser_AppInstallDialogResult()
          .SetWebAppInstallStatus(
              ToLong(web_app::WebAppInstallStatus::kAccepted))
          .SetAppId(app_id));
#endif  // BUILDFLAG(IS_CHROMEOS)

  // DIY apps get their name from the DIY install dialog and are always set to
  // open in a new window.
  if (dialog_type_ == InstallDialogType::kDiy) {
    CHECK(!text_field_contents_.empty());
    install_info_->title = text_field_contents_;
    install_info_->user_display_mode =
        web_app::mojom::UserDisplayMode::kStandalone;
  }

  // The password manager PWA installation tutorial requires the
  // `kInstalledPWAEventId` event to be fired from the detailed install dialog.
  // See `kPasswordManagerTutorialMetricPrefix` in
  // `MaybeRegisterChromeTutorials()` for more information.
  if (dialog_type_ == InstallDialogType::kDetailed) {
    auto* element_tracker = ui::ElementTracker::GetElementTracker();
    auto* element_framework = ui::ElementTracker::GetFrameworkDelegate();
    CHECK(element_tracker);
    auto* ok_button =
        element_tracker->GetElementInAnyContext(kPwaInstallDialogInstallButton);
    if (ok_button && element_framework) {
      element_framework->NotifyCustomEvent(ok_button, kInstalledPWAEventId);
    }
  }

  CHECK(callback_);
  CHECK(install_tracker_);
  install_tracker_->ReportResult(webapps::MlInstallUserResponse::kAccepted);
  received_user_response_ = true;
  base::UmaHistogramEnumeration(
      "WebApp.InstallConfirmation.CloseReason",
      views::Widget::ClosedReason::kAcceptButtonClicked);
  std::move(callback_).Run(true, std::move(install_info_));
}

void WebAppInstallDialogDelegate::OnCancel() {
  CHECK(install_tracker_);
  install_tracker_->ReportResult(webapps::MlInstallUserResponse::kCancelled);
  received_user_response_ = true;
  base::UmaHistogramEnumeration(
      "WebApp.InstallConfirmation.CloseReason",
      views::Widget::ClosedReason::kCancelButtonClicked);
  MeasureIphOnDialogClose();
}

void WebAppInstallDialogDelegate::OnClose() {
  CHECK(install_tracker_);
  install_tracker_->ReportResult(webapps::MlInstallUserResponse::kIgnored);
  received_user_response_ = true;

  // This could be hit by triggering the Esc key as well, unfortunately there is
  // no way to listen to that without observing the low level widget.
  base::UmaHistogramEnumeration(
      "WebApp.InstallConfirmation.CloseReason",
      views::Widget::ClosedReason::kCloseButtonClicked);
  MeasureIphOnDialogClose();
}

void WebAppInstallDialogDelegate::OnDestroyed() {
  // Only performs histogram measurement and other actions if the dialog was
  // destroyed without user action, like a change in visibility or navigation to
  // a different tab or destruction of the native widget that contains the
  // dialog this delegate is assigned to.
  if (received_user_response_) {
    return;
  }

  install_tracker_->ReportResult(webapps::MlInstallUserResponse::kIgnored);
  base::UmaHistogramEnumeration("WebApp.InstallConfirmation.CloseReason",
                                views::Widget::ClosedReason::kUnspecified);
  MeasureIphOnDialogClose();
}

void WebAppInstallDialogDelegate::OnTextFieldChangedMaybeUpdateButton(
    const std::u16string& text_field_contents) {
  text_field_contents_ = text_field_contents;
  ui::DialogModel::Button* ok_button =
      dialog_model()->GetButtonByUniqueId(kDiyAppsDialogOkButtonId);
  CHECK(ok_button);
  dialog_model()->SetButtonEnabled(ok_button,
                                   /*enabled=*/!text_field_contents.empty());
}

void WebAppInstallDialogDelegate::OnVisibilityChanged(
    content::Visibility visibility) {
  if (visibility != content::Visibility::VISIBLE) {
    CloseDialogAsIgnored();
  }
}

void WebAppInstallDialogDelegate::WebContentsDestroyed() {
  CloseDialogAsIgnored();
}

void WebAppInstallDialogDelegate::PrimaryPageChanged(content::Page& page) {
  CloseDialogAsIgnored();
}

void WebAppInstallDialogDelegate::OnOcclusionStateChanged(bool occluded) {
  // If a picture-in-picture window is occluding the dialog, force it to close
  // to prevent spoofing.
  if (occluded) {
    PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
  }
}

void WebAppInstallDialogDelegate::OnWidgetBoundsChanged(
    views::Widget* widget,
    const gfx::Rect& new_bounds) {
  if (IsWidgetCurrentSizeSmallerThanPreferredSize(widget)) {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE,
        base::BindOnce(&WebAppInstallDialogDelegate::CloseDialogAsIgnored,
                       weak_ptr_factory_.GetWeakPtr()));
  }
}

void WebAppInstallDialogDelegate::OnWidgetDestroyed(views::Widget* widget) {
  widget_observation_.Reset();
}

void WebAppInstallDialogDelegate::CloseDialogAsIgnored() {
  if (!dialog_model() || !dialog_model()->host()) {
    return;
  }
  CHECK(install_tracker_);
  install_tracker_->ReportResult(webapps::MlInstallUserResponse::kIgnored);
  dialog_model()->host()->Close();
}

void WebAppInstallDialogDelegate::MeasureIphOnDialogClose() {
  if (callback_.is_null()) {
    return;
  }
  MeasureCancelUserActionsForInstallDialog();
  if (iph_state_ == PwaInProductHelpState::kShown && install_info_) {
    webapps::AppId app_id =
        GenerateAppIdFromManifestId(install_info_->manifest_id());
    WebAppPrefGuardrails::GetForDesktopInstallIph(prefs_).RecordIgnore(
        app_id, base::Time::Now());
  }

  // If |install_info_| is populated, then the dialog was not accepted.
  if (install_info_) {
#if BUILDFLAG(IS_CHROMEOS)
    const webapps::AppId app_id =
        web_app::GenerateAppIdFromManifestId(install_info_->manifest_id());
    metrics::structured::StructuredMetricsClient::Record(
        cros_events::AppDiscovery_Browser_AppInstallDialogResult()
            .SetWebAppInstallStatus(
                ToLong(web_app::WebAppInstallStatus::kCancelled))
            .SetAppId(app_id));
#endif  // BUILDFLAG(IS_CHROMEOS)
    std::move(callback_).Run(false, std::move(install_info_));
  }
}

void WebAppInstallDialogDelegate::MeasureAcceptUserActionsForInstallDialog() {
  const char* accept_dialog_metric_name = nullptr;
  switch (dialog_type_) {
    case InstallDialogType::kDetailed:
      accept_dialog_metric_name = "WebAppDetailedInstallAccepted";
      break;
    case InstallDialogType::kSimple:
      accept_dialog_metric_name = "WebAppInstallAccepted";
      break;
    case InstallDialogType::kDiy:
      accept_dialog_metric_name = "WebAppDiyInstallAccepted";
      break;
  }
  base::RecordAction(base::UserMetricsAction(accept_dialog_metric_name));
}

void WebAppInstallDialogDelegate::MeasureCancelUserActionsForInstallDialog() {
  const char* cancel_dialog_metric_name = nullptr;
  switch (dialog_type_) {
    case InstallDialogType::kDetailed:
      cancel_dialog_metric_name = "WebAppDetailedInstallCancelled";
      break;
    case InstallDialogType::kSimple:
      cancel_dialog_metric_name = "WebAppInstallCancelled";
      break;
    case InstallDialogType::kDiy:
      cancel_dialog_metric_name = "WebAppDiyInstallCancelled";
      break;
  }
  base::RecordAction(base::UserMetricsAction(cancel_dialog_metric_name));
}

}  // namespace web_app