1 // Copyright 2015 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.
5 #include "components/resource_provider/public/cpp/resource_loader.h"
8 #include "base/files/file.h"
9 #include "mojo/application/public/cpp/connect.h"
10 #include "mojo/application/public/interfaces/service_provider.mojom.h"
11 #include "mojo/application/public/interfaces/shell.mojom.h"
12 #include "mojo/common/common_type_converters.h"
13 #include "mojo/platform_handle/platform_handle_functions.h"
15 namespace resource_provider
{
17 base::File
GetFileFromHandle(mojo::ScopedHandle handle
) {
18 CHECK(handle
.is_valid());
19 MojoPlatformHandle platform_handle
;
20 CHECK(MojoExtractPlatformHandle(handle
.release().value(),
21 &platform_handle
) == MOJO_RESULT_OK
);
22 return base::File(platform_handle
).Pass();
26 ResourceLoader::ResourceLoader(mojo::Shell
* shell
,
27 const std::set
<std::string
>& paths
)
28 : loaded_(false), did_block_(false) {
29 mojo::URLRequestPtr
request(mojo::URLRequest::New());
30 request
->url
= mojo::String::From("mojo:resource_provider");
31 mojo::ServiceProviderPtr resource_provider_service_provider
;
32 shell
->ConnectToApplication(
33 request
.Pass(), GetProxy(&resource_provider_service_provider
), nullptr,
34 nullptr, mojo::Shell::ConnectToApplicationCallback());
35 mojo::ConnectToService(resource_provider_service_provider
.get(),
37 std::vector
<std::string
> paths_vector(paths
.begin(), paths
.end());
38 resource_provider_
->GetResources(
39 mojo::Array
<mojo::String
>::From(paths_vector
),
40 base::Bind(&ResourceLoader::OnGotResources
, base::Unretained(this),
44 ResourceLoader::~ResourceLoader() {
47 bool ResourceLoader::BlockUntilLoaded() {
48 if (did_block_
|| loaded_
)
52 resource_provider_
.WaitForIncomingResponse();
56 base::File
ResourceLoader::ReleaseFile(const std::string
& path
) {
57 CHECK(resource_map_
.count(path
));
58 scoped_ptr
<base::File
> file_wrapper(resource_map_
[path
].Pass());
59 resource_map_
.erase(path
);
60 return file_wrapper
->Pass();
63 base::File
ResourceLoader::GetICUFile() {
65 resource_provider_
->GetICUHandle(
66 base::Bind(&ResourceLoader::OnGotICU
, base::Unretained(this), &rv
));
67 resource_provider_
.WaitForIncomingResponse();
72 void ResourceLoader::OnGotResources(const std::vector
<std::string
>& paths
,
73 mojo::Array
<mojo::ScopedHandle
> resources
) {
75 CHECK(!resources
.is_null());
76 CHECK_EQ(resources
.size(), paths
.size());
77 for (size_t i
= 0; i
< resources
.size(); ++i
) {
78 resource_map_
[paths
[i
]].reset(
79 new base::File(GetFileFromHandle(resources
[i
].Pass())));
84 void ResourceLoader::OnGotICU(base::File
* file
, mojo::ScopedHandle handle
) {
85 *file
= GetFileFromHandle(handle
.Pass());
88 } // namespace resource_provider