File: simple_scan_runner.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 (308 lines) | stat: -rw-r--r-- 11,454 bytes parent folder | download | duplicates (5)
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
// Copyright 2025 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/extensions/api/document_scan/simple_scan_runner.h"

#include "base/base64.h"
#include "base/containers/contains.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/extensions/extensions_dialogs.h"
#include "chrome/common/pref_names.h"
#include "chromeos/crosapi/mojom/document_scan.mojom.h"
#include "components/prefs/pref_service.h"
#include "extensions/browser/image_loader.h"
#include "extensions/common/extension.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/native_window_tracker.h"

namespace extensions {

namespace {

// Error messages that can be included in a response when scanning fails.
constexpr char kNoScannersAvailableError[] = "No scanners available";
constexpr char kScanImageError[] = "Failed to scan image";
constexpr char kUnsupportedMimeTypesError[] = "Unsupported MIME types";
constexpr char kVirtualPrinterUnavailableError[] =
    "Virtual USB printer unavailable";

// Special MIME type that triggers use of virtual-usb-printer for scanning.
constexpr char kTestingMimeType[] = "testing";

// The name of the virtual USB printer used for testing.
constexpr char kVirtualUSBPrinter[] = "DavieV Virtual USB Printer (USB)";

// The PNG MIME type.
constexpr char kScannerImageMimeTypePng[] = "image/png";

// The PNG image data URL prefix of a scanned image.
constexpr char kPngImageDataUrlPrefix[] = "data:image/png;base64,";

// The delay between reads from the scanner when data isn't expected to be ready
// immediately.
constexpr base::TimeDelta kSlowReadInterval = base::Milliseconds(500);

// The delay between reads from the scanner when data might be ready.
constexpr base::TimeDelta kReadInterval = base::Milliseconds(100);

// The connection type name for Mopria eSCL scanners.
constexpr char kMopriaProtocolName[] = "Mopria";

}  // namespace

SimpleScanRunner::SimpleScanRunner(scoped_refptr<const Extension> extension,
                                   crosapi::mojom::DocumentScan* document_scan)
    : extension_(std::move(extension)), document_scan_(document_scan) {
  CHECK(extension_);
}

SimpleScanRunner::~SimpleScanRunner() = default;

void SimpleScanRunner::Start(std::vector<std::string> mime_types,
                             SimpleScanCallback callback) {
  CHECK(!callback_) << "scan call already in progress";
  callback_ = std::move(callback);
  mime_types_ = std::move(mime_types);

  // Clear any leftover state from a previous scan.
  scanner_ids_.clear();
  scanner_handle_ = "";
  job_handle_ = "";
  scan_data_.clear();
  scan_result_ = crosapi::mojom::ScanFailureMode::kUnknown;

  bool should_use_virtual_usb_printer = false;
  if (base::Contains(mime_types_, kTestingMimeType)) {
    should_use_virtual_usb_printer = true;
  } else if (!base::Contains(mime_types_, kScannerImageMimeTypePng)) {
    std::move(callback_).Run(std::nullopt, kUnsupportedMimeTypesError);
    return;
  }

  auto filter = crosapi::mojom::ScannerEnumFilter::New();
  document_scan_->GetScannerList(
      extension_id(), std::move(filter),
      base::BindOnce(&SimpleScanRunner::OnSimpleScanListReceived,
                     weak_ptr_factory_.GetWeakPtr(),
                     should_use_virtual_usb_printer));
}

const ExtensionId& SimpleScanRunner::extension_id() const {
  return extension_->id();
}

void SimpleScanRunner::OnSimpleScanListReceived(
    bool force_virtual_usb_printer,
    crosapi::mojom::GetScannerListResponsePtr response) {
  if (response->scanners.empty()) {
    std::move(callback_).Run(std::nullopt, kNoScannersAvailableError);
    return;
  }

  // A scanner source needs to be chosen.  Since the choice is unspecified, sort
  // the list with these heuristics and take the first one that can be
  // successfully opened:
  //   1.  If force_virtual_usb_printer is true, always pick the virtual USB
  //       printer.
  //   2.  USB scanners come first, since they are both local and secure.
  //   3.  Secure network scanners come next.
  //   4.  Insecure network scanners come last.
  // Within each grouping, prefer Mopria eSCL to legacy protocols, since the
  // backend is known to work consistently.
  std::stable_sort(
      response->scanners.begin(), response->scanners.end(),
      [](const crosapi::mojom::ScannerInfoPtr& a,
         const crosapi::mojom::ScannerInfoPtr& b) {
        // a < a returns false by std::sort requirement.
        if (a->id == b->id) {
          return false;
        }

        // Virtual USB printer always comes first.
        if (a->display_name == kVirtualUSBPrinter) {
          return true;
        } else if (b->display_name == kVirtualUSBPrinter) {
          return false;
        }

        // USB devices come first.
        if (a->connection_type != b->connection_type) {
          if (a->connection_type ==
              crosapi::mojom::ScannerInfo::ConnectionType::kUsb) {
            return true;
          } else if (b->connection_type ==
                     crosapi::mojom::ScannerInfo::ConnectionType::kUsb) {
            return false;
          }
        }

        // Secure devices come before insecure.
        if (a->secure != b->secure) {
          if (a->secure) {
            return true;
          } else if (b->secure) {
            return false;
          }
        }

        // Mopria/eSCL devices come before legacy devices.
        if (a->protocol_type != b->protocol_type) {
          if (a->protocol_type.has_value() &&
              a->protocol_type.value() == kMopriaProtocolName) {
            return true;
          } else if (b->protocol_type.has_value() &&
                     b->protocol_type.value() == kMopriaProtocolName) {
            return false;
          }
        }

        // Sort by display name if all else is equal.
        return a->display_name < b->display_name;
      });

  if (force_virtual_usb_printer &&
      response->scanners[0]->display_name != kVirtualUSBPrinter) {
    std::move(callback_).Run(std::nullopt, kVirtualPrinterUnavailableError);
    return;
  }

  // Store the list of IDs in reverse so it can be processed more efficiently in
  // the callbacks.  The rest of the ScannerInfo fields aren't needed.
  scanner_ids_.reserve(response->scanners.size());
  for (ssize_t i = response->scanners.size() - 1; i >= 0; i--) {
    if (force_virtual_usb_printer &&
        response->scanners[i]->display_name != kVirtualUSBPrinter) {
      continue;
    }
    scanner_ids_.push_back(std::move(response->scanners[i]->id));
  }

  OpenFirstScanner();
}

void SimpleScanRunner::OpenFirstScanner() {
  if (scanner_ids_.empty()) {
    std::move(callback_).Run(std::nullopt, kNoScannersAvailableError);
    return;
  }

  std::string scanner_id = std::move(scanner_ids_.back());
  scanner_ids_.pop_back();
  document_scan_->OpenScanner(
      extension_id(), std::move(scanner_id),
      base::BindOnce(&SimpleScanRunner::OnOpenScannerResponse,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SimpleScanRunner::OnOpenScannerResponse(
    crosapi::mojom::OpenScannerResponsePtr response) {
  if (response->result != crosapi::mojom::ScannerOperationResult::kSuccess ||
      !response->scanner_handle.has_value()) {
    OpenFirstScanner();
    return;
  }
  scanner_handle_ = std::move(response->scanner_handle.value());

  auto options = crosapi::mojom::StartScanOptions::New();
  options->format = kScannerImageMimeTypePng;

  document_scan_->StartPreparedScan(
      scanner_handle_, std::move(options),
      base::BindOnce(&SimpleScanRunner::OnStartPreparedScanResponse,
                     weak_ptr_factory_.GetWeakPtr()));
}

void SimpleScanRunner::OnStartPreparedScanResponse(
    crosapi::mojom::StartPreparedScanResponsePtr response) {
  if (response->result != crosapi::mojom::ScannerOperationResult::kSuccess ||
      !response->job_handle.has_value()) {
    // Closing the scanner will also return the response to the caller.
    document_scan_->CloseScanner(
        scanner_handle_,
        base::BindOnce(&SimpleScanRunner::OnCloseScannerResponse,
                       weak_ptr_factory_.GetWeakPtr()));
    return;
  }

  // Scanners normally don't produce bytes right away, so start the read loop
  // after a delay.
  job_handle_ = std::move(response->job_handle.value());
  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&SimpleScanRunner::ReadScanData,
                     weak_ptr_factory_.GetWeakPtr()),
      kSlowReadInterval);
}

void SimpleScanRunner::ReadScanData() {
  document_scan_->ReadScanData(
      job_handle_, base::BindOnce(&SimpleScanRunner::OnReadScanDataResponse,
                                  weak_ptr_factory_.GetWeakPtr()));
}

void SimpleScanRunner::OnReadScanDataResponse(
    crosapi::mojom::ReadScanDataResponsePtr response) {
  // Success means to keep going.  If data was ready, append it to what we got
  // so far.
  if (response->result == crosapi::mojom::ScannerOperationResult::kSuccess) {
    if (response->data.has_value() && response->data->size() > 0) {
      scan_data_.insert(scan_data_.end(), response->data->begin(),
                        response->data->end());
    }

    // Once the first byte after the image headers is received, poll the scanner
    // more quickly because data usually streams consistently.
    base::TimeDelta delay =
        (scan_data_.size() > 100) ? kReadInterval : kSlowReadInterval;
    base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&SimpleScanRunner::ReadScanData,
                       weak_ptr_factory_.GetWeakPtr()),
        delay);
    return;
  }

