File: mahi_ui_controller.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (364 lines) | stat: -rw-r--r-- 12,197 bytes parent folder | download | duplicates (6)
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
// 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 "ash/system/mahi/mahi_ui_controller.h"

#include <memory>

#include "ash/session/session_controller_impl.h"
#include "ash/shell.h"
#include "ash/system/mahi/mahi_constants.h"
#include "ash/system/mahi/mahi_panel_widget.h"
#include "ash/system/mahi/mahi_ui_update.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "chromeos/components/mahi/public/cpp/mahi_manager.h"
#include "components/account_id/account_id.h"
#include "ui/views/view.h"

namespace ash {

namespace {

// Returns true if `status` indicates an error.
// NOTE: `chromeos::MahiResponseStatus::kLowQuota` is a warning.
bool IsErrorStatus(chromeos::MahiResponseStatus status) {
  switch (status) {
    case chromeos::MahiResponseStatus::kCantFindOutputData:
    case chromeos::MahiResponseStatus::kContentExtractionError:
    case chromeos::MahiResponseStatus::kInappropriate:
    case chromeos::MahiResponseStatus::kQuotaLimitHit:
    case chromeos::MahiResponseStatus::kResourceExhausted:
    case chromeos::MahiResponseStatus::kUnknownError:
    case chromeos::MahiResponseStatus::kRestrictedCountry:
    case chromeos::MahiResponseStatus::kUnsupportedLanguage:
      return true;
    case chromeos::MahiResponseStatus::kLowQuota:
    case chromeos::MahiResponseStatus::kSuccess:
      return false;
  }
}

}  // namespace

// MahiUiController::delegate --------------------------------------------------

MahiUiController::Delegate::Delegate(MahiUiController* ui_controller) {
  CHECK(ui_controller);
  observation_.Observe(ui_controller);
}

MahiUiController::Delegate::~Delegate() = default;

// MahiUiController ------------------------------------------------------------

MahiUiController::MahiUiController() {
  // The shell may not be available in tests if using a plain object for the UI
  // controller, which means the session will not be observed.
  if (Shell::HasInstance()) {
    Shell::Get()->session_controller()->AddObserver(this);
  }
}

MahiUiController::~MahiUiController() {
  if (Shell::HasInstance()) {
    Shell::Get()->session_controller()->RemoveObserver(this);
  }

  if (mahi_panel_widget_) {
    // Immediately close the widget to avoid dangling pointers in tests.
    mahi_panel_widget_->CloseNow();
    mahi_panel_widget_.reset();
  }

  RecordTimesPanelOpenedMetric();
}

void MahiUiController::AddDelegate(Delegate* delegate) {
  delegates_.AddObserver(delegate);
}

void MahiUiController::RemoveDelegate(Delegate* delegate) {
  delegates_.RemoveObserver(delegate);
}

void MahiUiController::OpenMahiPanel(int64_t display_id,
                                     const gfx::Rect& mahi_menu_bounds,
                                     bool elucidation_in_use) {
  // TODO(http://b/339250208): Use DCHECK instead of return early when
  // `IsEnabled()` is false.
  if (!chromeos::MahiManager::Get()->IsEnabled()) {
    return;
  }

  elucidation_in_use_ = elucidation_in_use;

  mahi_panel_widget_ = MahiPanelWidget::CreateAndShowPanelWidget(
      display_id, mahi_menu_bounds, /*ui_controller=*/this);
  times_panel_opened_per_session_++;
}

void MahiUiController::CloseMahiPanel() {
  mahi_panel_widget_.reset();
}

bool MahiUiController::IsMahiPanelOpen() {
  return !!mahi_panel_widget_;
}

void MahiUiController::NavigateToQuestionAnswerView() {
  SetVisibilityStateAndNotifyUiUpdate(
      VisibilityState::kQuestionAndAnswer,
      MahiUiUpdate(MahiUiUpdateType::kQuestionAndAnswerViewNavigated));
}

void MahiUiController::NavigateToSummaryOutlinesSection() {
  SetVisibilityStateAndNotifyUiUpdate(
      VisibilityState::kSummaryAndOutlinesAndElucidation,
      MahiUiUpdate(MahiUiUpdateType::kSummaryAndOutlinesSectionNavigated));
}

void MahiUiController::NotifyRefreshAvailabilityChanged(bool available) {
  // Do not show the refresh banner when the elucidation panel is showing
  // because the elucidation is based on user selected text, while clicking the
  // banner refreshes summary of the new focused webpage/PDF file and doesn't
  // make sense in such cases.
  if (elucidation_in_use_) {
    return;
  }

  NotifyUiUpdate(
      MahiUiUpdate(MahiUiUpdateType::kRefreshAvailabilityUpdated, available));
}

void MahiUiController::NotifyPanelBoundsChanged(const gfx::Rect& panel_bounds) {
  NotifyUiUpdate(
      MahiUiUpdate(MahiUiUpdateType::kPanelBoundsChanged, panel_bounds));
}

void MahiUiController::RefreshContents() {
  most_recent_question_params_.reset();
  NavigateToSummaryOutlinesSection();
  if (elucidation_in_use_) {
    NotifyUiUpdate(MahiUiUpdate(MahiUiUpdateType::kElucidationRequested));
  } else {
    NotifyUiUpdate(MahiUiUpdate(MahiUiUpdateType::kContentsRefreshInitiated));
  }
}

void MahiUiController::Retry(VisibilityState origin_state) {
  switch (origin_state) {
    case VisibilityState::kQuestionAndAnswer:
      if (most_recent_question_params_) {
        SetVisibilityStateAndNotifyUiUpdate(
            origin_state, MahiUiUpdate(MahiUiUpdateType::kQuestionReAsked,
                                       *most_recent_question_params_));
      } else {
        LOG(ERROR) << "Tried to re-ask a non-existing question";
      }
      return;
    case VisibilityState::kSummaryAndOutlinesAndElucidation:
      // TODO(crbug.com/375292907, crbug.com/375293412): retry is not robust
      // enough, try fix.
      if (elucidation_in_use_) {
        SetVisibilityStateAndNotifyUiUpdate(
            origin_state,
            MahiUiUpdate(MahiUiUpdateType::kElucidationRequested));
      } else {
        SetVisibilityStateAndNotifyUiUpdate(
            origin_state,
            MahiUiUpdate(MahiUiUpdateType::kSummaryAndOutlinesReloaded));
      }
      return;

    case VisibilityState::kError:
      NOTREACHED();
  }
}

void MahiUiController::SendQuestion(const std::u16string& question,
                                    bool current_panel_content,
                                    QuestionSource source,
                                    bool update_summary_after_answer_question) {
  InvalidatePendingRequests();

  update_summary_after_answer_question_ = update_summary_after_answer_question;

  base::UmaHistogramEnumeration(
      mahi_constants::kMahiQuestionSourceHistogramName, source);

  if (source != QuestionSource::kRetry) {
    most_recent_question_params_.emplace(question, current_panel_content);
  }

  // Display the Q&A section.
  SetVisibilityStateAndNotifyUiUpdate(
      VisibilityState::kQuestionAndAnswer,
      MahiUiUpdate(MahiUiUpdateType::kQuestionPosted, question));

  // If Mahi Manager Implementation allows for repeating answers, then the
  // callback function should be bound as a repeating callback. Else, a BindOnce
  // callback will be used.
  if (chromeos::MahiManager::Get()->AllowRepeatingAnswers()) {
    chromeos::MahiManager::Get()->AnswerQuestionRepeating(
        question, current_panel_content,
        base::BindRepeating(&MahiUiController::OnAnswerLoaded,
                            weak_ptr_factory_.GetWeakPtr()));
  } else {
    chromeos::MahiManager::Get()->AnswerQuestion(
        question, current_panel_content,
        base::BindOnce(&MahiUiController::OnAnswerLoaded,
                       weak_ptr_factory_.GetWeakPtr()));
  }
}

void MahiUiController::UpdateSummaryAndOutlines() {
  InvalidatePendingRequests();

  chromeos::MahiManager::Get()->GetSummary(base::BindOnce(
      &MahiUiController::OnSummaryLoaded, weak_ptr_factory_.GetWeakPtr()));
  chromeos::MahiManager::Get()->GetOutlines(base::BindOnce(
      &MahiUiController::OnOutlinesLoaded, weak_ptr_factory_.GetWeakPtr()));
}

void MahiUiController::UpdateElucidation() {
  InvalidatePendingRequests();

  chromeos::MahiManager::Get()->GetElucidation(base::BindOnce(
      &MahiUiController::OnElucidationLoaded, weak_ptr_factory_.GetWeakPtr()));
}

void MahiUiController::OnSessionStateChanged(
    session_manager::SessionState state) {
  if (state != session_manager::SessionState::ACTIVE) {
    RecordTimesPanelOpenedMetric();
    CloseMahiPanel();
  }
}

void MahiUiController::OnActiveUserSessionChanged(const AccountId& account_id) {
  CloseMahiPanel();
}

void MahiUiController::RecordTimesPanelOpenedMetric() {
  if (times_panel_opened_per_session_ > 0) {
    base::UmaHistogramCounts1000(
        mahi_constants::kTimesMahiPanelOpenedPerSessionHistogramName,
        times_panel_opened_per_session_);
  }

  times_panel_opened_per_session_ = 0;
}

void MahiUiController::HandleError(const MahiUiError& error) {
  // `chromeos::MahiResponseStatus::kLowQuota` is a warning not an error.
  CHECK_NE(error.status, chromeos::MahiResponseStatus::kLowQuota);

  // The presentation of any error during `State::kQuestionAndAnswer` should be
  // embedded into the Q&A view instead of a separate view.
  const MahiUiUpdate update(MahiUiUpdateType::kErrorReceived, error);
  if (error.origin_state == VisibilityState::kQuestionAndAnswer) {
    NotifyUiUpdate(update);
    return;
  }

  // Display the view that presents the error.
  SetVisibilityStateAndNotifyUiUpdate(VisibilityState::kError, update);
}

void MahiUiController::NotifyUiUpdate(const MahiUiUpdate& update) {
  for (auto& delegate : delegates_) {
    delegate.OnUpdated(update);
  }
}

void MahiUiController::SetVisibilityStateAndNotifyUiUpdate(
    VisibilityState state,
    const MahiUiUpdate& update) {
  visibility_state_ = state;

  for (auto& delegate : delegates_) {
    views::View* const associated_view = delegate.GetView();
    if (const bool target_visible = delegate.GetViewVisibility(state);
        target_visible != associated_view->GetVisible()) {
      associated_view->SetVisible(target_visible);
    }

    delegate.OnUpdated(update);
  }
}

void MahiUiController::OnAnswerLoaded(std::optional<std::u16string> answer,
                                      chromeos::MahiResponseStatus status) {
  if (IsErrorStatus(status)) {
    HandleError(MahiUiError(
        status, /*origin_state=*/VisibilityState::kQuestionAndAnswer));
    update_summary_after_answer_question_ = false;
    return;
  }

  // TODO(b/331302199): Handle the case that `answer` is `std::nullopt` in a
  // better way.
  if (!answer) {
    LOG(ERROR) << "Received an empty Mahi answer";
  }

  const std::u16string answer_after_process = answer.value_or(std::u16string());
  NotifyUiUpdate(
      MahiUiUpdate(MahiUiUpdateType::kAnswerLoaded, answer_after_process));

  if (update_summary_after_answer_question_) {
    // TODO(b/345621992): Add test to verify this behavior.
    UpdateSummaryAndOutlines();
    update_summary_after_answer_question_ = false;
  }
}

void MahiUiController::OnOutlinesLoaded(
    std::vector<chromeos::MahiOutline> outlines,
    chromeos::MahiResponseStatus status) {
  if (IsErrorStatus(status)) {
    HandleError(MahiUiError(
        status,
        /*origin_state=*/VisibilityState::kSummaryAndOutlinesAndElucidation));
    return;
  }

  NotifyUiUpdate(MahiUiUpdate(MahiUiUpdateType::kOutlinesLoaded, outlines));
}

void MahiUiController::OnSummaryLoaded(std::u16string summary_text,
                                       chromeos::MahiResponseStatus status) {
  if (IsErrorStatus(status)) {
    HandleError(MahiUiError(
        status,
        /*origin_state=*/VisibilityState::kSummaryAndOutlinesAndElucidation));
    return;
  }

  NotifyUiUpdate(MahiUiUpdate(MahiUiUpdateType::kSummaryLoaded, summary_text));
}

void MahiUiController::OnElucidationLoaded(
    std::u16string elucidation_text,
    chromeos::MahiResponseStatus status) {
  if (IsErrorStatus(status)) {
    HandleError(MahiUiError(
        status,
        /*origin_state=*/VisibilityState::kSummaryAndOutlinesAndElucidation));
    return;
  }
  NotifyUiUpdate(
      MahiUiUpdate(MahiUiUpdateType::kElucidationLoaded, elucidation_text));
}

void MahiUiController::InvalidatePendingRequests() {
  // By invalidating existing weak ptrs, the pending `OnAnswerLoaded`,
  // `OnOutlinesLoaded` and `OnSummaryLoaded` callbacks are cancelled.
  weak_ptr_factory_.InvalidateWeakPtrs();
}

}  // namespace ash