• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The Chromium Embedded Framework Authors. Portions copyright
2 // 2013 The Chromium Authors. All rights reserved. Use of this source code is
3 // governed by a BSD-style license that can be found in the LICENSE file.
4 
5 #include "libcef/browser/devtools/devtools_file_manager.h"
6 
7 #include "libcef/browser/alloy/alloy_browser_host_impl.h"
8 
9 #include "base/bind.h"
10 #include "base/callback.h"
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/json/json_writer.h"
14 #include "base/lazy_instance.h"
15 #include "base/path_service.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/task/post_task.h"
18 #include "base/task/thread_pool.h"
19 #include "base/threading/sequenced_task_runner_handle.h"
20 #include "base/util/values/values_util.h"
21 #include "base/values.h"
22 #include "chrome/common/pref_names.h"
23 #include "components/prefs/scoped_user_pref_update.h"
24 #include "content/public/browser/web_contents.h"
25 
26 namespace {
27 
28 base::LazyInstance<base::FilePath>::Leaky g_last_save_path =
29     LAZY_INSTANCE_INITIALIZER;
30 
WriteToFile(const base::FilePath & path,const std::string & content)31 void WriteToFile(const base::FilePath& path, const std::string& content) {
32   DCHECK(!path.empty());
33   base::WriteFile(path, content.c_str(), content.length());
34 }
35 
AppendToFile(const base::FilePath & path,const std::string & content)36 void AppendToFile(const base::FilePath& path, const std::string& content) {
37   DCHECK(!path.empty());
38   base::AppendToFile(path, content.c_str(), content.size());
39 }
40 
41 }  // namespace
42 
CefDevToolsFileManager(AlloyBrowserHostImpl * browser_impl,PrefService * prefs)43 CefDevToolsFileManager::CefDevToolsFileManager(
44     AlloyBrowserHostImpl* browser_impl,
45     PrefService* prefs)
46     : browser_impl_(browser_impl),
47       prefs_(prefs),
48       file_task_runner_(
49           base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})),
50       weak_factory_(this) {}
51 
SaveToFile(const std::string & url,const std::string & content,bool save_as)52 void CefDevToolsFileManager::SaveToFile(const std::string& url,
53                                         const std::string& content,
54                                         bool save_as) {
55   Save(url, content, save_as,
56        base::Bind(&CefDevToolsFileManager::FileSavedAs,
57                   weak_factory_.GetWeakPtr(), url),
58        base::Bind(&CefDevToolsFileManager::CanceledFileSaveAs,
59                   weak_factory_.GetWeakPtr(), url));
60 }
61 
AppendToFile(const std::string & url,const std::string & content)62 void CefDevToolsFileManager::AppendToFile(const std::string& url,
63                                           const std::string& content) {
64   Append(url, content,
65          base::Bind(&CefDevToolsFileManager::AppendedTo,
66                     weak_factory_.GetWeakPtr(), url));
67 }
68 
Save(const std::string & url,const std::string & content,bool save_as,const SaveCallback & saveCallback,const CancelCallback & cancelCallback)69 void CefDevToolsFileManager::Save(const std::string& url,
70                                   const std::string& content,
71                                   bool save_as,
72                                   const SaveCallback& saveCallback,
73                                   const CancelCallback& cancelCallback) {
74   auto it = saved_files_.find(url);
75   if (it != saved_files_.end() && !save_as) {
76     SaveAsFileSelected(url, content, saveCallback, it->second);
77     return;
78   }
79 
80   const base::DictionaryValue* file_map =
81       prefs_->GetDictionary(prefs::kDevToolsEditedFiles);
82   base::FilePath initial_path;
83 
84   const base::Value* path_value;
85   if (file_map->Get(base::MD5String(url), &path_value)) {
86     base::Optional<base::FilePath> path = util::ValueToFilePath(*path_value);
87     if (path)
88       initial_path = std::move(*path);
89   }
90 
91   if (initial_path.empty()) {
92     GURL gurl(url);
93     std::string suggested_file_name =
94         gurl.is_valid() ? gurl.ExtractFileName() : url;
95 
96     if (suggested_file_name.length() > 64)
97       suggested_file_name = suggested_file_name.substr(0, 64);
98 
99     if (!g_last_save_path.Pointer()->empty()) {
100       initial_path = g_last_save_path.Pointer()->DirName().AppendASCII(
101           suggested_file_name);
102     } else {
103       // Use the temp directory. It may be an empty value.
104       base::PathService::Get(base::DIR_TEMP, &initial_path);
105       initial_path = initial_path.AppendASCII(suggested_file_name);
106     }
107   }
108 
109   CefFileDialogRunner::FileChooserParams params;
110   params.mode = blink::mojom::FileChooserParams::Mode::kSave;
111   if (!initial_path.empty()) {
112     params.default_file_name = initial_path;
113     if (!initial_path.Extension().empty()) {
114       params.accept_types.push_back(CefString(initial_path.Extension()));
115     }
116   }
117 
118   browser_impl_->RunFileChooser(
119       params, base::Bind(&CefDevToolsFileManager::SaveAsDialogDismissed,
120                          weak_factory_.GetWeakPtr(), url, content, saveCallback,
121                          cancelCallback));
122 }
123 
SaveAsDialogDismissed(const std::string & url,const std::string & content,const SaveCallback & saveCallback,const CancelCallback & cancelCallback,int selected_accept_filter,const std::vector<base::FilePath> & file_paths)124 void CefDevToolsFileManager::SaveAsDialogDismissed(
125     const std::string& url,
126     const std::string& content,
127     const SaveCallback& saveCallback,
128     const CancelCallback& cancelCallback,
129     int selected_accept_filter,
130     const std::vector<base::FilePath>& file_paths) {
131   if (file_paths.size() == 1) {
132     SaveAsFileSelected(url, content, saveCallback, file_paths[0]);
133   } else {
134     cancelCallback.Run();
135   }
136 }
137 
SaveAsFileSelected(const std::string & url,const std::string & content,const SaveCallback & callback,const base::FilePath & path)138 void CefDevToolsFileManager::SaveAsFileSelected(const std::string& url,
139                                                 const std::string& content,
140                                                 const SaveCallback& callback,
141                                                 const base::FilePath& path) {
142   *g_last_save_path.Pointer() = path;
143   saved_files_[url] = path;
144 
145   DictionaryPrefUpdate update(prefs_, prefs::kDevToolsEditedFiles);
146   base::DictionaryValue* files_map = update.Get();
147   files_map->SetKey(base::MD5String(url), util::FilePathToValue(path));
148   std::string file_system_path = path.AsUTF8Unsafe();
149   callback.Run(file_system_path);
150   file_task_runner_->PostTask(FROM_HERE,
151                               base::BindOnce(&::WriteToFile, path, content));
152 }
153 
FileSavedAs(const std::string & url,const std::string & file_system_path)154 void CefDevToolsFileManager::FileSavedAs(const std::string& url,
155                                          const std::string& file_system_path) {
156   base::Value url_value(url);
157   base::Value file_system_path_value(file_system_path);
158   CallClientFunction("DevToolsAPI.savedURL", &url_value,
159                      &file_system_path_value, nullptr);
160 }
161 
CanceledFileSaveAs(const std::string & url)162 void CefDevToolsFileManager::CanceledFileSaveAs(const std::string& url) {
163   base::Value url_value(url);
164   CallClientFunction("DevToolsAPI.canceledSaveURL", &url_value, nullptr,
165                      nullptr);
166 }
167 
Append(const std::string & url,const std::string & content,const AppendCallback & callback)168 void CefDevToolsFileManager::Append(const std::string& url,
169                                     const std::string& content,
170                                     const AppendCallback& callback) {
171   auto it = saved_files_.find(url);
172   if (it == saved_files_.end())
173     return;
174   callback.Run();
175   file_task_runner_->PostTask(
176       FROM_HERE, base::BindOnce(&::AppendToFile, it->second, content));
177 }
178 
AppendedTo(const std::string & url)179 void CefDevToolsFileManager::AppendedTo(const std::string& url) {
180   base::Value url_value(url);
181   CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr);
182 }
183 
CallClientFunction(const std::string & function_name,const base::Value * arg1,const base::Value * arg2,const base::Value * arg3)184 void CefDevToolsFileManager::CallClientFunction(
185     const std::string& function_name,
186     const base::Value* arg1,
187     const base::Value* arg2,
188     const base::Value* arg3) {
189   std::string javascript = function_name + "(";
190   if (arg1) {
191     std::string json;
192     base::JSONWriter::Write(*arg1, &json);
193     javascript.append(json);
194     if (arg2) {
195       base::JSONWriter::Write(*arg2, &json);
196       javascript.append(", ").append(json);
197       if (arg3) {
198         base::JSONWriter::Write(*arg3, &json);
199         javascript.append(", ").append(json);
200       }
201     }
202   }
203   javascript.append(");");
204   browser_impl_->web_contents()->GetMainFrame()->ExecuteJavaScript(
205       base::UTF8ToUTF16(javascript), base::NullCallback());
206 }
207