summaryrefslogtreecommitdiffstats
path: root/chrome/browser/extensions/api/api_function.cc
blob: 7bcbdc74450b2a33df7ee6ac16d8b17bf76b3cab (plain)
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
// Copyright (c) 2012 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 "chrome/browser/extensions/api/api_function.h"

#include "base/bind.h"
#include "chrome/browser/extensions/api/api_resource_event_notifier.h"
#include "chrome/browser/profiles/profile.h"

using content::BrowserThread;

namespace extensions {

AsyncApiFunction::AsyncApiFunction()
    : work_thread_id_(BrowserThread::IO) {
}

AsyncApiFunction::~AsyncApiFunction() {
}

bool AsyncApiFunction::RunImpl() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!PrePrepare() || !Prepare()) {
    return false;
  }
  bool rv = BrowserThread::PostTask(
      work_thread_id_, FROM_HERE,
      base::Bind(&AsyncApiFunction::WorkOnWorkThread, this));
  DCHECK(rv);
  return true;
}

bool AsyncApiFunction::PrePrepare() {
  return true;
}

void AsyncApiFunction::Work() {
}

void AsyncApiFunction::AsyncWorkStart() {
  Work();
  AsyncWorkCompleted();
}

void AsyncApiFunction::AsyncWorkCompleted() {
  if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    bool rv = BrowserThread::PostTask(
        BrowserThread::UI, FROM_HERE,
        base::Bind(&AsyncApiFunction::RespondOnUIThread, this));
    DCHECK(rv);
  } else {
    SendResponse(Respond());
  }
}

void AsyncApiFunction::WorkOnWorkThread() {
  DCHECK(BrowserThread::CurrentlyOn(work_thread_id_));
  DCHECK(work_thread_id_ != BrowserThread::UI) <<
      "You have specified that AsyncApiFunction::Work() should happen on "
      "the UI thread. This nullifies the point of this class. Either "
      "specify a different thread or derive from a different class.";
  AsyncWorkStart();
}

void AsyncApiFunction::RespondOnUIThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  SendResponse(Respond());
}

int AsyncApiFunction::ExtractSrcId(const DictionaryValue* options) {
  int src_id = -1;
  if (options) {
    if (options->HasKey(kSrcIdKey))
      EXTENSION_FUNCTION_VALIDATE(options->GetInteger(kSrcIdKey, &src_id));
  }
  return src_id;
}

ApiResourceEventNotifier* AsyncApiFunction::CreateEventNotifier(int src_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return new ApiResourceEventNotifier(
      profile()->GetExtensionEventRouter(), profile(), extension_id(),
      src_id, source_url());
}

}  // namespace extensions