File: quick_insert_search_aggregator.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 (366 lines) | stat: -rw-r--r-- 13,419 bytes parent folder | download | duplicates (3)
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
// 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/quick_insert/search/quick_insert_search_aggregator.h"

#include <algorithm>
#include <cstddef>
#include <iterator>
#include <set>
#include <string>
#include <utility>
#include <variant>
#include <vector>

#include "ash/quick_insert/model/quick_insert_search_results_section.h"
#include "ash/quick_insert/quick_insert_search_result.h"
#include "ash/quick_insert/search/quick_insert_search_source.h"
#include "ash/quick_insert/views/quick_insert_view_delegate.h"
#include "base/check.h"
#include "base/containers/flat_set.h"
#include "base/containers/span.h"
#include "base/functional/overloaded.h"
#include "base/location.h"
#include "base/memory/weak_ptr.h"
#include "base/notreached.h"
#include "base/substring_set_matcher/matcher_string_pattern.h"
#include "base/time/time.h"
#include "base/types/cxx23_to_underlying.h"
#include "components/url_matcher/url_matcher.h"

namespace ash {

namespace {

QuickInsertSectionType SectionTypeFromSearchSource(
    QuickInsertSearchSource source) {
  switch (source) {
    case QuickInsertSearchSource::kOmnibox:
      return QuickInsertSectionType::kLinks;
    case QuickInsertSearchSource::kDate:
    case QuickInsertSearchSource::kMath:
      return QuickInsertSectionType::kNone;
    case QuickInsertSearchSource::kClipboard:
      return QuickInsertSectionType::kClipboard;
    case QuickInsertSearchSource::kAction:
      return QuickInsertSectionType::kNone;
    case QuickInsertSearchSource::kLocalFile:
      return QuickInsertSectionType::kLocalFiles;
    case QuickInsertSearchSource::kDrive:
      return QuickInsertSectionType::kDriveFiles;
    case QuickInsertSearchSource::kEditorWrite:
    case QuickInsertSearchSource::kEditorRewrite:
    case QuickInsertSearchSource::kLobsterWithNoSelectedText:
    case QuickInsertSearchSource::kLobsterWithSelectedText:
      return QuickInsertSectionType::kContentEditor;
    case QuickInsertSearchSource::kGifs:
      return QuickInsertSectionType::kSearchedGifs;
  }
}

bool ShouldPromote(const QuickInsertSearchResult& result) {
  return std::visit(
      base::Overloaded{
          [](const QuickInsertClipboardResult& data) { return data.is_recent; },
          [](const QuickInsertBrowsingHistoryResult& data) {
            return data.best_match;
          },
          [](const QuickInsertLocalFileResult& data) {
            return data.best_match;
          },
          [](const QuickInsertDriveFileResult& data) {
            return data.best_match;
          },
          [](const auto& data) { return false; }},
      result);
}

std::vector<GURL> LinksFromSearchResults(
    base::span<const QuickInsertSearchResult> results) {
  std::vector<GURL> links;
  for (const QuickInsertSearchResult& link : results) {
    auto* link_data = std::get_if<QuickInsertBrowsingHistoryResult>(&link);
    if (link_data == nullptr) {
      continue;
    }
    links.push_back(link_data->url);
  }
  return links;
}

std::vector<std::string> DriveIdsFromSearchResults(
    base::span<const QuickInsertSearchResult> results) {
  std::vector<std::string> drive_ids;
  for (const QuickInsertSearchResult& file : results) {
    auto* drive_data = std::get_if<QuickInsertDriveFileResult>(&file);
    if (drive_data == nullptr) {
      continue;
    }
    if (!drive_data->id.has_value()) {
      continue;
    }
    drive_ids.push_back(*drive_data->id);
  }
  return drive_ids;
}

void DeduplicateDriveLinksFromIds(std::vector<QuickInsertSearchResult>& links,
                                  std::vector<std::string> drive_ids) {
  std::vector<base::MatcherStringPattern> patterns;
  base::MatcherStringPattern::ID next_id = 0;
  for (std::string& drive_id : drive_ids) {
    patterns.emplace_back(std::move(drive_id), next_id);
    ++next_id;
  }

  base::SubstringSetMatcher matcher;
  bool success = matcher.Build(patterns);
  // This may fail if the tree gets too many nodes (`kInvalidNodeId`, which is
  // around ~8,400,000). Drive IDs are 44 characters long, so this would require
  // having >190,000 Drive IDs in the worst case. This should never happen.
  CHECK(success);

  std::erase_if(links, [&matcher](const QuickInsertSearchResult& link) {
    auto* link_data = std::get_if<QuickInsertBrowsingHistoryResult>(&link);
    if (link_data == nullptr) {
      return false;
    }
    return matcher.AnyMatch(link_data->url.spec());
  });
}

void DeduplicateDriveFilesFromLinks(std::vector<QuickInsertSearchResult>& files,
                                    base::span<const GURL> links) {
  std::vector<base::MatcherStringPattern> patterns;
  for (size_t i = 0; i < files.size(); ++i) {
    auto* drive_data = std::get_if<QuickInsertDriveFileResult>(&files[i]);
    if (drive_data == nullptr) {
      continue;
    }
    if (!drive_data->id.has_value()) {
      continue;
    }
    // Pattern IDs need to be associated with the index of the file so we can
    // remove them below.
    patterns.emplace_back(*drive_data->id, i);
  }

  base::SubstringSetMatcher matcher;
  bool success = matcher.Build(patterns);
  CHECK(success);

  std::set<size_t> matched_files;
  for (const GURL& link : links) {
    // Drive IDs are unlikely to overlap as they are random fixed-length
    // strings, so the number of `matched_files` set insertions should be
    // limited to `O(t)` for each call.
    matcher.Match(link.spec(), &matched_files);
  }
  std::vector<QuickInsertSearchResult*> results_to_remove;
  for (size_t i : matched_files) {
    results_to_remove.push_back(&files[i]);
  }
  base::flat_set<QuickInsertSearchResult*> results_to_remove_set =
      std::move(results_to_remove);

  std::erase_if(files,
                [&results_to_remove_set](const QuickInsertSearchResult& file) {
                  return results_to_remove_set.contains(&file);
                });
}

}  // namespace

QuickInsertSearchAggregator::QuickInsertSearchAggregator(
    base::TimeDelta burn_in_period,
    QuickInsertViewDelegate::SearchResultsCallback callback) {
  current_callback_ = std::move(callback);
  CHECK(!current_callback_.is_null());

  // TODO: b/324154537 - Show a loading animation while waiting for results.
  burn_in_timer_.Start(FROM_HERE, burn_in_period, this,
                       &QuickInsertSearchAggregator::PublishBurnInResults);
}

QuickInsertSearchAggregator::~QuickInsertSearchAggregator() = default;

void QuickInsertSearchAggregator::HandleSearchSourceResults(
    QuickInsertSearchSource source,
    std::vector<QuickInsertSearchResult> results,
    bool has_more_results) {
  CHECK(!current_callback_.is_null())
      << "Results were obtained after \"no more results\"";
  const QuickInsertSectionType section_type =
      SectionTypeFromSearchSource(source);
  UnpublishedResults& accumulated =
      accumulated_results_[base::to_underlying(section_type)];
  // Suggested results have multiple sources, which we store in any order and
  // explicitly do not append if post-burn-in.
  if (section_type == QuickInsertSectionType::kNone ||
      section_type == QuickInsertSectionType::kContentEditor) {
    // Suggested results cannot have more results, since it's not a proper
    // category.
    CHECK(!has_more_results);
    std::ranges::move(results, std::back_inserter(accumulated.results));
    return;
  }

  if (IsPostBurnIn()) {
    // Publish post-burn-in results and skip assignment.
    if (!results.empty()) {
      if (section_type == QuickInsertSectionType::kDriveFiles) {
        if (std::holds_alternative<std::monostate>(link_drive_dedupe_state_)) {
          link_drive_dedupe_state_ = DriveIdsFromSearchResults(results);
        } else if (auto* links = std::get_if<std::vector<GURL>>(
                       &link_drive_dedupe_state_)) {
          DeduplicateDriveFilesFromLinks(results, std::move(*links));
          link_drive_dedupe_state_ = std::monostate();
        } else {
          NOTREACHED();
        }
      } else if (section_type == QuickInsertSectionType::kLinks) {
        if (std::holds_alternative<std::monostate>(link_drive_dedupe_state_)) {
          link_drive_dedupe_state_ = LinksFromSearchResults(results);
        } else if (auto* drive_ids = std::get_if<std::vector<std::string>>(
                       &link_drive_dedupe_state_)) {
          DeduplicateDriveLinksFromIds(results, std::move(*drive_ids));
          link_drive_dedupe_state_ = std::monostate();
        } else {
          NOTREACHED();
        }
      }

      std::vector<QuickInsertSearchResultsSection> sections;
      sections.emplace_back(section_type, std::move(results), has_more_results);
      current_callback_.Run(std::move(sections));
    }
    return;
  }

  CHECK(accumulated.results.empty());
  accumulated = UnpublishedResults(std::move(results), has_more_results);
}

void QuickInsertSearchAggregator::HandleNoMoreResults(bool interrupted) {
  // Only call the callback if it wasn't interrupted.
  if (!interrupted) {
    // We could get a "no more results" signal before burn-in finishes.
    // Publish those results immediately if that is the case.
    if (burn_in_timer_.IsRunning()) {
      burn_in_timer_.FireNow();
    }
    current_callback_.Run({});
  }
  // Ensure that we don't accidentally publish more results afterwards.
  current_callback_.Reset();
}

QuickInsertSearchAggregator::UnpublishedResults::UnpublishedResults() = default;

QuickInsertSearchAggregator::UnpublishedResults::UnpublishedResults(
    std::vector<QuickInsertSearchResult> results,
    bool has_more)
    : results(std::move(results)), has_more(has_more) {}

QuickInsertSearchAggregator::UnpublishedResults::UnpublishedResults(
    UnpublishedResults&& other) = default;

QuickInsertSearchAggregator::UnpublishedResults&
QuickInsertSearchAggregator::UnpublishedResults::operator=(
    UnpublishedResults&& other) = default;

QuickInsertSearchAggregator::UnpublishedResults::~UnpublishedResults() =
    default;

bool QuickInsertSearchAggregator::IsPostBurnIn() const {
  return !burn_in_timer_.IsRunning();
}

void QuickInsertSearchAggregator::PublishBurnInResults() {
  // This variable should only be set after burn-in.
  CHECK(std::holds_alternative<std::monostate>(link_drive_dedupe_state_));

  UnpublishedResults* link_results =
      AccumulatedResultsForSection(QuickInsertSectionType::kLinks);
  UnpublishedResults* drive_results =
      AccumulatedResultsForSection(QuickInsertSectionType::kDriveFiles);
  if (link_results != nullptr && drive_results != nullptr) {
    DeduplicateDriveLinksFromIds(
        link_results->results,
        DriveIdsFromSearchResults(drive_results->results));
  } else if (link_results != nullptr) {
    // Link results came in before burn-in, and Drive results didn't.
    link_drive_dedupe_state_ = LinksFromSearchResults(link_results->results);
  } else if (drive_results != nullptr) {
    // Drive results came in before burn-in, and link results didn't.
    link_drive_dedupe_state_ =
        DriveIdsFromSearchResults(drive_results->results);
  }

  std::vector<QuickInsertSearchResultsSection> sections;
  base::flat_set<QuickInsertSectionType> published_types;

  // The None section always goes first.
  if (UnpublishedResults* none_results =
          AccumulatedResultsForSection(QuickInsertSectionType::kNone)) {
    sections.emplace_back(QuickInsertSectionType::kNone,
                          std::move(none_results->results),
                          /*has_more=*/false);
    published_types.insert(QuickInsertSectionType::kNone);
  }

  // User generated results can be ranked amongst themselves.
  for (QuickInsertSectionType type : {
           QuickInsertSectionType::kLinks,
           QuickInsertSectionType::kDriveFiles,
           QuickInsertSectionType::kLocalFiles,
           QuickInsertSectionType::kClipboard,
       }) {
    if (UnpublishedResults* results = AccumulatedResultsForSection(type);
        results && std::ranges::any_of(results->results, &ShouldPromote)) {
      sections.emplace_back(type, std::move(results->results),
                            results->has_more);
      published_types.insert(type);
    }
  }

  // The remaining results are ranked based on a predefined order
  for (QuickInsertSectionType type : {
           QuickInsertSectionType::kLinks,
           QuickInsertSectionType::kDriveFiles,
           QuickInsertSectionType::kLocalFiles,
           QuickInsertSectionType::kClipboard,
           QuickInsertSectionType::kContentEditor,
           QuickInsertSectionType::kSearchedGifs,
       }) {
    if (published_types.contains(type)) {
      continue;
    }
    if (UnpublishedResults* results = AccumulatedResultsForSection(type)) {
      sections.emplace_back(type, std::move(results->results),
                            results->has_more);
    }
  }
  if (!sections.empty()) {
    current_callback_.Run(std::move(sections));
  }
}

base::WeakPtr<QuickInsertSearchAggregator>
QuickInsertSearchAggregator::GetWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

QuickInsertSearchAggregator::UnpublishedResults*
QuickInsertSearchAggregator::AccumulatedResultsForSection(
    QuickInsertSectionType type) {
  UnpublishedResults& accumulated =
      accumulated_results_[base::to_underlying(type)];
  if (accumulated.results.empty()) {
    return nullptr;
  }
  return &accumulated;
}

}  // namespace ash