summaryrefslogtreecommitdiffstats
path: root/mojo/shell/app_container.cc
blob: 98aa6fab67dd1fb1c0f071b08f429a0fa57ac612 (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
// Copyright 2013 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 "mojo/shell/app_container.h"

#include "base/bind.h"
#include "base/callback_forward.h"
#include "base/callback_helpers.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/native_library.h"
#include "base/scoped_native_library.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/thread.h"
#include "mojo/public/system/core.h"
#include "mojo/services/native_viewport/native_viewport_impl.h"
#include "mojo/shell/context.h"

typedef MojoResult (*MojoMainFunction)(MojoHandle pipe);

namespace mojo {
namespace shell {

AppContainer::AppContainer(Context* context)
    : context_(context),
      weak_factory_(this) {
}

AppContainer::~AppContainer() {
}

void AppContainer::Load(const GURL& app_url) {
  request_ = context_->loader()->Load(app_url, this);
}

void AppContainer::DidCompleteLoad(const GURL& app_url,
                                   const base::FilePath& app_path) {
  CreateMessagePipe(&shell_handle_, &app_handle_);

  native_viewport_.reset(
    new services::NativeViewportImpl(context_, shell_handle_.Pass()));

  // Launch the app on its own thread.
  // TODO(beng): Create a unique thread name.
  app_path_ = app_path;
  ack_closure_ =
      base::Bind(&AppContainer::AppCompleted, weak_factory_.GetWeakPtr());
  thread_.reset(new base::DelegateSimpleThread(this, "app_thread"));
  thread_->Start();
}

void AppContainer::Run() {
  base::ScopedClosureRunner app_deleter(
      base::Bind(base::IgnoreResult(&base::DeleteFile), app_path_, false));
  base::ScopedNativeLibrary app_library(
      base::LoadNativeLibrary(app_path_, NULL));
  if (!app_library.is_valid()) {
    LOG(ERROR) << "Failed to load library: " << app_path_.value().c_str();
    return;
  }

  MojoMainFunction main_function = reinterpret_cast<MojoMainFunction>(
      app_library.GetFunctionPointer("MojoMain"));
  if (!main_function) {
    LOG(ERROR) << "Entrypoint MojoMain not found.";
    return;
  }

  // |MojoMain()| takes ownership of the app handle.
  MojoResult result = main_function(app_handle_.release().value());
  if (result < MOJO_RESULT_OK) {
    LOG(ERROR) << "MojoMain returned an error: " << result;
    return;
  }
  context_->task_runners()->ui_runner()->PostTask(FROM_HERE, ack_closure_);
}

void AppContainer::AppCompleted() {
  native_viewport_.reset();

  thread_->Join();
  thread_.reset();
}

}  // namespace shell
}  // namespace mojo