  // EOF means no more data is available.  There might be a final data chunk.
  if (response->result == crosapi::mojom::ScannerOperationResult::kEndOfData) {
    if (response->data.has_value() && response->data->size() > 0) {
      scan_data_.insert(scan_data_.end(), response->data->begin(),
                        response->data->end());
    }

    scan_result_ = crosapi::mojom::ScanFailureMode::kNoFailure;
  }

  document_scan_->CloseScanner(
      scanner_handle_, base::BindOnce(&SimpleScanRunner::OnCloseScannerResponse,
                                      weak_ptr_factory_.GetWeakPtr()));
}

void SimpleScanRunner::OnCloseScannerResponse(
    crosapi::mojom::CloseScannerResponsePtr) {
  // Intentionally ignore the response.  The result to return to the caller has
  // already been determined at the end of the read loop.
  OnSimpleScanCompleted(scan_result_);
}

void SimpleScanRunner::OnSimpleScanCompleted(
    crosapi::mojom::ScanFailureMode failure_mode) {
  if (!scan_data_.size() ||
      failure_mode != crosapi::mojom::ScanFailureMode::kNoFailure) {
    std::move(callback_).Run(std::nullopt, kScanImageError);
    return;
  }

  std::string image_base64 = base::Base64Encode(scan_data_);
  api::document_scan::ScanResults scan_results;
  scan_results.data_urls.push_back(kPngImageDataUrlPrefix +
                                   std::move(image_base64));
  scan_results.mime_type = kScannerImageMimeTypePng;

  std::move(callback_).Run(std::move(scan_results), std::nullopt);
}

}  // namespace extensions