1// Copyright (c) 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/importer/external_process_importer_host.h"
6
7#include "chrome/browser/bookmarks/bookmark_model.h"
8#include "chrome/browser/importer/external_process_importer_client.h"
9#include "chrome/browser/importer/in_process_importer_bridge.h"
10
11ExternalProcessImporterHost::ExternalProcessImporterHost()
12    : items_(0),
13      import_to_bookmark_bar_(false),
14      cancelled_(false),
15      import_process_launched_(false) {
16}
17
18void ExternalProcessImporterHost::Cancel() {
19  cancelled_ = true;
20  if (import_process_launched_)
21    client_->Cancel();
22  NotifyImportEnded();  // Tells the observer that we're done, and releases us.
23}
24
25void ExternalProcessImporterHost::StartImportSettings(
26    const importer::SourceProfile& source_profile,
27    Profile* target_profile,
28    uint16 items,
29    ProfileWriter* writer,
30    bool first_run) {
31  DCHECK(!profile_);
32  profile_ = target_profile;
33  writer_ = writer;
34  source_profile_ = &source_profile;
35  items_ = items;
36
37  ImporterHost::AddRef();  // Balanced in ImporterHost::NotifyImportEnded.
38
39  import_to_bookmark_bar_ = ShouldImportToBookmarkBar(first_run);
40  CheckForFirefoxLock(source_profile, items, first_run);
41  CheckForLoadedModels(items);
42
43  InvokeTaskIfDone();
44}
45
46void ExternalProcessImporterHost::InvokeTaskIfDone() {
47  if (waiting_for_bookmarkbar_model_ || !registrar_.IsEmpty() ||
48      !is_source_readable_ || cancelled_)
49    return;
50
51  // This is the in-process half of the bridge, which catches data from the IPC
52  // pipe and feeds it to the ProfileWriter. The external process half of the
53  // bridge lives in the external process (see ProfileImportThread).
54  // The ExternalProcessImporterClient created in the next line owns the bridge,
55  // and will delete it.
56  InProcessImporterBridge* bridge =
57      new InProcessImporterBridge(writer_.get(), this);
58  client_ = new ExternalProcessImporterClient(
59      this, *source_profile_, items_, bridge, import_to_bookmark_bar_);
60  import_process_launched_ = true;
61  client_->Start();
62}
63
64void ExternalProcessImporterHost::Loaded(BookmarkModel* model) {
65  DCHECK(model->IsLoaded());
66  model->RemoveObserver(this);
67  waiting_for_bookmarkbar_model_ = false;
68  installed_bookmark_observer_ = false;
69
70  // Because the import process is running externally, the decision whether
71  // to import to the bookmark bar must be stored here so that it can be
72  // passed to the importer when the import task is invoked.
73  import_to_bookmark_bar_ = (!model->HasBookmarks());
74  InvokeTaskIfDone();
75}
76