1 // Copyright 2013 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 "gin/modules/file_module_provider.h"
6
7 #include "base/bind.h"
8 #include "base/file_util.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/strings/string_split.h"
11 #include "gin/converter.h"
12
13 namespace gin {
14
15 namespace {
16
AttempToLoadModule(const base::WeakPtr<Runner> & runner,const std::vector<base::FilePath> & search_paths,const std::string & id)17 void AttempToLoadModule(const base::WeakPtr<Runner>& runner,
18 const std::vector<base::FilePath>& search_paths,
19 const std::string& id) {
20 if (!runner)
21 return;
22
23 std::vector<std::string> components;
24 base::SplitString(id, '/', &components);
25
26 base::FilePath path;
27 for (size_t i = 0; i < components.size(); ++i) {
28 // TODO(abarth): Technically the path components can be UTF-8. We don't
29 // handle that case correctly yet.
30 path = path.AppendASCII(components[i]);
31 }
32 path = path.AddExtension(FILE_PATH_LITERAL("js"));
33
34 for (size_t i = 0; i < search_paths.size(); ++i) {
35 std::string source;
36 if (!ReadFileToString(search_paths[i].Append(path), &source))
37 continue;
38
39 Runner::Scope scope(runner.get());
40 v8::Handle<v8::Script> script = v8::Script::New(
41 StringToV8(runner->isolate(), source),
42 StringToV8(runner->isolate(), id));
43 runner->Run(script);
44 return;
45 }
46 }
47
48 } // namespace
49
FileModuleProvider(const std::vector<base::FilePath> & search_paths)50 FileModuleProvider::FileModuleProvider(
51 const std::vector<base::FilePath>& search_paths)
52 : search_paths_(search_paths) {
53 }
54
~FileModuleProvider()55 FileModuleProvider::~FileModuleProvider() {
56 }
57
AttempToLoadModules(Runner * runner,const std::set<std::string> & ids)58 void FileModuleProvider::AttempToLoadModules(
59 Runner* runner, const std::set<std::string>& ids) {
60 std::set<std::string> modules = ids;
61 for (std::set<std::string>::const_iterator it = modules.begin();
62 it != modules.end(); ++it) {
63 const std::string& id = *it;
64 if (attempted_ids_.count(id))
65 continue;
66 attempted_ids_.insert(id);
67 base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
68 AttempToLoadModule, runner->GetWeakPtr(), search_paths_, id));
69 }
70 }
71
72 } // namespace gin
73