#include "base/command_line.h"
#include "base/logging.h"
#include "base/process/launch.h"
#include "base/run_loop.h"
#include "codelabs/mojo_examples/mojom/interface.mojom.h"
#include "codelabs/mojo_examples/process_bootstrapper.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/platform/platform_channel.h"
#include "mojo/public/cpp/system/invitation.h"
#include "mojo/public/cpp/system/message_pipe.h"
mojo::ScopedMessagePipeHandle LaunchAndConnect() {
mojo::PlatformChannel channel;
mojo::OutgoingInvitation invitation;
mojo::ScopedMessagePipeHandle pipe = invitation.AttachMessagePipe("pipe");
base::LaunchOptions options;
static const base::CommandLine::CharType* argv[] = {
FILE_PATH_LITERAL("./01-mojo-renderer")};
base::CommandLine command_line(1, argv);
channel.PrepareToPassRemoteEndpoint(&options, &command_line);
LOG(INFO) << "Browser: " << command_line.GetCommandLineString();
base::Process child_process = base::LaunchProcess(command_line, options);
channel.RemoteProcessLaunchAttempted();
mojo::OutgoingInvitation::Send(std::move(invitation), child_process.Handle(),
channel.TakeLocalEndpoint());
return pipe;
}
void CreateProcessRemote(mojo::ScopedMessagePipeHandle pipe) {
mojo::PendingRemote<codelabs::mojom::Process> pending_remote(std::move(pipe),
0u);
mojo::Remote<codelabs::mojom::Process> remote(std::move(pending_remote));
LOG(INFO) << "Browser invoking SayHello() on remote pointing to renderer";
remote->SayHello();
}
int main(int argc, char** argv) {
LOG(INFO) << "'Browser process' starting up";
base::CommandLine::Init(argc, argv);
ProcessBootstrapper bootstrapper;
bootstrapper.InitMainThread(base::MessagePumpType::IO);
bootstrapper.InitMojo(true);
mojo::ScopedMessagePipeHandle pipe = LaunchAndConnect();
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&CreateProcessRemote, std::move(pipe)));
base::RunLoop run_loop;
base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(
[](base::OnceClosure quit_closure) {
LOG(INFO) << "'Browser process' shutting down";
std::move(quit_closure).Run();
},
run_loop.QuitClosure()),
base::Seconds(2));
run_loop.Run();
return 0;
}