Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(281)

Side by Side Diff: chrome/browser/download/save_package.h

Issue 7373004: Move the save file code from chrome to content. This is just a file move so the DEPS in content\b... (Closed) Base URL: svn://chrome-svn/chrome/trunk/src/
Patch Set: '' Created 9 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2011 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 #ifndef CHROME_BROWSER_DOWNLOAD_SAVE_PACKAGE_H_
6 #define CHROME_BROWSER_DOWNLOAD_SAVE_PACKAGE_H_
7 #pragma once
8
9 #include <queue>
10 #include <string>
11 #include <vector>
12
13 #include "base/basictypes.h"
14 #include "base/file_path.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/hash_tables.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/task.h"
19 #include "chrome/browser/ui/shell_dialogs.h"
20 #include "content/browser/tab_contents/tab_contents_observer.h"
21 #include "googleurl/src/gurl.h"
22
23 class DownloadItem;
24 class DownloadManager;
25 class GURL;
26 class MessageLoop;
27 class PrefService;
28 class Profile;
29 struct SaveFileCreateInfo;
30 class SaveFileManager;
31 class SaveItem;
32 class SavePackage;
33 struct SavePackageParam;
34 class TabContentsWrapper;
35
36 namespace base {
37 class Thread;
38 class Time;
39 }
40
41
42 // The SavePackage object manages the process of saving a page as only-html or
43 // complete-html and providing the information for displaying saving status.
44 // Saving page as only-html means means that we save web page to a single HTML
45 // file regardless internal sub resources and sub frames.
46 // Saving page as complete-html page means we save not only the main html file
47 // the user told it to save but also a directory for the auxiliary files such
48 // as all sub-frame html files, image files, css files and js files.
49 //
50 // Each page saving job may include one or multiple files which need to be
51 // saved. Each file is represented by a SaveItem, and all SaveItems are owned
52 // by the SavePackage. SaveItems are created when a user initiates a page
53 // saving job, and exist for the duration of one tab's life time.
54 class SavePackage : public base::RefCountedThreadSafe<SavePackage>,
55 public TabContentsObserver,
56 public SelectFileDialog::Listener {
57 public:
58 enum SavePackageType {
59 // The value of the save type before its set by the user.
60 SAVE_TYPE_UNKNOWN = -1,
61 // User chose to save only the HTML of the page.
62 SAVE_AS_ONLY_HTML = 0,
63 // User chose to save complete-html page.
64 SAVE_AS_COMPLETE_HTML = 1
65 };
66
67 enum WaitState {
68 // State when created but not initialized.
69 INITIALIZE = 0,
70 // State when after initializing, but not yet saving.
71 START_PROCESS,
72 // Waiting on a list of savable resources from the backend.
73 RESOURCES_LIST,
74 // Waiting for data sent from net IO or from file system.
75 NET_FILES,
76 // Waiting for html DOM data sent from render process.
77 HTML_DATA,
78 // Saving page finished successfully.
79 SUCCESSFUL,
80 // Failed to save page.
81 FAILED
82 };
83
84 // Constructor for user initiated page saving. This constructor results in a
85 // SavePackage that will generate and sanitize a suggested name for the user
86 // in the "Save As" dialog box.
87 explicit SavePackage(TabContentsWrapper* wrapper);
88
89 // This contructor is used only for testing. We can bypass the file and
90 // directory name generation / sanitization by providing well known paths
91 // better suited for tests.
92 SavePackage(TabContentsWrapper* wrapper,
93 SavePackageType save_type,
94 const FilePath& file_full_path,
95 const FilePath& directory_full_path);
96
97 // Initialize the SavePackage. Returns true if it initializes properly.
98 // Need to make sure that this method must be called in the UI thread because
99 // using g_browser_process on a non-UI thread can cause crashes during
100 // shutdown.
101 bool Init();
102
103 void Cancel(bool user_action);
104
105 void Finish();
106
107 // Notifications sent from the file thread to the UI thread.
108 void StartSave(const SaveFileCreateInfo* info);
109 bool UpdateSaveProgress(int32 save_id, int64 size, bool write_success);
110 void SaveFinished(int32 save_id, int64 size, bool is_success);
111 void SaveFailed(const GURL& save_url);
112 void SaveCanceled(SaveItem* save_item);
113
114 // Rough percent complete, -1 means we don't know (since we didn't receive a
115 // total size).
116 int PercentComplete();
117
118 // Show or Open a saved page via the Windows shell.
119 void ShowDownloadInShell();
120
121 bool canceled() const { return user_canceled_ || disk_error_occurred_; }
122 bool finished() const { return finished_; }
123 SavePackageType save_type() const { return save_type_; }
124 int tab_id() const { return tab_id_; }
125 int id() const { return unique_id_; }
126
127 void GetSaveInfo();
128
129 // Statics -------------------------------------------------------------------
130
131 // Used to disable prompting the user for a directory/filename of the saved
132 // web page. This is available for testing.
133 static void SetShouldPromptUser(bool should_prompt);
134
135 // Check whether we can do the saving page operation for the specified URL.
136 static bool IsSavableURL(const GURL& url);
137
138 // Check whether we can do the saving page operation for the contents which
139 // have the specified MIME type.
140 static bool IsSavableContents(const std::string& contents_mime_type);
141
142 // SelectFileDialog::Listener ------------------------------------------------
143 virtual void FileSelected(const FilePath& path, int index, void* params);
144 virtual void FileSelectionCanceled(void* params);
145
146 private:
147 friend class base::RefCountedThreadSafe<SavePackage>;
148
149 // For testing only.
150 SavePackage(TabContentsWrapper* wrapper,
151 const FilePath& file_full_path,
152 const FilePath& directory_full_path);
153
154 virtual ~SavePackage();
155
156 // Notes from Init() above applies here as well.
157 void InternalInit();
158
159 void Stop();
160 void CheckFinish();
161 void SaveNextFile(bool process_all_remainder_items);
162 void DoSavingProcess();
163
164 // TabContentsObserver implementation.
165 virtual bool OnMessageReceived(const IPC::Message& message);
166
167 // Return max length of a path for a specific base directory.
168 // This is needed on POSIX, which restrict the length of file names in
169 // addition to the restriction on the length of path names.
170 // |base_dir| is assumed to be a directory name with no trailing slash.
171 static uint32 GetMaxPathLengthForDirectory(const FilePath& base_dir);
172
173 static bool GetSafePureFileName(const FilePath& dir_path,
174 const FilePath::StringType& file_name_ext,
175 uint32 max_file_path_len,
176 FilePath::StringType* pure_file_name);
177
178 // Create a file name based on the response from the server.
179 bool GenerateFileName(const std::string& disposition,
180 const GURL& url,
181 bool need_html_ext,
182 FilePath::StringType* generated_name);
183
184 // Get all savable resource links from current web page, include main
185 // frame and sub-frame.
186 void GetAllSavableResourceLinksForCurrentPage();
187 // Get html data by serializing all frames of current page with lists
188 // which contain all resource links that have local copy.
189 void GetSerializedHtmlDataForCurrentPageWithLocalLinks();
190
191 SaveItem* LookupItemInProcessBySaveId(int32 save_id);
192 void PutInProgressItemToSavedMap(SaveItem* save_item);
193
194 // Retrieves the URL to be saved from tab_contents_ variable.
195 GURL GetUrlToBeSaved();
196
197 void CreateDirectoryOnFileThread(const FilePath& website_save_dir,
198 const FilePath& download_save_dir,
199 const std::string& mime_type);
200 void ContinueGetSaveInfo(const FilePath& suggested_path,
201 bool can_save_as_complete);
202 void ContinueSave(const FilePath& final_name, int index);
203
204 void OnReceivedSavableResourceLinksForCurrentPage(
205 const std::vector<GURL>& resources_list,
206 const std::vector<GURL>& referrers_list,
207 const std::vector<GURL>& frames_list);
208
209 void OnReceivedSerializedHtmlData(const GURL& frame_url,
210 const std::string& data,
211 int32 status);
212
213
214 typedef base::hash_map<std::string, SaveItem*> SaveUrlItemMap;
215 // in_progress_items_ is map of all saving job in in-progress state.
216 SaveUrlItemMap in_progress_items_;
217 // saved_failed_items_ is map of all saving job which are failed.
218 SaveUrlItemMap saved_failed_items_;
219
220 // The number of in process SaveItems.
221 int in_process_count() const {
222 return static_cast<int>(in_progress_items_.size());
223 }
224
225 // The number of all SaveItems which have completed, including success items
226 // and failed items.
227 int completed_count() const {
228 return static_cast<int>(saved_success_items_.size() +
229 saved_failed_items_.size());
230 }
231
232 // Retrieve the preference for the directory to save pages to.
233 static FilePath GetSaveDirPreference(PrefService* prefs);
234
235 // Helper function for preparing suggested name for the SaveAs Dialog. The
236 // suggested name is determined by the web document's title.
237 FilePath GetSuggestedNameForSaveAs(
238 bool can_save_as_complete,
239 const std::string& contents_mime_type);
240
241 // Ensures that the file name has a proper extension for HTML by adding ".htm"
242 // if necessary.
243 static FilePath EnsureHtmlExtension(const FilePath& name);
244
245 // Ensures that the file name has a proper extension for supported formats
246 // if necessary.
247 static FilePath EnsureMimeExtension(const FilePath& name,
248 const std::string& contents_mime_type);
249
250 // Returns extension for supported MIME types (for example, for "text/plain"
251 // it returns "txt").
252 static const FilePath::CharType* ExtensionForMimeType(
253 const std::string& contents_mime_type);
254
255 // Owning TabContentsWrapper.
256 TabContentsWrapper* wrapper_;
257
258 typedef std::queue<SaveItem*> SaveItemQueue;
259 // A queue for items we are about to start saving.
260 SaveItemQueue waiting_item_queue_;
261
262 typedef base::hash_map<int32, SaveItem*> SavedItemMap;
263 // saved_success_items_ is map of all saving job which are successfully saved.
264 SavedItemMap saved_success_items_;
265
266 // Non-owning pointer for handling file writing on the file thread.
267 SaveFileManager* file_manager_;
268
269 // We use a fake DownloadItem here in order to reuse the DownloadItemView.
270 // This class owns the pointer.
271 DownloadItem* download_;
272
273 // The URL of the page the user wants to save.
274 GURL page_url_;
275 FilePath saved_main_file_path_;
276 FilePath saved_main_directory_path_;
277
278 // The title of the page the user wants to save.
279 string16 title_;
280
281 // Indicates whether the actual saving job is finishing or not.
282 bool finished_;
283
284 // Indicates whether user canceled the saving job.
285 bool user_canceled_;
286
287 // Indicates whether user get disk error.
288 bool disk_error_occurred_;
289
290 // Type about saving page as only-html or complete-html.
291 SavePackageType save_type_;
292
293 // Number of all need to be saved resources.
294 size_t all_save_items_count_;
295
296 typedef base::hash_set<FilePath::StringType> FileNameSet;
297 // This set is used to eliminate duplicated file names in saving directory.
298 FileNameSet file_name_set_;
299
300 typedef base::hash_map<FilePath::StringType, uint32> FileNameCountMap;
301 // This map is used to track serial number for specified filename.
302 FileNameCountMap file_name_count_map_;
303
304 // Indicates current waiting state when SavePackage try to get something
305 // from outside.
306 WaitState wait_state_;
307
308 // Since for one tab, it can only have one SavePackage in same time.
309 // Now we actually use render_process_id as tab's unique id.
310 const int tab_id_;
311
312 // Unique ID for this SavePackage.
313 const int unique_id_;
314
315 // For managing select file dialogs.
316 scoped_refptr<SelectFileDialog> select_file_dialog_;
317
318 friend class SavePackageTest;
319 FRIEND_TEST_ALL_PREFIXES(SavePackageTest, TestSuggestedSaveNames);
320 FRIEND_TEST_ALL_PREFIXES(SavePackageTest, TestLongSafePureFilename);
321
322 ScopedRunnableMethodFactory<SavePackage> method_factory_;
323
324 DISALLOW_COPY_AND_ASSIGN(SavePackage);
325 };
326
327 #endif // CHROME_BROWSER_DOWNLOAD_SAVE_PACKAGE_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698