1 // Copyright (c) 2012 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 #ifndef CHROME_BROWSER_MEDIA_GALLERIES_LINUX_MTP_DEVICE_DELEGATE_IMPL_LINUX_H_
6 #define CHROME_BROWSER_MEDIA_GALLERIES_LINUX_MTP_DEVICE_DELEGATE_IMPL_LINUX_H_
13 #include "base/callback.h"
14 #include "base/containers/scoped_ptr_hash_map.h"
15 #include "base/files/file_path.h"
16 #include "base/location.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "chrome/browser/media_galleries/fileapi/mtp_device_async_delegate.h"
20 #include "content/public/browser/browser_thread.h"
21 #include "storage/browser/fileapi/async_file_util.h"
23 struct SnapshotRequestInfo
;
25 // MTPDeviceDelegateImplLinux communicates with the media transfer protocol
26 // (MTP) device to complete file system operations. These operations are
27 // performed asynchronously. Instantiate this class per MTP device storage.
28 // MTPDeviceDelegateImplLinux lives on the IO thread.
29 // MTPDeviceDelegateImplLinux does a call-and-reply to the UI thread
30 // to dispatch the requests to MediaTransferProtocolManager.
31 class MTPDeviceDelegateImplLinux
: public MTPDeviceAsyncDelegate
{
33 friend void CreateMTPDeviceAsyncDelegate(
35 const CreateMTPDeviceAsyncDelegateCallback
&);
37 enum InitializationState
{
43 // Used to represent pending task details.
44 struct PendingTaskInfo
{
45 PendingTaskInfo(const base::FilePath
& path
,
46 content::BrowserThread::ID thread_id
,
47 const tracked_objects::Location
& location
,
48 const base::Closure
& task
);
52 base::FilePath cached_path
;
53 const content::BrowserThread::ID thread_id
;
54 const tracked_objects::Location location
;
55 const base::Closure task
;
60 // Maps file ids to file nodes.
61 typedef std::map
<uint32
, MTPFileNode
*> FileIdToMTPFileNodeMap
;
63 // Maps file paths to file info.
64 typedef std::map
<base::FilePath
, storage::DirectoryEntry
> FileInfoCache
;
66 // Should only be called by CreateMTPDeviceAsyncDelegate() factory call.
67 // Defer the device initializations until the first file operation request.
68 // Do all the initializations in EnsureInitAndRunTask() function.
69 explicit MTPDeviceDelegateImplLinux(const std::string
& device_location
);
71 // Destructed via CancelPendingTasksAndDeleteDelegate().
72 ~MTPDeviceDelegateImplLinux() override
;
74 // MTPDeviceAsyncDelegate:
75 void GetFileInfo(const base::FilePath
& file_path
,
76 const GetFileInfoSuccessCallback
& success_callback
,
77 const ErrorCallback
& error_callback
) override
;
78 void ReadDirectory(const base::FilePath
& root
,
79 const ReadDirectorySuccessCallback
& success_callback
,
80 const ErrorCallback
& error_callback
) override
;
81 void CreateSnapshotFile(
82 const base::FilePath
& device_file_path
,
83 const base::FilePath
& local_path
,
84 const CreateSnapshotFileSuccessCallback
& success_callback
,
85 const ErrorCallback
& error_callback
) override
;
86 bool IsStreaming() override
;
87 void ReadBytes(const base::FilePath
& device_file_path
,
88 const scoped_refptr
<net::IOBuffer
>& buf
,
91 const ReadBytesSuccessCallback
& success_callback
,
92 const ErrorCallback
& error_callback
) override
;
93 void CancelPendingTasksAndDeleteDelegate() override
;
95 // The internal methods correspond to the similarly named methods above.
96 // The |root_node_| cache should be filled at this point.
97 virtual void GetFileInfoInternal(
98 const base::FilePath
& file_path
,
99 const GetFileInfoSuccessCallback
& success_callback
,
100 const ErrorCallback
& error_callback
);
101 virtual void ReadDirectoryInternal(
102 const base::FilePath
& root
,
103 const ReadDirectorySuccessCallback
& success_callback
,
104 const ErrorCallback
& error_callback
);
105 virtual void CreateSnapshotFileInternal(
106 const base::FilePath
& device_file_path
,
107 const base::FilePath
& local_path
,
108 const CreateSnapshotFileSuccessCallback
& success_callback
,
109 const ErrorCallback
& error_callback
);
110 virtual void ReadBytesInternal(
111 const base::FilePath
& device_file_path
,
112 net::IOBuffer
* buf
, int64 offset
, int buf_len
,
113 const ReadBytesSuccessCallback
& success_callback
,
114 const ErrorCallback
& error_callback
);
116 // Ensures the device is initialized for communication.
117 // If the device is already initialized, call RunTask().
119 // If the device is uninitialized, store the |task_info| in a pending task
120 // queue and runs the pending tasks in the queue once the device is
121 // successfully initialized.
122 void EnsureInitAndRunTask(const PendingTaskInfo
& task_info
);
124 // Runs a task. If |task_info.path| is empty, or if the path is cached, runs
125 // the task immediately.
126 // Otherwise, fills the cache first before running the task.
127 // |task_info.task| runs on the UI thread.
128 void RunTask(const PendingTaskInfo
& task_info
);
130 // Writes data from the device to the snapshot file path based on the
131 // parameters in |current_snapshot_request_info_| by doing a call-and-reply to
134 // |snapshot_file_info| specifies the metadata details of the snapshot file.
135 void WriteDataIntoSnapshotFile(const base::File::Info
& snapshot_file_info
);
137 // Marks the current request as complete and call ProcessNextPendingRequest().
138 void PendingRequestDone();
140 // Processes the next pending request.
141 void ProcessNextPendingRequest();
143 // Handles the device initialization event. |succeeded| indicates whether
144 // device initialization succeeded.
146 // If the device is successfully initialized, runs the next pending task.
147 void OnInitCompleted(bool succeeded
);
149 // Called when GetFileInfo() succeeds. |file_info| specifies the
150 // requested file details. |success_callback| is invoked to notify the caller
151 // about the requested file details.
152 void OnDidGetFileInfo(const GetFileInfoSuccessCallback
& success_callback
,
153 const base::File::Info
& file_info
);
155 // Called when GetFileInfo() succeeds. GetFileInfo() is invoked to
156 // get the |dir_id| directory metadata details. |file_info| specifies the
157 // |dir_id| directory details.
159 // If |dir_id| is a directory, post a task on the UI thread to read the
160 // |dir_id| directory file entries.
162 // If |dir_id| is not a directory, |error_callback| is invoked to notify the
163 // caller about the file error and process the next pending request.
164 void OnDidGetFileInfoToReadDirectory(
166 const ReadDirectorySuccessCallback
& success_callback
,
167 const ErrorCallback
& error_callback
,
168 const base::File::Info
& file_info
);
170 // Called when GetFileInfo() succeeds. GetFileInfo() is invoked to
171 // create the snapshot file of |snapshot_request_info.device_file_path|.
172 // |file_info| specifies the device file metadata details.
174 // Posts a task on the UI thread to copy the data contents of the device file
175 // to the snapshot file.
176 void OnDidGetFileInfoToCreateSnapshotFile(
177 scoped_ptr
<SnapshotRequestInfo
> snapshot_request_info
,
178 const base::File::Info
& file_info
);
180 // Called when ReadDirectory() succeeds.
182 // |dir_id| is the directory read.
183 // |success_callback| is invoked to notify the caller about the directory
185 // |file_list| contains the directory file entries with their file ids.
186 // |has_more| is true if there are more file entries to read.
187 void OnDidReadDirectory(uint32 dir_id
,
188 const ReadDirectorySuccessCallback
& success_callback
,
189 const storage::AsyncFileUtil::EntryList
& file_list
,
192 // Called when WriteDataIntoSnapshotFile() succeeds.
194 // |snapshot_file_info| specifies the snapshot file metadata details.
196 // |current_snapshot_request_info_.success_callback| is invoked to notify the
197 // caller about |snapshot_file_info|.
198 void OnDidWriteDataIntoSnapshotFile(
199 const base::File::Info
& snapshot_file_info
,
200 const base::FilePath
& snapshot_file_path
);
202 // Called when WriteDataIntoSnapshotFile() fails.
204 // |error| specifies the file error code.
206 // |current_snapshot_request_info_.error_callback| is invoked to notify the
207 // caller about |error|.
208 void OnWriteDataIntoSnapshotFileError(base::File::Error error
);
210 // Called when ReadBytes() succeeds.
212 // |success_callback| is invoked to notify the caller about the read bytes.
213 // |bytes_read| is the number of bytes read.
214 void OnDidReadBytes(const ReadBytesSuccessCallback
& success_callback
,
215 const base::File::Info
& file_info
, int bytes_read
);
217 // Called when FillFileCache() succeeds.
218 void OnDidFillFileCache(const base::FilePath
& path
,
219 const storage::AsyncFileUtil::EntryList
& file_list
,
222 // Called when FillFileCache() fails.
223 void OnFillFileCacheFailed(base::File::Error error
);
225 // Handles the device file |error| while operating on |file_id|.
226 // |error_callback| is invoked to notify the caller about the file error.
227 void HandleDeviceFileError(const ErrorCallback
& error_callback
,
229 base::File::Error error
);
231 // Given a full path, returns a non-empty sub-path that needs to be read into
232 // the cache if such a uncached path exists.
233 // |cached_path| is the portion of |path| that has had cache lookup attempts.
234 base::FilePath
NextUncachedPathComponent(
235 const base::FilePath
& path
,
236 const base::FilePath
& cached_path
) const;
238 // Fills the file cache using the results from NextUncachedPathComponent().
239 void FillFileCache(const base::FilePath
& uncached_path
);
241 // Given a full path, if it exists in the cache, writes the file's id to |id|
243 bool CachedPathToId(const base::FilePath
& path
, uint32
* id
) const;
245 // MTP device initialization state.
246 InitializationState init_state_
;
248 // Used to make sure only one task is in progress at any time.
249 // Otherwise the browser will try to send too many requests at once and
250 // overload the device.
251 bool task_in_progress_
;
253 // Registered file system device path. This path does not
254 // correspond to a real device path (e.g. "/usb:2,2:81282").
255 const base::FilePath device_path_
;
257 // MTP device storage name (e.g. "usb:2,2:81282").
258 std::string storage_name_
;
260 // A list of pending tasks that needs to be run when the device is
261 // initialized or when the current task in progress is complete.
262 std::deque
<PendingTaskInfo
> pending_tasks_
;
264 // Used to track the current snapshot file request. A snapshot file is created
265 // incrementally. CreateSnapshotFile request reads the device file and writes
266 // to the snapshot file in chunks. In order to retain the order of the
267 // snapshot file requests, make sure there is only one active snapshot file
268 // request at any time.
269 scoped_ptr
<SnapshotRequestInfo
> current_snapshot_request_info_
;
271 // A mapping for quick lookups into the |root_node_| tree structure. Since
272 // |root_node_| contains pointers to this map, it must be declared after this
273 // so destruction happens in the right order.
274 FileIdToMTPFileNodeMap file_id_to_node_map_
;
276 // The root node of a tree-structure that caches the directory structure of
278 scoped_ptr
<MTPFileNode
> root_node_
;
280 // A list of child nodes encountered while a ReadDirectory operation, which
281 // can return results over multiple callbacks, is in progress.
282 std::set
<std::string
> child_nodes_seen_
;
284 // A cache to store file metadata for file entries read during a ReadDirectory
285 // operation. Used to service incoming GetFileInfo calls for the duration of
286 // the ReadDirectory operation.
287 FileInfoCache file_info_cache_
;
289 // For callbacks that may run after destruction.
290 base::WeakPtrFactory
<MTPDeviceDelegateImplLinux
> weak_ptr_factory_
;
292 DISALLOW_COPY_AND_ASSIGN(MTPDeviceDelegateImplLinux
);
295 #endif // CHROME_BROWSER_MEDIA_GALLERIES_LINUX_MTP_DEVICE_DELEGATE_IMPL_LINUX_H_