File: emoji_page_handler.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 (552 lines) | stat: -rw-r--r-- 19,421 bytes parent folder | download | duplicates (4)
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright 2020 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/webui/ash/emoji/emoji_page_handler.h"

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/public/cpp/system/toast_data.h"
#include "ash/public/cpp/system/toast_manager.h"
#include "base/json/values_util.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/strcat.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "base/trace_event/trace_event.h"
#include "base/types/expected.h"
#include "chrome/browser/ui/webui/ash/emoji/emoji_ui.h"
#include "chrome/browser/ui/webui/ash/emoji/seal_utils.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/ash/components/emoji/emoji_search.h"
#include "chromeos/ash/components/emoji/gif_tenor_api_fetcher.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "content/public/browser/storage_partition.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/base/ime/ash/ime_bridge.h"
#include "ui/base/ime/input_method_observer.h"
#include "ui/base/l10n/l10n_util.h"

namespace ash {

namespace {

constexpr char kEmojiPickerToastId[] = "emoji_picker_toast";
constexpr char kPrefsHistoryTextFieldName[] = "text";
constexpr char kPrefsHistoryTimestampFieldName[] = "timestamp";
constexpr char kPrefsPreferredVariantsFieldName[] = "preferred_variants";

// Keep in sync with entry in enums.xml.
enum class EmojiVariantType {
  // smaller entries only used by Chrome OS VK
  kEmojiPickerBase = 4,
  kEmojiPickerVariant = 5,
  kEmojiPickerGifInserted = 6,
  kEmojiPickerGifCopied = 7,
  kMaxValue = kEmojiPickerGifCopied,
};

void LogInsertEmoji(bool is_variant, int16_t search_length) {
  EmojiVariantType insert_value = is_variant
                                      ? EmojiVariantType::kEmojiPickerVariant
                                      : EmojiVariantType::kEmojiPickerBase;
  base::UmaHistogramEnumeration("InputMethod.SystemEmojiPicker.TriggerType",
                                insert_value);
  base::UmaHistogramCounts100("InputMethod.SystemEmojiPicker.SearchLength",
                              search_length);
}

void LogInsertGif(bool is_inserted) {
  EmojiVariantType insert_value =
      is_inserted ? EmojiVariantType::kEmojiPickerGifInserted
                  : EmojiVariantType::kEmojiPickerGifCopied;
  base::UmaHistogramEnumeration("InputMethod.SystemEmojiPicker.TriggerType",
                                insert_value);
}

void LogInsertEmojiDelay(base::TimeDelta delay) {
  base::UmaHistogramMediumTimes("InputMethod.SystemEmojiPicker.Delay", delay);
}

void LogLoadTime(base::TimeDelta delay) {
  base::UmaHistogramMediumTimes("InputMethod.SystemEmojiPicker.LoadTime",
                                delay);
}

void LogInsertionLatency(base::TimeDelta delay) {
  base::UmaHistogramTimes("InputMethod.SystemEmojiPicker.InsertionLatency",
                          delay);
}

std::string BuildGifHTML(const GURL& gif) {
  // Referrer-Policy is used to prevent Tenor from getting information about
  // where the GIFs are being used.
  return base::StrCat(
      {"<img src=\"", gif.spec(), "\" referrerpolicy=\"no-referrer\">"});
}

void CopyGifToClipboard(const GURL& gif_to_copy) {
  if (!gif_to_copy.is_valid()) {
    return;
  }

  // Overwrite the clipboard data with the GIF url.
  auto clipboard = std::make_unique<ui::ScopedClipboardWriter>(
      ui::ClipboardBuffer::kCopyPaste);

  clipboard->WriteHTML(base::UTF8ToUTF16(BuildGifHTML(gif_to_copy)), "");

  // Show a toast that says "GIF not supported. Copied to clipboard.".
  ToastManager::Get()->Show(ToastData(
      kEmojiPickerToastId, ToastCatalogName::kCopyGifToClipboardAction,
      l10n_util::GetStringUTF16(IDS_ASH_EMOJI_PICKER_COPY_GIF_TO_CLIPBOARD)));
}

std::string ConvertCategoryToPrefString(
    emoji_picker::mojom::Category category) {
  switch (category) {
    case emoji_picker::mojom::Category::kEmojis:
      return "emoji";
    case emoji_picker::mojom::Category::kSymbols:
      return "symbol";
    case emoji_picker::mojom::Category::kEmoticons:
      return "emoticon";
    case emoji_picker::mojom::Category::kGifs:
      return "gif";
  }
}

tenor::mojom::Status ConvertErrorToStatus(GifTenorApiFetcher::Error error) {
  switch (error) {
    case GifTenorApiFetcher::Error::kNetError:
      return tenor::mojom::Status::kNetError;
    case GifTenorApiFetcher::Error::kHttpError:
      return tenor::mojom::Status::kHttpError;
  }
}

}  // namespace

// Used to insert a gif / emoji after WebUI handler is destroyed, before
// self-constructing.
class InsertObserver : public ui::InputMethodObserver {
 public:
  explicit InsertObserver(ui::InputMethod* ime) : ime_(ime) {
    start_time_ = base::TimeTicks::Now();
    delete_timer_.Start(
        FROM_HERE, base::Seconds(1),
        base::BindOnce(&InsertObserver::DestroySelf, base::Unretained(this)));
  }

