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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/api/printer_provider/printer_provider_api.h"
#include <map>
#include <set>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/json/json_string_value_serializer.h"
#include "base/macros.h"
#include "base/memory/ref_counted_memory.h"
#include "base/scoped_observer.h"
#include "base/values.h"
#include "extensions/browser/api/printer_provider/printer_provider_print_job.h"
#include "extensions/browser/api/printer_provider_internal/printer_provider_internal_api.h"
#include "extensions/browser/api/printer_provider_internal/printer_provider_internal_api_observer.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_observer.h"
#include "extensions/common/api/printer_provider.h"
#include "extensions/common/api/printer_provider_internal.h"
#include "extensions/common/extension.h"
namespace extensions {
namespace {
// The separator between extension id and the extension's internal printer id
// used when generating a printer id unique across extensions.
const char kPrinterIdSeparator = ':';
// Given an extension ID and an ID of a printer reported by the extension, it
// generates a ID for the printer unique across extensions (assuming that the
// printer id is unique in the extension's space).
std::string GeneratePrinterId(const std::string& extension_id,
const std::string& internal_printer_id) {
std::string result = extension_id;
result.append(1, kPrinterIdSeparator);
result.append(internal_printer_id);
return result;
}
// Parses an ID created using |GeneratePrinterId| to it's components:
// the extension ID and the printer ID internal to the extension.
// Returns whenter the ID was succesfully parsed.
bool ParsePrinterId(const std::string& printer_id,
std::string* extension_id,
std::string* internal_printer_id) {
size_t separator = printer_id.find_first_of(kPrinterIdSeparator);
if (separator == std::string::npos)
return false;
*extension_id = printer_id.substr(0, separator);
*internal_printer_id = printer_id.substr(separator + 1);
return true;
}
// Holds information about a pending onGetPrintersRequested request;
// in particular, the list of extensions to which the event was dispatched but
// which haven't yet responded, and the |GetPrinters| callback associated with
// the event.
class GetPrintersRequest {
public:
explicit GetPrintersRequest(
const PrinterProviderAPI::GetPrintersCallback& callback);
~GetPrintersRequest();
// Adds an extension id to the list of the extensions that need to respond
// to the event.
void AddSource(const std::string& extension_id);
// Whether all extensions have responded to the event.
bool IsDone() const;
// Runs the callback for an extension and removes the extension from the
// list of extensions that still have to respond to the event.
void ReportForExtension(const std::string& extension_id,
const base::ListValue& printers);
private:
// Callback reporting event result for an extension. Called once for each
// extension.
PrinterProviderAPI::GetPrintersCallback callback_;
// The list of extensions that still have to respond to the event.
std::set<std::string> extensions_;
};
// Keeps track of pending chrome.printerProvider.onGetPrintersRequested
// requests.
class PendingGetPrintersRequests {
public:
PendingGetPrintersRequests();
~PendingGetPrintersRequests();
// Adds a new request to the set of pending requests. Returns the id
// assigned to the request.
int Add(const PrinterProviderAPI::GetPrintersCallback& callback);
// Completes a request for an extension. It runs the request callback with
// values reported by the extension.
bool CompleteForExtension(const std::string& extension_id,
int request_id,
const base::ListValue& result);
// Runs callbacks for the extension for all requests that are waiting for a
// response from the extension with the provided extension id. Callbacks are
// called as if the extension reported empty set of printers.
void FailAllForExtension(const std::string& extension_id);
// Adds an extension id to the list of the extensions that need to respond
// to the event.
bool AddSource(int request_id, const std::string& extension_id);
private:
int last_request_id_;
std::map<int, GetPrintersRequest> pending_requests_;
DISALLOW_COPY_AND_ASSIGN(PendingGetPrintersRequests);
};
// Keeps track of pending chrome.printerProvider.onGetCapabilityRequested
// requests for an extension.
class PendingGetCapabilityRequests {
public:
PendingGetCapabilityRequests();
~PendingGetCapabilityRequests();
// Adds a new request to the set. Only information needed is the callback
// associated with the request. Returns the id assigned to the request.
int Add(const PrinterProviderAPI::GetCapabilityCallback& callback);
// Completes the request with the provided request id. It runs the request
// callback and removes the request from the set.
bool Complete(int request_id, const base::DictionaryValue& result);
// Runs all pending callbacks with empty capability value and clears the
// set of pending requests.
void FailAll();
private:
int last_request_id_;
std::map<int, PrinterProviderAPI::GetCapabilityCallback> pending_requests_;
};
// Keeps track of pending chrome.printerProvider.ontPrintRequested requests
// for an extension.
class PendingPrintRequests {
public:
PendingPrintRequests();
~PendingPrintRequests();
// Adds a new request to the set. Only information needed is the callback
// associated with the request. Returns the id assigned to the request.
int Add(const PrinterProviderAPI::PrintCallback& callback);
// Completes the request with the provided request id. It runs the request
// callback and removes the request from the set.
bool Complete(int request_id, bool success, const std::string& result);
// Runs all pending callbacks with ERROR_FAILED and clears the set of
// pending requests.
void FailAll();
private:
int last_request_id_;
std::map<int, PrinterProviderAPI::PrintCallback> pending_requests_;
};
// Implements chrome.printerProvider API events.
class PrinterProviderAPIImpl : public PrinterProviderAPI,
public PrinterProviderInternalAPIObserver,
public ExtensionRegistryObserver {
public:
explicit PrinterProviderAPIImpl(content::BrowserContext* browser_context);
~PrinterProviderAPIImpl() override;
private:
// PrinterProviderAPI implementation:
void DispatchGetPrintersRequested(
const PrinterProviderAPI::GetPrintersCallback& callback) override;
void DispatchGetCapabilityRequested(
const std::string& printer_id,
const PrinterProviderAPI::GetCapabilityCallback& callback) override;
void DispatchPrintRequested(
const PrinterProviderPrintJob& job,
const PrinterProviderAPI::PrintCallback& callback) override;
// PrinterProviderInternalAPIObserver implementation:
void OnGetPrintersResult(
const Extension* extension,
int request_id,
const PrinterProviderInternalAPIObserver::PrinterInfoVector& result)
override;
void OnGetCapabilityResult(const Extension* extension,
int request_id,
const base::DictionaryValue& result) override;
void OnPrintResult(
const Extension* extension,
int request_id,
core_api::printer_provider_internal::PrintError error) override;
// ExtensionRegistryObserver implementation:
void OnExtensionUnloaded(content::BrowserContext* browser_context,
const Extension* extension,
UnloadedExtensionInfo::Reason reason) override;
// Called before chrome.printerProvider.onGetPrintersRequested event is
// dispatched to an extension. It returns whether the extension is interested
// in the event. If the extension listens to the event, it's added to the set
// of |request| sources. |request| is |GetPrintersRequest| object associated
// with the event.
bool WillRequestPrinters(int request_id,
content::BrowserContext* browser_context,
const Extension* extension,
base::ListValue* args);
content::BrowserContext* browser_context_;
PendingGetPrintersRequests pending_get_printers_requests_;
std::map<std::string, PendingPrintRequests> pending_print_requests_;
std::map<std::string, PendingGetCapabilityRequests>
pending_capability_requests_;
ScopedObserver<PrinterProviderInternalAPI, PrinterProviderInternalAPIObserver>
internal_api_observer_;
ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
extension_registry_observer_;
DISALLOW_COPY_AND_ASSIGN(PrinterProviderAPIImpl);
};
GetPrintersRequest::GetPrintersRequest(
const PrinterProviderAPI::GetPrintersCallback& callback)
: callback_(callback) {
}
GetPrintersRequest::~GetPrintersRequest() {
}
void GetPrintersRequest::AddSource(const std::string& extension_id) {
extensions_.insert(extension_id);
}
bool GetPrintersRequest::IsDone() const {
return extensions_.empty();
}
void GetPrintersRequest::ReportForExtension(const std::string& extension_id,
const base::ListValue& printers) {
if (extensions_.erase(extension_id) > 0)
callback_.Run(printers, IsDone());
}
PendingGetPrintersRequests::PendingGetPrintersRequests() : last_request_id_(0) {
}
PendingGetPrintersRequests::~PendingGetPrintersRequests() {
}
int PendingGetPrintersRequests::Add(
const PrinterProviderAPI::GetPrintersCallback& callback) {
pending_requests_.insert(
std::make_pair(++last_request_id_, GetPrintersRequest(callback)));
return last_request_id_;
}
bool PendingGetPrintersRequests::CompleteForExtension(
const std::string& extension_id,
int request_id,
const base::ListValue& result) {
auto it = pending_requests_.find(request_id);
if (it == pending_requests_.end())
return false;
it->second.ReportForExtension(extension_id, result);
if (it->second.IsDone()) {
pending_requests_.erase(it);
}
return true;
}
void PendingGetPrintersRequests::FailAllForExtension(
const std::string& extension_id) {
auto it = pending_requests_.begin();
while (it != pending_requests_.end()) {
int request_id = it->first;
// |it| may get deleted during |CompleteForExtension|, so progress it to the
// next item before calling the method.
++it;
CompleteForExtension(extension_id, request_id, base::ListValue());
}
}
bool PendingGetPrintersRequests::AddSource(int request_id,
const std::string& extension_id) {
auto it = pending_requests_.find(request_id);
if (it == pending_requests_.end())
return false;
it->second.AddSource(extension_id);
return true;
}
PendingGetCapabilityRequests::PendingGetCapabilityRequests()
: last_request_id_(0) {
}
PendingGetCapabilityRequests::~PendingGetCapabilityRequests() {
}
int PendingGetCapabilityRequests::Add(
const PrinterProviderAPI::GetCapabilityCallback& callback) {
pending_requests_[++last_request_id_] = callback;
return last_request_id_;
}
bool PendingGetCapabilityRequests::Complete(
int request_id,
const base::DictionaryValue& response) {
auto it = pending_requests_.find(request_id);
if (it == pending_requests_.end())
return false;
PrinterProviderAPI::GetCapabilityCallback callback = it->second;
pending_requests_.erase(it);
callback.Run(response);
return true;
}
void PendingGetCapabilityRequests::FailAll() {
for (auto& request : pending_requests_)
request.second.Run(base::DictionaryValue());
pending_requests_.clear();
}
PendingPrintRequests::PendingPrintRequests() : last_request_id_(0) {
}
PendingPrintRequests::~PendingPrintRequests() {
}
int PendingPrintRequests::Add(
const PrinterProviderAPI::PrintCallback& callback) {
pending_requests_[++last_request_id_] = callback;
return last_request_id_;
}
bool PendingPrintRequests::Complete(int request_id,
bool success,
const std::string& response) {
auto it = pending_requests_.find(request_id);
if (it == pending_requests_.end())
return false;
PrinterProviderAPI::PrintCallback callback = it->second;
pending_requests_.erase(it);
callback.Run(success, response);
return true;
}
void PendingPrintRequests::FailAll() {
for (auto& request : pending_requests_)
request.second.Run(false, PrinterProviderAPI::GetDefaultPrintError());
pending_requests_.clear();
}
PrinterProviderAPIImpl::PrinterProviderAPIImpl(
content::BrowserContext* browser_context)
: browser_context_(browser_context),
internal_api_observer_(this),
extension_registry_observer_(this) {
internal_api_observer_.Add(
PrinterProviderInternalAPI::GetFactoryInstance()->Get(browser_context));
extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context));
}
PrinterProviderAPIImpl::~PrinterProviderAPIImpl() {
}
void PrinterProviderAPIImpl::DispatchGetPrintersRequested(
const GetPrintersCallback& callback) {
EventRouter* event_router = EventRouter::Get(browser_context_);
if (!event_router->HasEventListener(
core_api::printer_provider::OnGetPrintersRequested::kEventName)) {
callback.Run(base::ListValue(), true /* done */);
return;
}
// |pending_get_printers_requests_| take ownership of |request| which gets
// NULLed out. Save the pointer before passing it to the requests, as it will
// be needed later on.
int request_id = pending_get_printers_requests_.Add(callback);
scoped_ptr<base::ListValue> internal_args(new base::ListValue);
// Request id is not part of the public API, but it will be massaged out in
// custom bindings.
internal_args->AppendInteger(request_id);
scoped_ptr<Event> event(
new Event(core_api::printer_provider::OnGetPrintersRequested::kEventName,
internal_args.Pass()));
// This callback is called synchronously during |BroadcastEvent|, so
// Unretained is safe.
event->will_dispatch_callback =
base::Bind(&PrinterProviderAPIImpl::WillRequestPrinters,
base::Unretained(this), request_id);
event_router->BroadcastEvent(event.Pass());
}
void PrinterProviderAPIImpl::DispatchGetCapabilityRequested(
const std::string& printer_id,
const PrinterProviderAPI::GetCapabilityCallback& callback) {
std::string extension_id;
std::string internal_printer_id;
if (!ParsePrinterId(printer_id, &extension_id, &internal_printer_id)) {
callback.Run(base::DictionaryValue());
return;
}
EventRouter* event_router = EventRouter::Get(browser_context_);
if (!event_router->ExtensionHasEventListener(
extension_id,
core_api::printer_provider::OnGetCapabilityRequested::kEventName)) {
callback.Run(base::DictionaryValue());
return;
}
int request_id = pending_capability_requests_[extension_id].Add(callback);
scoped_ptr<base::ListValue> internal_args(new base::ListValue);
// Request id is not part of the public API, but it will be massaged out in
// custom bindings.
internal_args->AppendInteger(request_id);
internal_args->AppendString(internal_printer_id);
scoped_ptr<Event> event(new Event(
core_api::printer_provider::OnGetCapabilityRequested::kEventName,
internal_args.Pass()));
event_router->DispatchEventToExtension(extension_id, event.Pass());
}
void PrinterProviderAPIImpl::DispatchPrintRequested(
const PrinterProviderPrintJob& job,
const PrinterProviderAPI::PrintCallback& callback) {
std::string extension_id;
std::string internal_printer_id;
if (!ParsePrinterId(job.printer_id, &extension_id, &internal_printer_id)) {
callback.Run(false, PrinterProviderAPI::GetDefaultPrintError());
return;
}
EventRouter* event_router = EventRouter::Get(browser_context_);
if (!event_router->ExtensionHasEventListener(
extension_id,
core_api::printer_provider::OnPrintRequested::kEventName)) {
callback.Run(false, PrinterProviderAPI::GetDefaultPrintError());
return;
}
core_api::printer_provider::PrintJob print_job;
print_job.printer_id = internal_printer_id;
JSONStringValueSerializer serializer(job.ticket_json);
scoped_ptr<base::Value> ticket_value(serializer.Deserialize(NULL, NULL));
if (!ticket_value ||
!core_api::printer_provider::PrintJob::Ticket::Populate(
*ticket_value, &print_job.ticket)) {
callback.Run(false,
core_api::printer_provider::ToString(
core_api::printer_provider::PRINT_ERROR_INVALID_TICKET));
return;
}
// TODO(tbarzic): Figure out how to support huge documents.
if (job.document_bytes->size() > PrinterProviderAPI::kMaxDocumentSize) {
callback.Run(false,
core_api::printer_provider::ToString(
core_api::printer_provider::PRINT_ERROR_INVALID_DATA));
return;
}
print_job.content_type = job.content_type;
print_job.document = std::vector<char>(
job.document_bytes->front(),
job.document_bytes->front() + job.document_bytes->size());
int request_id = pending_print_requests_[extension_id].Add(callback);
scoped_ptr<base::ListValue> internal_args(new base::ListValue);
// Request id is not part of the public API and it will be massaged out in
// custom bindings.
internal_args->AppendInteger(request_id);
internal_args->Append(print_job.ToValue().release());
scoped_ptr<Event> event(
new Event(core_api::printer_provider::OnPrintRequested::kEventName,
internal_args.Pass()));
event_router->DispatchEventToExtension(extension_id, event.Pass());
}
void PrinterProviderAPIImpl::OnGetPrintersResult(
const Extension* extension,
int request_id,
const PrinterProviderInternalAPIObserver::PrinterInfoVector& result) {
base::ListValue printer_list;
// Update some printer description properties to better identify the extension
// managing the printer.
for (size_t i = 0; i < result.size(); ++i) {
scoped_ptr<base::DictionaryValue> printer(result[i]->ToValue());
std::string internal_printer_id;
CHECK(printer->GetString("id", &internal_printer_id));
printer->SetString("id",
GeneratePrinterId(extension->id(), internal_printer_id));
printer->SetString("extensionId", extension->id());
printer_list.Append(printer.release());
}
pending_get_printers_requests_.CompleteForExtension(extension->id(),
request_id, printer_list);
}
void PrinterProviderAPIImpl::OnGetCapabilityResult(
const Extension* extension,
int request_id,
const base::DictionaryValue& result) {
pending_capability_requests_[extension->id()].Complete(request_id, result);
}
void PrinterProviderAPIImpl::OnPrintResult(
const Extension* extension,
int request_id,
core_api::printer_provider_internal::PrintError error) {
const std::string error_str =
error == core_api::printer_provider_internal::PRINT_ERROR_NONE
? PrinterProviderAPI::GetDefaultPrintError()
: core_api::printer_provider_internal::ToString(error);
pending_print_requests_[extension->id()].Complete(
request_id, error == core_api::printer_provider_internal::PRINT_ERROR_OK,
error_str);
}
void PrinterProviderAPIImpl::OnExtensionUnloaded(
content::BrowserContext* browser_context,
const Extension* extension,
UnloadedExtensionInfo::Reason reason) {
pending_get_printers_requests_.FailAllForExtension(extension->id());
auto print_it = pending_print_requests_.find(extension->id());
if (print_it != pending_print_requests_.end()) {
print_it->second.FailAll();
pending_print_requests_.erase(print_it);
}
auto capability_it = pending_capability_requests_.find(extension->id());
if (capability_it != pending_capability_requests_.end()) {
capability_it->second.FailAll();
pending_capability_requests_.erase(capability_it);
}
}
bool PrinterProviderAPIImpl::WillRequestPrinters(
int request_id,
content::BrowserContext* browser_context,
const Extension* extension,
base::ListValue* args) {
if (!extension)
return false;
EventRouter* event_router = EventRouter::Get(browser_context_);
if (!event_router->ExtensionHasEventListener(
extension->id(),
core_api::printer_provider::OnGetPrintersRequested::kEventName)) {
return false;
}
return pending_get_printers_requests_.AddSource(request_id, extension->id());
}
} // namespace
// static
PrinterProviderAPI* PrinterProviderAPI::Create(
content::BrowserContext* context) {
return new PrinterProviderAPIImpl(context);
}
// static
std::string PrinterProviderAPI::GetDefaultPrintError() {
return core_api::printer_provider_internal::ToString(
core_api::printer_provider_internal::PRINT_ERROR_FAILED);
}
} // namespace extensions
|