  ~InsertObserver() override { ime_->RemoveObserver(this); }

  virtual void PerformInsert(ui::TextInputClient* input_client) = 0;

  virtual void PerformCopy() = 0;

  void OnTextInputStateChanged(const ui::TextInputClient* client) override {
    focus_change_count_++;
    // At least 2 focus changes - 1 for loss of focus in emoji picker, second
    // for focusing in the new text field.
    // You would expect this to fail if the emoji picker window does not have
    // focus in the text field, but waiting for at least 2 focus changes is
    // still correct behavior.

    if (focus_change_count_ >= 2) {
      // Need to get the client via the IME as InsertText is non-const.
      // Can't use this->ime_ either as it may not be active, want to ensure
      // that we get the active IME.
      ui::InputMethod* input_method =
          IMEBridge::Get()->GetInputContextHandler()->GetInputMethod();

      if (!input_method) {
        return;
      }
      ui::TextInputClient* input_client = input_method->GetTextInputClient();

      if (!input_client) {
        return;
      }
      if (input_client->GetTextInputType() ==
          ui::TextInputType::TEXT_INPUT_TYPE_NONE) {
        // In some clients (e.g. Sheets), there is an extra focus before the
        // "real" text input field.
        focus_change_count_--;
        return;
      }

      PerformInsert(input_client);
      if (this->inserted_) {
        DestroySelf();
      }
      return;
    }
  }
  void OnFocus() override {}
  void OnBlur() override {}
  void OnCaretBoundsChanged(const ui::TextInputClient* client) override {}
  void OnInputMethodDestroyed(const ui::InputMethod* client) override {}

 protected:
  void MarkInserted() {
    this->inserted_ = true;
    LogInsertionLatency(base::TimeTicks::Now() - start_time_);
  }

 private:
  void DestroySelf() {
    if (!inserted_) {
      PerformCopy();
    }
    delete this;
  }
  int focus_change_count_ = 0;
  base::OneShotTimer delete_timer_;
  raw_ptr<ui::InputMethod, LeakedDanglingUntriaged> ime_;
  bool inserted_ = false;
  base::TimeTicks start_time_;
};

// Used to insert an emoji after WebUI handler is destroyed, before
// self-destructing.
class EmojiObserver : public InsertObserver {
 public:
  explicit EmojiObserver(const std::string& emoji_to_insert,
                         ui::InputMethod* ime)
      : InsertObserver(ime), emoji_to_insert_(emoji_to_insert) {}

  void PerformInsert(ui::TextInputClient* input_client) override {
    if (input_client->GetTextInputType() ==
        ui::TextInputType::TEXT_INPUT_TYPE_NONE) {
      // In some clients (e.g. Sheets), there is an extra focus before the
      // "real" text input field. so we skip this insertion.
      return;
    }
    input_client->InsertText(
        base::UTF8ToUTF16(emoji_to_insert_),
        ui::TextInputClient::InsertTextCursorBehavior::kMoveCursorAfterText);
    MarkInserted();
  }

  void PerformCopy() override {}

 private:
  std::string emoji_to_insert_;
};

// Used to insert a gif after WebUI handler is destroyed, before
// self-destructing.
class GifObserver : public InsertObserver {
 public:
  explicit GifObserver(const GURL& gif_to_insert, ui::InputMethod* ime)
      : InsertObserver(ime), gif_to_insert_(gif_to_insert) {}

  void PerformInsert(ui::TextInputClient* input_client) override {
    if (input_client->CanInsertImage()) {
      input_client->InsertImage(gif_to_insert_);
      MarkInserted();
      LogInsertGif(/*is_inserted=*/true);
    }
  }

  void PerformCopy() override {
    CopyGifToClipboard(gif_to_insert_);
    LogInsertGif(/*is_inserted=*/false);
  }

 private:
  GURL gif_to_insert_;
};

EmojiPageHandler::EmojiPageHandler(
    mojo::PendingReceiver<emoji_picker::mojom::PageHandler> receiver,
    content::WebUI* web_ui,
    EmojiUI* webui_controller,
    bool incognito_mode,
    bool no_text_field,
    emoji_picker::mojom::Category initial_category,
    const std::string& initial_query)
    : receiver_(this, std::move(receiver)),
      webui_controller_(webui_controller),
      incognito_mode_(incognito_mode),
      no_text_field_(no_text_field),
      initial_category_(initial_category),
      initial_query_(initial_query),
      profile_(Profile::FromWebUI(web_ui)) {
  // There are two conditions to control the GIF support:
  //   1. Feature flag is turned on.
  //   2. For managed users, the policy is turned on.
  gif_support_enabled_ =
      base::FeatureList::IsEnabled(features::kImeSystemEmojiPickerGIFSupport) &&
      (profile_->GetPrefs()->IsManagedPreference(
           prefs::kEmojiPickerGifSupportEnabled)
           ? profile_->GetPrefs()->GetBoolean(
                 prefs::kEmojiPickerGifSupportEnabled)
           : true);

  url_loader_factory_ = profile_->GetDefaultStoragePartition()
                            ->GetURLLoaderFactoryForBrowserProcess();
}

EmojiPageHandler::~EmojiPageHandler() = default;

void EmojiPageHandler::ShowUI() {
  auto embedder = webui_controller_->embedder();
  // Embedder may not exist in some cases (e.g. user browses to
  // chrome://emoji-picker directly rather than using right click on
  // text field -> emoji).
  if (embedder) {
    embedder->ShowUI();
  }
  shown_time_ = base::TimeTicks::Now();
}

void EmojiPageHandler::IsIncognitoTextField(
    IsIncognitoTextFieldCallback callback) {
  std::move(callback).Run(incognito_mode_);
}

void EmojiPageHandler::GetFeatureList(GetFeatureListCallback callback) {
  std::vector<emoji_picker::mojom::Feature> enabled_features;
  if (gif_support_enabled_) {
    enabled_features.push_back(
        emoji_picker::mojom::Feature::EMOJI_PICKER_GIF_SUPPORT);
  }

  if (base::FeatureList::IsEnabled(features::kImeSystemEmojiPickerMojoSearch)) {
    enabled_features.push_back(
        emoji_picker::mojom::Feature::EMOJI_PICKER_MOJO_SEARCH);
  }
  if (SealUtils::ShouldEnable()) {
    enabled_features.push_back(
        emoji_picker::mojom::Feature::EMOJI_PICKER_SEAL_SUPPORT);
  }

  if (base::FeatureList::IsEnabled(
          features::kImeSystemEmojiPickerVariantGrouping)) {
    enabled_features.push_back(
        emoji_picker::mojom::Feature::EMOJI_PICKER_VARIANT_GROUPING_SUPPORT);
  }

  std::move(callback).Run(enabled_features);
}

void EmojiPageHandler::GetCategories(GetCategoriesCallback callback) {
  GifTenorApiFetcher::FetchCategories(
      url_loader_factory_,
      base::BindOnce(
          [](GetCategoriesCallback callback,
             base::expected<std::vector<std::string>, GifTenorApiFetcher::Error>
                 response) {
            if (response.has_value()) {
              std::move(callback).Run(tenor::mojom::Status::kHttpOk,
                                      std::move(*response));
            } else {
              std::move(callback).Run(ConvertErrorToStatus(response.error()),
                                      {});
            }
          },
          std::move(callback)));
}

void EmojiPageHandler::GetFeaturedGifs(const std::optional<std::string>& pos,
                                       GetFeaturedGifsCallback callback) {
  GifTenorApiFetcher::FetchFeaturedGifs(
      url_loader_factory_, pos,
      base::BindOnce(
          [](GetFeaturedGifsCallback callback,
             base::expected<tenor::mojom::PaginatedGifResponsesPtr,
                            GifTenorApiFetcher::Error> response) {
            if (response.has_value()) {
              std::move(callback).Run(tenor::mojom::Status::kHttpOk,
                                      std::move(*response));
            } else {
              std::move(callback).Run(
                  ConvertErrorToStatus(response.error()),
                  tenor::mojom::PaginatedGifResponses::New(
                      "", std::vector<tenor::mojom::GifResponsePtr>{}));
            }
          },
          std::move(callback)));
}

void EmojiPageHandler::SearchGifs(const std::string& query,
                                  const std::optional<std::string>& pos,
                                  SearchGifsCallback callback) {
  GifTenorApiFetcher::FetchGifSearch(
      url_loader_factory_, query, pos,
      /*limit=*/std::nullopt,
      base::BindOnce(
          [](SearchGifsCallback callback,
             base::expected<tenor::mojom::PaginatedGifResponsesPtr,
                            GifTenorApiFetcher::Error> response) {
            if (response.has_value()) {
              std::move(callback).Run(tenor::mojom::Status::kHttpOk,
                                      std::move(*response));
            } else {
              std::move(callback).Run(
                  ConvertErrorToStatus(response.error()),
                  tenor::mojom::PaginatedGifResponses::New(
                      "", std::vector<tenor::mojom::GifResponsePtr>{}));
            }
          },
          std::move(callback)));
}

void EmojiPageHandler::GetGifsByIds(const std::vector<std::string>& ids,
                                    GetGifsByIdsCallback callback) {
  GifTenorApiFetcher::FetchGifsByIds(
      url_loader_factory_, ids,
      base::BindOnce(
          [](GetGifsByIdsCallback callback,
             base::expected<std::vector<tenor::mojom::GifResponsePtr>,
                            GifTenorApiFetcher::Error> response) {
            if (response.has_value()) {
              std::move(callback).Run(tenor::mojom::Status::kHttpOk,
                                      std::move(*response));
            } else {
              std::move(callback).Run(ConvertErrorToStatus(response.error()),
                                      {});
            }
          },
          std::move(callback)));
}

void EmojiPageHandler::InsertEmoji(const std::string& emoji_to_insert,
                                   bool is_variant,
                                   int16_t search_length) {
  LogInsertEmoji(is_variant, search_length);
  LogInsertEmojiDelay(base::TimeTicks::Now() - shown_time_);
  // In theory, we are returning focus to the input field where the user
  // originally selected emoji. However, the input field may not exist anymore
  // e.g. JS has mutated the web page while emoji picker was open, so check
  // that a valid input client is available as part of inserting the emoji.
  ui::InputMethod* input_method =
      IMEBridge::Get()->GetInputContextHandler()->GetInputMethod();
  if (!input_method) {
    DLOG(WARNING) << "no input_method found";
    return;
  }
  if (no_text_field_) {
    return;
  }

  // It seems like this might leak EmojiObserver, but the EmojiObserver
  // destroys itself on a timer (complex behavior needed since the observer
  // needs to outlive the page handler)
  input_method->AddObserver(new EmojiObserver(emoji_to_insert, input_method));

  // By hiding the emoji picker, we restore focus to the original text field
  // so we can insert the text.
  auto embedder = webui_controller_->embedder();
  if (embedder) {
    embedder->CloseUI();
  }
}

void EmojiPageHandler::InsertGif(const GURL& gif) {
  if (!gif.is_valid()) {
    return;
  }

  ui::InputMethod* input_method =
      IMEBridge::Get()->GetInputContextHandler()->GetInputMethod();

  if (!input_method) {
    DLOG(WARNING) << "no input_method found";
    CopyGifToClipboard(gif);
    LogInsertGif(/*is_inserted=*/false);
    return;
  }

  if (no_text_field_) {
    CopyGifToClipboard(gif);
    LogInsertGif(/*is_inserted=*/false);
    return;
  }

  // The GifObserver here will self-destroy.
  input_method->AddObserver(new GifObserver(gif, input_method));

  // By hiding the emoji picker, we restore focus to the original text field.
  auto embedder = webui_controller_->embedder();
  if (embedder) {
    embedder->CloseUI();
  }
}

void EmojiPageHandler::OnUiFullyLoaded() {
  LogLoadTime(base::TimeTicks::Now() - shown_time_);
}

void EmojiPageHandler::GetInitialCategory(GetInitialCategoryCallback callback) {
  std::move(callback).Run(initial_category_);
}

void EmojiPageHandler::GetInitialQuery(GetInitialQueryCallback callback) {
  std::move(callback).Run(initial_query_);
}

void EmojiPageHandler::UpdateHistoryInPrefs(
    emoji_picker::mojom::Category category,
    std::vector<emoji_picker::mojom::HistoryItemPtr> history) {
  base::Value::List history_value;
  for (const auto& item : history) {
    history_value.Append(base::Value::Dict()
                             .Set(kPrefsHistoryTextFieldName, item->emoji)
                             .Set(kPrefsHistoryTimestampFieldName,
                                  base::TimeToValue(item->timestamp)));
  }
  ScopedDictPrefUpdate update(profile_->GetPrefs(), prefs::kEmojiPickerHistory);
  update->Set(ConvertCategoryToPrefString(category), std::move(history_value));
}

void EmojiPageHandler::UpdatePreferredVariantsInPrefs(
    std::vector<emoji_picker::mojom::EmojiVariantPtr> preferred_variants) {
  base::Value::Dict value;
  for (const auto& variant : preferred_variants) {
    value.Set(variant->base, variant->variant);
  }
  ScopedDictPrefUpdate update(profile_->GetPrefs(),
                              prefs::kEmojiPickerPreferences);
  update->Set(kPrefsPreferredVariantsFieldName, std::move(value));
}

void EmojiPageHandler::GetHistoryFromPrefs(
    emoji_picker::mojom::Category category,
    GetHistoryFromPrefsCallback callback) {
  if (profile_ == nullptr || profile_->GetPrefs() == nullptr) {
    std::move(callback).Run({});
    return;
  }
  const base::Value::List* history =
      profile_->GetPrefs()
          ->GetDict(prefs::kEmojiPickerHistory)
          .FindList(ConvertCategoryToPrefString(category));
  if (history == nullptr) {
    std::move(callback).Run({});
    return;
  }
  std::vector<emoji_picker::mojom::HistoryItemPtr> results;
  for (const auto& it : *history) {
    const base::Value::Dict* value_dict = it.GetIfDict();
    if (value_dict == nullptr) {
      continue;
    }
    const std::string* text =
        value_dict->FindString(kPrefsHistoryTextFieldName);
    std::optional<base::Time> timestamp =
        base::ValueToTime(value_dict->Find(kPrefsHistoryTimestampFieldName));

    if (text != nullptr) {
      results.push_back(emoji_picker::mojom::HistoryItem::New(
          *text, timestamp.has_value() ? *timestamp : base::Time::UnixEpoch()));
    }
  }
  std::move(callback).Run(std::move(results));
}

}  // namespace ash