diff options
author | tommycli <tommycli@chromium.org> | 2016-03-01 16:23:10 -0800 |
---|---|---|
committer | Commit bot <commit-bot@chromium.org> | 2016-03-02 00:24:20 +0000 |
commit | d3f29202a41db90b9657b39158777b58ef81bfdb (patch) | |
tree | f3cee2c919ea123172c4398c0defb4288fbc9b12 | |
parent | 68403dc18553e0420a76cabdc4d6cc88604fea5f (diff) | |
download | chromium_src-d3f29202a41db90b9657b39158777b58ef81bfdb.zip chromium_src-d3f29202a41db90b9657b39158777b58ef81bfdb.tar.gz chromium_src-d3f29202a41db90b9657b39158777b58ef81bfdb.tar.bz2 |
Media Galleries Partial Deprecation: Remove scan functionality.
Removes ~4100 sloc, and 50k off the binary size.
BUG=542912
Review URL: https://codereview.chromium.org/1695563002
Cr-Commit-Position: refs/heads/master@{#378624}
69 files changed, 123 insertions, 4190 deletions
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 654b0c6..ab1a963 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd @@ -13198,21 +13198,6 @@ Please check your email at <ph name="ACCOUNT_EMAIL">$2<ex>jane.doe@gmail.com</ex <message name="IDS_MEDIA_GALLERIES_PERMISSION_SUGGESTIONS" desc="Header in media gallery permission dialog for locations that the app does not have permission for."> Suggestions </message> - <message name="IDS_MEDIA_GALLERIES_SCAN_RESULT_DIALOG_HEADER" desc="Header for media gallery scan result dialog."> - Add folders to "<ph name="EXTENSION">$1<ex>Photo Editor</ex></ph>"? - </message> - <message name="IDS_MEDIA_GALLERIES_SCAN_RESULT_DIALOG_SUBTEXT_READ_WRITE" desc="Explanatory text for the media gallery scan result dialog. Indicates that the specified (by name) extension will have read and write access to the selected folders."> - "<ph name="EXTENSION">$1<ex>PhotoEditor</ex></ph>" will be able to read and write images, video, and sound files in the checked folders. - </message> - <message name="IDS_MEDIA_GALLERIES_SCAN_RESULT_DIALOG_SUBTEXT_READ_DELETE" desc="Explanatory text for the media gallery scan result dialog. Indicates that the specified (by name) extension will have read and delete access to the selected folders."> - "<ph name="EXTENSION">$1<ex>PhotoEditor</ex></ph>" will be able to read and delete images, video, and sound files in the checked folders. - </message> - <message name="IDS_MEDIA_GALLERIES_SCAN_RESULT_DIALOG_SUBTEXT_READ_ONLY" desc="Explanatory text for the media gallery scan result dialog. Indicates that the specified (by name) extension will have read-only access to the selected folders."> - "<ph name="EXTENSION">$1<ex>PhotoEditor</ex></ph>" will be able to read images, video, and sound files in the checked folders. - </message> - <message name="IDS_MEDIA_GALLERIES_SCAN_RESULT_OPEN_FOLDER_VIEW_ACCESSIBILITY_NAME" desc="Accessibility name for an icon that opens the folder view of a gallery from the media galleries scan result dialog."> - Show in folder - </message> <message name="IDS_MEDIA_GALLERIES_LAST_ATTACHED" desc="Explanatory text indicating to the user when a particular location was last attached, i.e. a removable device that isn't plugged in. The date presented will be a day in a localized format providing year, month, and day."> last attached on <ph name="DATE">$1<ex>1/22/11</ex></ph> </message> diff --git a/chrome/app/theme/default_100_percent/common/folder.png b/chrome/app/theme/default_100_percent/common/folder.png Binary files differdeleted file mode 100644 index 9912e96..0000000 --- a/chrome/app/theme/default_100_percent/common/folder.png +++ /dev/null diff --git a/chrome/app/theme/default_200_percent/common/folder.png b/chrome/app/theme/default_200_percent/common/folder.png Binary files differdeleted file mode 100644 index 727a2cd..0000000 --- a/chrome/app/theme/default_200_percent/common/folder.png +++ /dev/null diff --git a/chrome/app/theme/theme_resources.grd b/chrome/app/theme/theme_resources.grd index b9f9c08..22ca374 100644 --- a/chrome/app/theme/theme_resources.grd +++ b/chrome/app/theme/theme_resources.grd @@ -257,7 +257,6 @@ <if expr="chromeos"> <structure type="chrome_scaled_image" name="IDR_FATAL_ERROR" file="cros/fatal_error.png" /> </if> - <structure type="chrome_scaled_image" name="IDR_FILE_FOLDER" file="common/folder.png" /> <if expr="chromeos"> <structure type="chrome_scaled_image" name="IDR_FILETYPE_AUDIO" file="cros/file_types/audio.png" /> <structure type="chrome_scaled_image" name="IDR_FILETYPE_GENERIC" file="cros/file_types/generic.png" /> diff --git a/chrome/browser/extensions/api/file_system/file_system_api.cc b/chrome/browser/extensions/api/file_system/file_system_api.cc index 2e365c8..3484b17 100644 --- a/chrome/browser/extensions/api/file_system/file_system_api.cc +++ b/chrome/browser/extensions/api/file_system/file_system_api.cc @@ -297,16 +297,6 @@ void SetLastChooseEntryDirectory(ExtensionPrefs* prefs, base::CreateFilePathValue(path)); } -std::vector<base::FilePath> GetGrayListedDirectories() { - std::vector<base::FilePath> graylisted_directories; - for (size_t i = 0; i < arraysize(kGraylistedPaths); ++i) { - base::FilePath graylisted_path; - if (PathService::Get(kGraylistedPaths[i], &graylisted_path)) - graylisted_directories.push_back(graylisted_path); - } - return graylisted_directories; -} - #if defined(OS_CHROMEOS) void DispatchVolumeListChangeEvent(Profile* profile) { DCHECK(profile); diff --git a/chrome/browser/extensions/api/file_system/file_system_api.h b/chrome/browser/extensions/api/file_system/file_system_api.h index fad2b1b..285260e 100644 --- a/chrome/browser/extensions/api/file_system/file_system_api.h +++ b/chrome/browser/extensions/api/file_system/file_system_api.h @@ -45,8 +45,6 @@ void SetLastChooseEntryDirectory(ExtensionPrefs* prefs, const std::string& extension_id, const base::FilePath& path); -std::vector<base::FilePath> GetGrayListedDirectories(); - #if defined(OS_CHROMEOS) // Dispatches an event about a mounted on unmounted volume in the system to // each extension which can request it. diff --git a/chrome/browser/extensions/api/idltest/idltest_apitest.cc b/chrome/browser/extensions/api/idltest/idltest_apitest.cc index 595e55c..eb564da 100644 --- a/chrome/browser/extensions/api/idltest/idltest_apitest.cc +++ b/chrome/browser/extensions/api/idltest/idltest_apitest.cc @@ -20,4 +20,5 @@ class ExtensionIdltestApiTest : public ExtensionApiTest { IN_PROC_BROWSER_TEST_F(ExtensionIdltestApiTest, IdlCompiler) { EXPECT_TRUE(RunExtensionSubtest("idltest/binary_data", "binary.html")); EXPECT_TRUE(RunExtensionSubtest("idltest/nocompile", "nocompile.html")); + EXPECT_TRUE(RunExtensionSubtest("idltest/nodefine", "nodefine.html")); }; diff --git a/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc b/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc index 3a19e98..39b6c694 100644 --- a/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc +++ b/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc @@ -31,8 +31,6 @@ #include "chrome/browser/media_galleries/media_galleries_histograms.h" #include "chrome/browser/media_galleries/media_galleries_permission_controller.h" #include "chrome/browser/media_galleries/media_galleries_preferences.h" -#include "chrome/browser/media_galleries/media_galleries_scan_result_controller.h" -#include "chrome/browser/media_galleries/media_scan_manager.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/chrome_select_file_policy.h" @@ -82,7 +80,6 @@ const char kFailedToSetGalleryPermission[] = const char kInvalidGalleryIdMsg[] = "Invalid gallery id."; const char kMissingEventListener[] = "Missing event listener registration."; const char kNonExistentGalleryId[] = "Non-existent gallery id."; -const char kNoScanPermission[] = "No permission to scan."; const char kDeviceIdKey[] = "deviceId"; const char kGalleryIdKey[] = "galleryId"; @@ -107,10 +104,6 @@ GalleryWatchManager* gallery_watch_manager() { return media_file_system_registry()->gallery_watch_manager(); } -MediaScanManager* media_scan_manager() { - return media_file_system_registry()->media_scan_manager(); -} - // Checks whether the MediaGalleries API is currently accessible (it may be // disallowed even if an extension has the requisite permission). Then // initializes the MediaGalleriesPreferences @@ -217,20 +210,6 @@ base::ListValue* ConstructFileSystemList( return list.release(); } -bool CheckScanPermission(const extensions::Extension* extension, - std::string* error) { - DCHECK(extension); - DCHECK(error); - MediaGalleriesPermission::CheckParam scan_param( - MediaGalleriesPermission::kScanPermission); - bool has_scan_permission = - extension->permissions_data()->CheckAPIPermissionWithParam( - APIPermission::kMediaGalleries, &scan_param); - if (!has_scan_permission) - *error = kNoScanPermission; - return has_scan_permission; -} - class SelectDirectoryDialog : public ui::SelectFileDialog::Listener, public base::RefCounted<SelectDirectoryDialog> { public: @@ -298,7 +277,6 @@ MediaGalleriesEventRouter::MediaGalleriesEventRouter( this, MediaGalleries::OnGalleryChanged::kEventName); gallery_watch_manager()->AddObserver(profile_, this); - media_scan_manager()->AddObserver(profile_, this); } MediaGalleriesEventRouter::~MediaGalleriesEventRouter() { @@ -311,8 +289,6 @@ void MediaGalleriesEventRouter::Shutdown() { EventRouter::Get(profile_)->UnregisterObserver(this); gallery_watch_manager()->RemoveObserver(profile_); - media_scan_manager()->RemoveObserver(profile_); - media_scan_manager()->CancelScansForProfile(profile_); } static base::LazyInstance< @@ -340,57 +316,6 @@ bool MediaGalleriesEventRouter::ExtensionHasGalleryChangeListener( extension_id, MediaGalleries::OnGalleryChanged::kEventName); } -bool MediaGalleriesEventRouter::ExtensionHasScanProgressListener( - const std::string& extension_id) const { - return EventRouter::Get(profile_)->ExtensionHasEventListener( - extension_id, MediaGalleries::OnScanProgress::kEventName); -} - -void MediaGalleriesEventRouter::OnScanStarted(const std::string& extension_id) { - MediaGalleries::ScanProgressDetails details; - details.type = MediaGalleries::SCAN_PROGRESS_TYPE_START; - DispatchEventToExtension(extension_id, - events::MEDIA_GALLERIES_ON_SCAN_PROGRESS, - MediaGalleries::OnScanProgress::kEventName, - MediaGalleries::OnScanProgress::Create(details)); -} - -void MediaGalleriesEventRouter::OnScanCancelled( - const std::string& extension_id) { - MediaGalleries::ScanProgressDetails details; - details.type = MediaGalleries::SCAN_PROGRESS_TYPE_CANCEL; - DispatchEventToExtension(extension_id, - events::MEDIA_GALLERIES_ON_SCAN_PROGRESS, - MediaGalleries::OnScanProgress::kEventName, - MediaGalleries::OnScanProgress::Create(details)); -} - -void MediaGalleriesEventRouter::OnScanFinished( - const std::string& extension_id, int gallery_count, - const MediaGalleryScanResult& file_counts) { - media_galleries::UsageCount(media_galleries::SCAN_FINISHED); - MediaGalleries::ScanProgressDetails details; - details.type = MediaGalleries::SCAN_PROGRESS_TYPE_FINISH; - details.gallery_count.reset(new int(gallery_count)); - details.audio_count.reset(new int(file_counts.audio_count)); - details.image_count.reset(new int(file_counts.image_count)); - details.video_count.reset(new int(file_counts.video_count)); - DispatchEventToExtension(extension_id, - events::MEDIA_GALLERIES_ON_SCAN_PROGRESS, - MediaGalleries::OnScanProgress::kEventName, - MediaGalleries::OnScanProgress::Create(details)); -} - -void MediaGalleriesEventRouter::OnScanError( - const std::string& extension_id) { - MediaGalleries::ScanProgressDetails details; - details.type = MediaGalleries::SCAN_PROGRESS_TYPE_ERROR; - DispatchEventToExtension(extension_id, - events::MEDIA_GALLERIES_ON_SCAN_PROGRESS, - MediaGalleries::OnScanProgress::kEventName, - MediaGalleries::OnScanProgress::Create(details)); -} - void MediaGalleriesEventRouter::DispatchEventToExtension( const std::string& extension_id, events::HistogramValue histogram_value, @@ -765,135 +690,6 @@ void MediaGalleriesDropPermissionForMediaFileSystemFunction::OnPreferencesInit( } /////////////////////////////////////////////////////////////////////////////// -// MediaGalleriesStartMediaScanFunction // -/////////////////////////////////////////////////////////////////////////////// -MediaGalleriesStartMediaScanFunction::~MediaGalleriesStartMediaScanFunction() {} - -bool MediaGalleriesStartMediaScanFunction::RunAsync() { - media_galleries::UsageCount(media_galleries::START_MEDIA_SCAN); - if (!CheckScanPermission(extension(), &error_)) { - MediaGalleriesEventRouter::Get(GetProfile()) - ->OnScanError(extension()->id()); - return false; - } - return Setup(GetProfile(), &error_, base::Bind( - &MediaGalleriesStartMediaScanFunction::OnPreferencesInit, this)); -} - -void MediaGalleriesStartMediaScanFunction::OnPreferencesInit() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - MediaGalleriesEventRouter* api = MediaGalleriesEventRouter::Get(GetProfile()); - if (!api->ExtensionHasScanProgressListener(extension()->id())) { - error_ = kMissingEventListener; - SendResponse(false); - return; - } - - media_scan_manager()->StartScan(GetProfile(), extension(), user_gesture()); - SendResponse(true); -} - -/////////////////////////////////////////////////////////////////////////////// -// MediaGalleriesCancelMediaScanFunction // -/////////////////////////////////////////////////////////////////////////////// -MediaGalleriesCancelMediaScanFunction:: - ~MediaGalleriesCancelMediaScanFunction() { -} - -bool MediaGalleriesCancelMediaScanFunction::RunAsync() { - media_galleries::UsageCount(media_galleries::CANCEL_MEDIA_SCAN); - if (!CheckScanPermission(extension(), &error_)) { - MediaGalleriesEventRouter::Get(GetProfile()) - ->OnScanError(extension()->id()); - return false; - } - return Setup(GetProfile(), &error_, base::Bind( - &MediaGalleriesCancelMediaScanFunction::OnPreferencesInit, this)); -} - -void MediaGalleriesCancelMediaScanFunction::OnPreferencesInit() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - media_scan_manager()->CancelScan(GetProfile(), extension()); - SendResponse(true); -} - -/////////////////////////////////////////////////////////////////////////////// -// MediaGalleriesAddScanResultsFunction // -/////////////////////////////////////////////////////////////////////////////// -MediaGalleriesAddScanResultsFunction::~MediaGalleriesAddScanResultsFunction() {} - -bool MediaGalleriesAddScanResultsFunction::RunAsync() { - media_galleries::UsageCount(media_galleries::ADD_SCAN_RESULTS); - if (!CheckScanPermission(extension(), &error_)) { - // We don't fire a scan progress error here, as it would be unintuitive. - return false; - } - if (!user_gesture()) - return false; - - return Setup(GetProfile(), &error_, base::Bind( - &MediaGalleriesAddScanResultsFunction::OnPreferencesInit, this)); -} - -MediaGalleriesScanResultController* -MediaGalleriesAddScanResultsFunction::MakeDialog( - content::WebContents* web_contents, - const extensions::Extension& extension, - const base::Closure& on_finish) { - // Controller will delete itself. - return new MediaGalleriesScanResultController(web_contents, extension, - on_finish); -} - -void MediaGalleriesAddScanResultsFunction::OnPreferencesInit() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - MediaGalleriesPreferences* preferences = - media_file_system_registry()->GetPreferences(GetProfile()); - if (MediaGalleriesScanResultController::ScanResultCountForExtension( - preferences, extension()) == 0) { - GetAndReturnGalleries(); - return; - } - - WebContents* contents = - ChromeExtensionFunctionDetails(this).GetOriginWebContents(); - if (!contents) { - SendResponse(false); - return; - } - - base::Closure cb = base::Bind( - &MediaGalleriesAddScanResultsFunction::GetAndReturnGalleries, this); - MakeDialog(contents, *extension(), cb); -} - -void MediaGalleriesAddScanResultsFunction::GetAndReturnGalleries() { - if (!render_frame_host()) { - ReturnGalleries(std::vector<MediaFileSystemInfo>()); - return; - } - MediaFileSystemRegistry* registry = media_file_system_registry(); - DCHECK(registry->GetPreferences(GetProfile())->IsInitialized()); - registry->GetMediaFileSystemsForExtension( - GetSenderWebContents(), extension(), - base::Bind(&MediaGalleriesAddScanResultsFunction::ReturnGalleries, this)); -} - -void MediaGalleriesAddScanResultsFunction::ReturnGalleries( - const std::vector<MediaFileSystemInfo>& filesystems) { - scoped_ptr<base::ListValue> list( - ConstructFileSystemList(render_frame_host(), extension(), filesystems)); - if (!list.get()) { - SendResponse(false); - return; - } - - // The custom JS binding will use this list to create DOMFileSystem objects. - SetResult(list.release()); - SendResponse(true); -} - -/////////////////////////////////////////////////////////////////////////////// // MediaGalleriesGetMetadataFunction // /////////////////////////////////////////////////////////////////////////////// MediaGalleriesGetMetadataFunction::~MediaGalleriesGetMetadataFunction() {} diff --git a/chrome/browser/extensions/api/media_galleries/media_galleries_api.h b/chrome/browser/extensions/api/media_galleries/media_galleries_api.h index 2307232..ea40115 100644 --- a/chrome/browser/extensions/api/media_galleries/media_galleries_api.h +++ b/chrome/browser/extensions/api/media_galleries/media_galleries_api.h @@ -20,7 +20,6 @@ #include "chrome/browser/extensions/chrome_extension_function.h" #include "chrome/browser/media_galleries/gallery_watch_manager_observer.h" #include "chrome/browser/media_galleries/media_file_system_registry.h" -#include "chrome/browser/media_galleries/media_scan_manager_observer.h" #include "chrome/common/extensions/api/media_galleries.h" #include "chrome/common/media_galleries/metadata_types.h" #include "components/storage_monitor/media_storage_util.h" @@ -30,8 +29,6 @@ namespace MediaGalleries = extensions::api::media_galleries; -class MediaGalleriesScanResultController; - namespace content { class BlobHandle; class WebContents; @@ -49,7 +46,6 @@ class Extension; // Created at the same time as the Profile. This is also the event router. class MediaGalleriesEventRouter : public BrowserContextKeyedAPI, public GalleryWatchManagerObserver, - public MediaScanManagerObserver, public extensions::EventRouter::Observer { public: // KeyedService implementation. @@ -63,15 +59,6 @@ class MediaGalleriesEventRouter : public BrowserContextKeyedAPI, static MediaGalleriesEventRouter* Get(content::BrowserContext* context); bool ExtensionHasGalleryChangeListener(const std::string& extension_id) const; - bool ExtensionHasScanProgressListener(const std::string& extension_id) const; - - // MediaScanManagerObserver implementation. - void OnScanStarted(const std::string& extension_id) override; - void OnScanCancelled(const std::string& extension_id) override; - void OnScanFinished(const std::string& extension_id, - int gallery_count, - const MediaGalleryScanResult& file_counts) override; - void OnScanError(const std::string& extension_id) override; private: friend class BrowserContextKeyedAPIFactory<MediaGalleriesEventRouter>; @@ -214,64 +201,6 @@ class MediaGalleriesDropPermissionForMediaFileSystemFunction void OnPreferencesInit(MediaGalleryPrefId pref_id); }; -class MediaGalleriesStartMediaScanFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("mediaGalleries.startMediaScan", - MEDIAGALLERIES_STARTMEDIASCAN) - - protected: - ~MediaGalleriesStartMediaScanFunction() override; - bool RunAsync() override; - - private: - // Bottom half for RunAsync, invoked after the preferences is initialized. - void OnPreferencesInit(); -}; - -class MediaGalleriesCancelMediaScanFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("mediaGalleries.cancelMediaScan", - MEDIAGALLERIES_CANCELMEDIASCAN) - - protected: - ~MediaGalleriesCancelMediaScanFunction() override; - bool RunAsync() override; - - private: - // Bottom half for RunAsync, invoked after the preferences is initialized. - void OnPreferencesInit(); -}; - -class MediaGalleriesAddScanResultsFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("mediaGalleries.addScanResults", - MEDIAGALLERIES_ADDSCANRESULTS) - - protected: - ~MediaGalleriesAddScanResultsFunction() override; - bool RunAsync() override; - - // Pulled out for testing. - virtual MediaGalleriesScanResultController* MakeDialog( - content::WebContents* web_contents, - const extensions::Extension& extension, - const base::Closure& on_finish); - - private: - // Bottom half for RunAsync, invoked after the preferences is initialized. - void OnPreferencesInit(); - - // Grabs galleries from the media file system registry and passes them to - // ReturnGalleries(). - void GetAndReturnGalleries(); - - // Returns galleries to the caller. - void ReturnGalleries(const std::vector<MediaFileSystemInfo>& filesystems); -}; - class MediaGalleriesGetMetadataFunction : public ChromeAsyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("mediaGalleries.getMetadata", diff --git a/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc b/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc index 58a074c3..1a59f99 100644 --- a/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc +++ b/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc @@ -19,11 +19,8 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/media_galleries/media_galleries_api.h" #include "chrome/browser/media_galleries/media_file_system_registry.h" -#include "chrome/browser/media_galleries/media_folder_finder.h" #include "chrome/browser/media_galleries/media_galleries_preferences.h" -#include "chrome/browser/media_galleries/media_galleries_scan_result_controller.h" #include "chrome/browser/media_galleries/media_galleries_test_util.h" -#include "chrome/browser/media_galleries/media_scan_manager.h" #include "chrome/browser/ui/extensions/app_launch_params.h" #include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/common/chrome_paths.h" @@ -71,50 +68,8 @@ base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("C:\\qux"); base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux"); #endif -class DoNothingMediaFolderFinder : public MediaFolderFinder { - public: - explicit DoNothingMediaFolderFinder( - const MediaFolderFinderResultsCallback& callback) - : MediaFolderFinder(callback) { - } - ~DoNothingMediaFolderFinder() override {} - - static MediaFolderFinder* CreateDoNothingMediaFolderFinder( - const MediaFolderFinderResultsCallback& callback) { - return new DoNothingMediaFolderFinder(callback); - } - - void StartScan() override {} - - private: -}; - } // namespace -class TestMediaGalleriesAddScanResultsFunction - : public extensions::MediaGalleriesAddScanResultsFunction { - public: - static ExtensionFunction* Factory() { - return new TestMediaGalleriesAddScanResultsFunction; - } - - protected: - ~TestMediaGalleriesAddScanResultsFunction() override {} - - // Accepts the dialog as soon as it is created. - MediaGalleriesScanResultController* MakeDialog( - content::WebContents* web_contents, - const extensions::Extension& extension, - const base::Closure& on_finish) override { - MediaGalleriesScanResultController* controller = - extensions::MediaGalleriesAddScanResultsFunction::MakeDialog( - web_contents, extension, on_finish); - controller->dialog_->AcceptDialogForTesting(); - // The dialog is closing or closed so don't return it. - return NULL; - } -}; - class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest { protected: MediaGalleriesPlatformAppBrowserTest() : test_jpg_size_(0) {} @@ -400,30 +355,7 @@ class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest { return ensure_media_directories_exists_.get(); } - void InstallDoNothingFolderFinder() { - MediaScanManager * scan_manager = - g_browser_process->media_file_system_registry()->media_scan_manager(); - scan_manager->SetMediaFolderFinderFactory(base::Bind( - &DoNothingMediaFolderFinder::CreateDoNothingMediaFolderFinder)); - } - - void SetRootsForFolderFinder(const std::vector<base::FilePath>& roots) { - MediaScanManager* scan_manager = - g_browser_process->media_file_system_registry()->media_scan_manager(); - scan_manager->SetMediaFolderFinderFactory(base::Bind( - &MediaGalleriesPlatformAppBrowserTest::CreateMediaFolderFinderWithRoots, - roots)); - } - private: - static MediaFolderFinder* CreateMediaFolderFinderWithRoots( - const std::vector<base::FilePath>& roots, - const MediaFolderFinder::MediaFolderFinderResultsCallback& callback) { - MediaFolderFinder* finder = new MediaFolderFinder(callback); - finder->SetRootsForTesting(roots); - return finder; - } - MediaGalleriesPreferences* GetAndInitializePreferences() { MediaGalleriesPreferences* preferences = g_browser_process->media_file_system_registry()->GetPreferences( @@ -621,51 +553,6 @@ IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, } #endif // defined(OS_MACOSX) -IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, CancelScan) { - InstallDoNothingFolderFinder(); - ASSERT_TRUE(RunMediaGalleriesTest("cancel_scan")) << message_; -} - -// Flaky time outs on MSAN. https://crbug.com/503329 -#if defined(MEMORY_SANITIZER) -#define MAYBE_Scan DISABLED_Scan -#else -#define MAYBE_Scan Scan -#endif -IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, MAYBE_Scan) { - base::ScopedTempDir scan_root; - ASSERT_TRUE(scan_root.CreateUniqueTempDir()); - std::vector<base::FilePath> roots; - roots.push_back(scan_root.path()); - SetRootsForFolderFinder(roots); - - // Override addScanResults so that the dialog is accepted as soon as it is - // created. - ASSERT_TRUE(extensions::ExtensionFunctionDispatcher::OverrideFunction( - "mediaGalleries.addScanResults", - &TestMediaGalleriesAddScanResultsFunction::Factory)); - - // Add some files and directories to the scan root for testing. Only the - // "f" directory should be found. - std::string dummy_data; - dummy_data.resize(1); - ASSERT_TRUE(base::CreateDirectory(scan_root.path().AppendASCII("a/b"))); - ASSERT_EQ(static_cast<int>(dummy_data.size()), - base::WriteFile(scan_root.path().AppendASCII("a/b/c.jpg"), - dummy_data.c_str(), dummy_data.size())); - ASSERT_TRUE(base::CreateDirectory(scan_root.path().AppendASCII("a/d"))); - dummy_data.resize(201 * 1024); // 200k is the min size for the folder finder. - ASSERT_EQ(static_cast<int>(dummy_data.size()), - base::WriteFile(scan_root.path().AppendASCII("a/d/e.txt"), - dummy_data.c_str(), dummy_data.size())); - ASSERT_TRUE(base::CreateDirectory(scan_root.path().AppendASCII("f"))); - ASSERT_EQ(static_cast<int>(dummy_data.size()), - base::WriteFile(scan_root.path().AppendASCII("f/g.jpg"), - dummy_data.c_str(), dummy_data.size())); - - ASSERT_TRUE(RunMediaGalleriesTest("scan")) << message_; -} - IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, ToURL) { RemoveAllGalleries(); MediaGalleryPrefId pref_id; diff --git a/chrome/browser/media_galleries/fileapi/media_path_filter.cc b/chrome/browser/media_galleries/fileapi/media_path_filter.cc index de14bb69..34807df 100644 --- a/chrome/browser/media_galleries/fileapi/media_path_filter.cc +++ b/chrome/browser/media_galleries/fileapi/media_path_filter.cc @@ -148,16 +148,16 @@ MediaPathFilter::~MediaPathFilter() { } bool MediaPathFilter::Match(const base::FilePath& path) { - return GetType(path) != MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN; + return GetType(path) != MEDIA_GALLERY_FILE_TYPE_UNKNOWN; } -MediaGalleryScanFileType MediaPathFilter::GetType(const base::FilePath& path) { +MediaGalleryFileType MediaPathFilter::GetType(const base::FilePath& path) { EnsureInitialized(); MediaFileExtensionMap::const_iterator it = media_file_extensions_map_.find(base::ToLowerASCII(path.Extension())); if (it == media_file_extensions_map_.end()) - return MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN; - return static_cast<MediaGalleryScanFileType>(it->second); + return MEDIA_GALLERY_FILE_TYPE_UNKNOWN; + return static_cast<MediaGalleryFileType>(it->second); } void MediaPathFilter::EnsureInitialized() { @@ -169,30 +169,27 @@ void MediaPathFilter::EnsureInitialized() { // doing this in the ctor and removing |initialized_| would result in a // ThreadRestrictions failure. AddExtensionsToMediaFileExtensionMap(GetMediaExtensionList("image/*"), - MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE); + MEDIA_GALLERY_FILE_TYPE_IMAGE); AddExtensionsToMediaFileExtensionMap(GetMediaExtensionList("audio/*"), - MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO); + MEDIA_GALLERY_FILE_TYPE_AUDIO); AddExtensionsToMediaFileExtensionMap(GetMediaExtensionList("video/*"), - MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO); + MEDIA_GALLERY_FILE_TYPE_VIDEO); AddAdditionalExtensionsToMediaFileExtensionMap( - kExtraSupportedImageExtensions, - arraysize(kExtraSupportedImageExtensions), - MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE); + kExtraSupportedImageExtensions, arraysize(kExtraSupportedImageExtensions), + MEDIA_GALLERY_FILE_TYPE_IMAGE); AddAdditionalExtensionsToMediaFileExtensionMap( - kExtraSupportedAudioExtensions, - arraysize(kExtraSupportedAudioExtensions), - MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO); + kExtraSupportedAudioExtensions, arraysize(kExtraSupportedAudioExtensions), + MEDIA_GALLERY_FILE_TYPE_AUDIO); AddAdditionalExtensionsToMediaFileExtensionMap( - kExtraSupportedVideoExtensions, - arraysize(kExtraSupportedVideoExtensions), - MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO); + kExtraSupportedVideoExtensions, arraysize(kExtraSupportedVideoExtensions), + MEDIA_GALLERY_FILE_TYPE_VIDEO); initialized_ = true; } void MediaPathFilter::AddExtensionsToMediaFileExtensionMap( const MediaFileExtensionList& extensions_list, - MediaGalleryScanFileType type) { + MediaGalleryFileType type) { for (size_t i = 0; i < extensions_list.size(); ++i) AddExtensionToMediaFileExtensionMap(extensions_list[i].c_str(), type); } @@ -200,14 +197,14 @@ void MediaPathFilter::AddExtensionsToMediaFileExtensionMap( void MediaPathFilter::AddAdditionalExtensionsToMediaFileExtensionMap( const base::FilePath::CharType* const* extensions_list, size_t extensions_list_size, - MediaGalleryScanFileType type) { + MediaGalleryFileType type) { for (size_t i = 0; i < extensions_list_size; ++i) AddExtensionToMediaFileExtensionMap(extensions_list[i], type); } void MediaPathFilter::AddExtensionToMediaFileExtensionMap( const base::FilePath::CharType* extension, - MediaGalleryScanFileType type) { + MediaGalleryFileType type) { base::FilePath::StringType extension_with_sep = base::FilePath::kExtensionSeparator + base::FilePath::StringType(extension); diff --git a/chrome/browser/media_galleries/fileapi/media_path_filter.h b/chrome/browser/media_galleries/fileapi/media_path_filter.h index 9f84f97..6e9fe5b3 100644 --- a/chrome/browser/media_galleries/fileapi/media_path_filter.h +++ b/chrome/browser/media_galleries/fileapi/media_path_filter.h @@ -14,7 +14,13 @@ #include "base/files/file_path.h" #include "base/macros.h" #include "base/sequence_checker.h" -#include "chrome/browser/media_galleries/media_scan_types.h" + +enum MediaGalleryFileType { + MEDIA_GALLERY_FILE_TYPE_UNKNOWN = 0, + MEDIA_GALLERY_FILE_TYPE_AUDIO = 1 << 0, + MEDIA_GALLERY_FILE_TYPE_IMAGE = 1 << 1, + MEDIA_GALLERY_FILE_TYPE_VIDEO = 1 << 2, +}; // This class holds the list of file path extensions that we should expose on // media filesystem. @@ -30,29 +36,29 @@ class MediaPathFilter { // Returns true if |path| is a media file. bool Match(const base::FilePath& path); - // Returns the type of |path| or MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN if it + // Returns the type of |path| or MEDIA_GALLERY_FILE_TYPE_UNKNOWN if it // is not a media file. - MediaGalleryScanFileType GetType(const base::FilePath& path); + MediaGalleryFileType GetType(const base::FilePath& path); private: typedef std::vector<base::FilePath::StringType> MediaFileExtensionList; // Key: .extension - // Value: MediaGalleryScanFileType, but stored as an int to allow "|=" + // Value: MediaGalleryFileType, but stored as an int to allow "|=" typedef base::hash_map<base::FilePath::StringType, int> MediaFileExtensionMap; void EnsureInitialized(); void AddExtensionsToMediaFileExtensionMap( const MediaFileExtensionList& extensions_list, - MediaGalleryScanFileType type); + MediaGalleryFileType type); void AddAdditionalExtensionsToMediaFileExtensionMap( const base::FilePath::CharType* const* extensions_list, size_t extensions_list_size, - MediaGalleryScanFileType type); + MediaGalleryFileType type); void AddExtensionToMediaFileExtensionMap( const base::FilePath::CharType* extension, - MediaGalleryScanFileType type); + MediaGalleryFileType type); // Checks |initialized_| is only accessed on one sequence. base::SequenceChecker sequence_checker_; diff --git a/chrome/browser/media_galleries/media_file_system_registry.cc b/chrome/browser/media_galleries/media_file_system_registry.cc index c532bed..a5c3adb 100644 --- a/chrome/browser/media_galleries/media_file_system_registry.cc +++ b/chrome/browser/media_galleries/media_file_system_registry.cc @@ -22,7 +22,6 @@ #include "chrome/browser/media_galleries/media_galleries_dialog_controller.h" #include "chrome/browser/media_galleries/media_galleries_histograms.h" #include "chrome/browser/media_galleries/media_galleries_preferences_factory.h" -#include "chrome/browser/media_galleries/media_scan_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension_constants.h" @@ -595,12 +594,6 @@ MediaGalleriesPreferences* MediaFileSystemRegistry::GetPreferences( return MediaGalleriesPreferencesFactory::GetForProfile(profile); } -MediaScanManager* MediaFileSystemRegistry::media_scan_manager() { - if (!media_scan_manager_) - media_scan_manager_.reset(new MediaScanManager); - return media_scan_manager_.get(); -} - GalleryWatchManager* MediaFileSystemRegistry::gallery_watch_manager() { if (!gallery_watch_manager_) gallery_watch_manager_.reset(new GalleryWatchManager); diff --git a/chrome/browser/media_galleries/media_file_system_registry.h b/chrome/browser/media_galleries/media_file_system_registry.h index 225d24d..4b508e7 100644 --- a/chrome/browser/media_galleries/media_file_system_registry.h +++ b/chrome/browser/media_galleries/media_file_system_registry.h @@ -26,7 +26,6 @@ class ExtensionGalleriesHost; class GalleryWatchManager; class MediaFileSystemContext; class MediaGalleriesPreferences; -class MediaScanManager; class Profile; namespace content { @@ -97,7 +96,6 @@ class MediaFileSystemRegistry // before use. MediaGalleriesPreferences* GetPreferences(Profile* profile); - MediaScanManager* media_scan_manager(); GalleryWatchManager* gallery_watch_manager(); // RemovableStorageObserver implementation. @@ -147,7 +145,6 @@ class MediaFileSystemRegistry scoped_ptr<MediaFileSystemContext> file_system_context_; - scoped_ptr<MediaScanManager> media_scan_manager_; scoped_ptr<GalleryWatchManager> gallery_watch_manager_; DISALLOW_COPY_AND_ASSIGN(MediaFileSystemRegistry); diff --git a/chrome/browser/media_galleries/media_folder_finder.cc b/chrome/browser/media_galleries/media_folder_finder.cc deleted file mode 100644 index 6abb669..0000000 --- a/chrome/browser/media_galleries/media_folder_finder.cc +++ /dev/null @@ -1,451 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/media_galleries/media_folder_finder.h" - -#include <stddef.h> -#include <stdint.h> - -#include <algorithm> -#include <set> - -#include "base/files/file_enumerator.h" -#include "base/files/file_util.h" -#include "base/macros.h" -#include "base/path_service.h" -#include "base/sequence_checker.h" -#include "base/stl_util.h" -#include "base/strings/string_util.h" -#include "base/task_runner_util.h" -#include "base/threading/sequenced_worker_pool.h" -#include "build/build_config.h" -#include "chrome/browser/extensions/api/file_system/file_system_api.h" -#include "chrome/browser/media_galleries/fileapi/media_path_filter.h" -#include "chrome/common/chrome_paths.h" -#include "components/storage_monitor/storage_monitor.h" -#include "content/public/browser/browser_thread.h" - -#if defined(OS_CHROMEOS) -#include "chrome/common/chrome_paths.h" -#include "chromeos/dbus/cros_disks_client.h" -#endif - -using storage_monitor::StorageInfo; -using storage_monitor::StorageMonitor; - -typedef base::Callback<void(const std::vector<base::FilePath>& /*roots*/)> - DefaultScanRootsCallback; -using content::BrowserThread; - -namespace { - -const int64_t kMinimumImageSize = 200 * 1024; // 200 KB -const int64_t kMinimumAudioSize = 500 * 1024; // 500 KB -const int64_t kMinimumVideoSize = 1024 * 1024; // 1 MB - -const int kPrunedPaths[] = { -#if defined(OS_WIN) - base::DIR_IE_INTERNET_CACHE, - base::DIR_PROGRAM_FILES, - base::DIR_PROGRAM_FILESX86, - base::DIR_WINDOWS, -#endif -#if defined(OS_MACOSX) - chrome::DIR_USER_APPLICATIONS, - chrome::DIR_USER_LIBRARY, -#endif -#if defined(OS_LINUX) - base::DIR_CACHE, -#endif -#if defined(OS_WIN) || defined(OS_LINUX) - base::DIR_TEMP, -#endif -}; - -bool IsValidScanPath(const base::FilePath& path) { - return !path.empty() && path.IsAbsolute(); -} - -void CountScanResult(MediaGalleryScanFileType type, - MediaGalleryScanResult* scan_result) { - if (type & MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE) - scan_result->image_count += 1; - if (type & MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO) - scan_result->audio_count += 1; - if (type & MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO) - scan_result->video_count += 1; -} - -bool FileMeetsSizeRequirement(MediaGalleryScanFileType type, int64_t size) { - if (type & MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE) - if (size >= kMinimumImageSize) - return true; - if (type & MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO) - if (size >= kMinimumAudioSize) - return true; - if (type & MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO) - if (size >= kMinimumVideoSize) - return true; - return false; -} - -// Return true if |path| should not be considered as the starting point for a -// media scan. -bool ShouldIgnoreScanRoot(const base::FilePath& path) { -#if defined(OS_MACOSX) - // Scanning root is of little value. - return (path.value() == "/"); -#elif defined(OS_CHROMEOS) - // Sanity check to make sure mount points are where they should be. - base::FilePath mount_point = - chromeos::CrosDisksClient::GetRemovableDiskMountPoint(); - return mount_point.IsParent(path); -#elif defined(OS_LINUX) - // /media and /mnt are likely the only places with interesting mount points. - if (base::StartsWith(path.value(), "/media", base::CompareCase::SENSITIVE) || - base::StartsWith(path.value(), "/mnt", base::CompareCase::SENSITIVE)) { - return false; - } - return true; -#elif defined(OS_WIN) - return false; -#else - NOTIMPLEMENTED(); - return false; -#endif -} - -// Return a location that is likely to have user data to scan, if any. -base::FilePath GetPlatformSpecificDefaultScanRoot() { - base::FilePath root; -#if defined(OS_CHROMEOS) - PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS_SAFE, &root); -#elif defined(OS_MACOSX) || defined(OS_LINUX) - PathService::Get(base::DIR_HOME, &root); -#elif defined(OS_WIN) - // Nothing to add. -#else - NOTIMPLEMENTED(); -#endif - return root; -} - -// Find the likely locations with user media files and pass them to -// |callback|. Locations are platform specific. -void GetDefaultScanRoots(const DefaultScanRootsCallback& callback, - bool has_override, - const std::vector<base::FilePath>& override_paths) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (has_override) { - callback.Run(override_paths); - return; - } - - StorageMonitor* monitor = StorageMonitor::GetInstance(); - DCHECK(monitor->IsInitialized()); - - std::vector<base::FilePath> roots; - std::vector<StorageInfo> storages = monitor->GetAllAvailableStorages(); - for (size_t i = 0; i < storages.size(); ++i) { - StorageInfo::Type type; - if (!StorageInfo::CrackDeviceId(storages[i].device_id(), &type, NULL) || - (type != StorageInfo::FIXED_MASS_STORAGE && - type != StorageInfo::REMOVABLE_MASS_STORAGE_NO_DCIM)) { - continue; - } - base::FilePath path(storages[i].location()); - if (ShouldIgnoreScanRoot(path)) - continue; - roots.push_back(path); - } - - base::FilePath platform_root = GetPlatformSpecificDefaultScanRoot(); - if (!platform_root.empty()) - roots.push_back(platform_root); - callback.Run(roots); -} - -} // namespace - -MediaFolderFinder::WorkerReply::WorkerReply() {} - -MediaFolderFinder::WorkerReply::WorkerReply(const WorkerReply& other) = default; - -MediaFolderFinder::WorkerReply::~WorkerReply() {} - -// The Worker is created on the UI thread, but does all its work on a blocking -// SequencedTaskRunner. -class MediaFolderFinder::Worker { - public: - explicit Worker(const std::vector<base::FilePath>& graylisted_folders); - ~Worker(); - - // Scans |path| and return the results. - WorkerReply ScanFolder(const base::FilePath& path); - - private: - void MakeFolderPathsAbsolute(); - - bool folder_paths_are_absolute_; - std::vector<base::FilePath> graylisted_folders_; - std::vector<base::FilePath> pruned_folders_; - - scoped_ptr<MediaPathFilter> filter_; - - base::SequenceChecker sequence_checker_; - - DISALLOW_COPY_AND_ASSIGN(Worker); -}; - -MediaFolderFinder::Worker::Worker( - const std::vector<base::FilePath>& graylisted_folders) - : folder_paths_are_absolute_(false), - graylisted_folders_(graylisted_folders), - filter_(new MediaPathFilter) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - for (size_t i = 0; i < arraysize(kPrunedPaths); ++i) { - base::FilePath path; - if (PathService::Get(kPrunedPaths[i], &path)) - pruned_folders_.push_back(path); - } - - sequence_checker_.DetachFromSequence(); -} - -MediaFolderFinder::Worker::~Worker() { - DCHECK(sequence_checker_.CalledOnValidSequencedThread()); -} - -MediaFolderFinder::WorkerReply MediaFolderFinder::Worker::ScanFolder( - const base::FilePath& path) { - DCHECK(sequence_checker_.CalledOnValidSequencedThread()); - CHECK(IsValidScanPath(path)); - - if (!folder_paths_are_absolute_) - MakeFolderPathsAbsolute(); - - WorkerReply reply; - bool folder_meets_size_requirement = false; - bool is_graylisted_folder = false; - base::FilePath abspath = base::MakeAbsoluteFilePath(path); - if (abspath.empty()) - return reply; - - for (size_t i = 0; i < graylisted_folders_.size(); ++i) { - if (abspath == graylisted_folders_[i] || - abspath.IsParent(graylisted_folders_[i])) { - is_graylisted_folder = true; - break; - } - } - - base::FileEnumerator enumerator( - path, - false, /* recursive? */ - base::FileEnumerator::FILES | base::FileEnumerator::DIRECTORIES -#if defined(OS_POSIX) - | base::FileEnumerator::SHOW_SYM_LINKS // show symlinks, not follow. -#endif - ); // NOLINT - while (!enumerator.Next().empty()) { - base::FileEnumerator::FileInfo file_info = enumerator.GetInfo(); - base::FilePath full_path = path.Append(file_info.GetName()); - if (MediaPathFilter::ShouldSkip(full_path)) - continue; - - // Enumerating a directory. - if (file_info.IsDirectory()) { - bool is_pruned_folder = false; - base::FilePath abs_full_path = base::MakeAbsoluteFilePath(full_path); - if (abs_full_path.empty()) - continue; - for (size_t i = 0; i < pruned_folders_.size(); ++i) { - if (abs_full_path == pruned_folders_[i]) { - is_pruned_folder = true; - break; - } - } - - if (!is_pruned_folder) - reply.new_folders.push_back(full_path); - continue; - } - - // Enumerating a file. - // - // Do not include scan results for graylisted folders. - if (is_graylisted_folder) - continue; - - MediaGalleryScanFileType type = filter_->GetType(full_path); - if (type == MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN) - continue; - - CountScanResult(type, &reply.scan_result); - if (!folder_meets_size_requirement) { - folder_meets_size_requirement = - FileMeetsSizeRequirement(type, file_info.GetSize()); - } - } - // Make sure there is at least 1 file above a size threshold. - if (!folder_meets_size_requirement) - reply.scan_result = MediaGalleryScanResult(); - return reply; -} - -void MediaFolderFinder::Worker::MakeFolderPathsAbsolute() { - DCHECK(sequence_checker_.CalledOnValidSequencedThread()); - DCHECK(!folder_paths_are_absolute_); - folder_paths_are_absolute_ = true; - - std::vector<base::FilePath> abs_paths; - for (size_t i = 0; i < graylisted_folders_.size(); ++i) { - base::FilePath path = base::MakeAbsoluteFilePath(graylisted_folders_[i]); - if (!path.empty()) - abs_paths.push_back(path); - } - graylisted_folders_ = abs_paths; - abs_paths.clear(); - for (size_t i = 0; i < pruned_folders_.size(); ++i) { - base::FilePath path = base::MakeAbsoluteFilePath(pruned_folders_[i]); - if (!path.empty()) - abs_paths.push_back(path); - } - pruned_folders_ = abs_paths; -} - -MediaFolderFinder::MediaFolderFinder( - const MediaFolderFinderResultsCallback& callback) - : results_callback_(callback), - graylisted_folders_( - extensions::file_system_api::GetGrayListedDirectories()), - scan_state_(SCAN_STATE_NOT_STARTED), - worker_(new Worker(graylisted_folders_)), - has_roots_for_testing_(false), - weak_factory_(this) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool(); - worker_task_runner_ = pool->GetSequencedTaskRunner(pool->GetSequenceToken()); -} - -MediaFolderFinder::~MediaFolderFinder() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - worker_task_runner_->DeleteSoon(FROM_HERE, worker_); - - if (scan_state_ == SCAN_STATE_FINISHED) - return; - - MediaFolderFinderResults empty_results; - results_callback_.Run(false /* success? */, empty_results); -} - -void MediaFolderFinder::StartScan() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - if (scan_state_ != SCAN_STATE_NOT_STARTED) - return; - - scan_state_ = SCAN_STATE_STARTED; - GetDefaultScanRoots( - base::Bind(&MediaFolderFinder::OnInitialized, weak_factory_.GetWeakPtr()), - has_roots_for_testing_, - roots_for_testing_); -} - -const std::vector<base::FilePath>& -MediaFolderFinder::graylisted_folders() const { - return graylisted_folders_; -} - -void MediaFolderFinder::SetRootsForTesting( - const std::vector<base::FilePath>& roots) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(SCAN_STATE_NOT_STARTED, scan_state_); - - has_roots_for_testing_ = true; - roots_for_testing_ = roots; -} - -void MediaFolderFinder::OnInitialized( - const std::vector<base::FilePath>& roots) { - DCHECK_EQ(SCAN_STATE_STARTED, scan_state_); - - std::set<base::FilePath> valid_roots; - for (size_t i = 0; i < roots.size(); ++i) { - // Skip if |path| is invalid or redundant. - const base::FilePath& path = roots[i]; - if (!IsValidScanPath(path)) - continue; - if (ContainsKey(valid_roots, path)) - continue; - - // Check for overlap. - bool valid_roots_contains_path = false; - std::vector<base::FilePath> overlapping_paths_to_remove; - for (std::set<base::FilePath>::iterator it = valid_roots.begin(); - it != valid_roots.end(); ++it) { - if (it->IsParent(path)) { - valid_roots_contains_path = true; - break; - } - const base::FilePath& other_path = *it; - if (path.IsParent(other_path)) - overlapping_paths_to_remove.push_back(other_path); - } - if (valid_roots_contains_path) - continue; - // Remove anything |path| overlaps from |valid_roots|. - for (size_t i = 0; i < overlapping_paths_to_remove.size(); ++i) - valid_roots.erase(overlapping_paths_to_remove[i]); - - valid_roots.insert(path); - } - - std::copy(valid_roots.begin(), valid_roots.end(), - std::back_inserter(folders_to_scan_)); - ScanFolder(); -} - -void MediaFolderFinder::ScanFolder() { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(SCAN_STATE_STARTED, scan_state_); - - if (folders_to_scan_.empty()) { - scan_state_ = SCAN_STATE_FINISHED; - results_callback_.Run(true /* success? */, results_); - return; - } - - base::FilePath folder_to_scan = folders_to_scan_.back(); - folders_to_scan_.pop_back(); - base::PostTaskAndReplyWithResult( - worker_task_runner_.get(), - FROM_HERE, - base::Bind( - &Worker::ScanFolder, base::Unretained(worker_), folder_to_scan), - base::Bind(&MediaFolderFinder::GotScanResults, - weak_factory_.GetWeakPtr(), - folder_to_scan)); -} - -void MediaFolderFinder::GotScanResults(const base::FilePath& path, - const WorkerReply& reply) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK_EQ(SCAN_STATE_STARTED, scan_state_); - DCHECK(!path.empty()); - CHECK(!ContainsKey(results_, path)); - - if (!IsEmptyScanResult(reply.scan_result)) - results_[path] = reply.scan_result; - - // Push new folders to the |folders_to_scan_| in reverse order. - std::copy(reply.new_folders.rbegin(), reply.new_folders.rend(), - std::back_inserter(folders_to_scan_)); - - ScanFolder(); -} diff --git a/chrome/browser/media_galleries/media_folder_finder.h b/chrome/browser/media_galleries/media_folder_finder.h deleted file mode 100644 index 3dffe6f..0000000 --- a/chrome/browser/media_galleries/media_folder_finder.h +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_FOLDER_FINDER_H_ -#define CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_FOLDER_FINDER_H_ - -#include <map> -#include <vector> - -#include "base/callback.h" -#include "base/files/file_path.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/sequenced_task_runner.h" -#include "chrome/browser/media_galleries/media_scan_types.h" - -// MediaFolderFinder scans local hard drives and look for folders that contain -// media files. -class MediaFolderFinder { - public: - // Key: path to a folder - // Value: scan results for that folder, non-recursive. - typedef std::map<base::FilePath, MediaGalleryScanResult> - MediaFolderFinderResults; - - // |results| never contains entries for |graylisted_folders_| or parent - // directories of |graylisted_folders_|. - typedef base::Callback<void(bool /*success*/, - const MediaFolderFinderResults& /*results*/)> - MediaFolderFinderResultsCallback; - - // |callback| will get called when the scan finishes. If the object is deleted - // before it finishes, the scan will stop and |callback| will get called with - // success = false. - // MediaFolderFinder has a default set of per-platform paths to scan. - // Override in tests with SetRootsForTesting(). - explicit MediaFolderFinder(const MediaFolderFinderResultsCallback& callback); - virtual ~MediaFolderFinder(); - - // Start the scan. - virtual void StartScan(); - - const std::vector<base::FilePath>& graylisted_folders() const; - - private: - friend class MediaFolderFinderTest; - friend class MediaGalleriesPlatformAppBrowserTest; - - class Worker; - struct WorkerReply { - WorkerReply(); - WorkerReply(const WorkerReply& other); - ~WorkerReply(); - - MediaGalleryScanResult scan_result; - std::vector<base::FilePath> new_folders; - }; - - enum ScanState { - SCAN_STATE_NOT_STARTED, - SCAN_STATE_STARTED, - SCAN_STATE_FINISHED, - }; - - void SetRootsForTesting(const std::vector<base::FilePath>& roots); - - void OnInitialized(const std::vector<base::FilePath>& roots); - - // Scan a folder from |folders_to_scan_|. - void ScanFolder(); - - // Callback that handles the |reply| from |worker_| for a scanned |path|. - void GotScanResults(const base::FilePath& path, const WorkerReply& reply); - - const MediaFolderFinderResultsCallback results_callback_; - MediaFolderFinderResults results_; - - std::vector<base::FilePath> graylisted_folders_; - std::vector<base::FilePath> folders_to_scan_; - ScanState scan_state_; - - scoped_refptr<base::SequencedTaskRunner> worker_task_runner_; - - // Owned by MediaFolderFinder, but lives on |worker_task_runner_|. - Worker* worker_; - - // Set of roots to scan for testing. - bool has_roots_for_testing_; - std::vector<base::FilePath> roots_for_testing_; - - base::WeakPtrFactory<MediaFolderFinder> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(MediaFolderFinder); -}; - -#endif // CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_FOLDER_FINDER_H_ diff --git a/chrome/browser/media_galleries/media_folder_finder_unittest.cc b/chrome/browser/media_galleries/media_folder_finder_unittest.cc deleted file mode 100644 index b114be6..0000000 --- a/chrome/browser/media_galleries/media_folder_finder_unittest.cc +++ /dev/null @@ -1,405 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/media_galleries/media_folder_finder.h" - -#include <stddef.h> - -#include <set> -#include <string> - -#include "base/base_paths.h" -#include "base/bind.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/macros.h" -#include "base/strings/stringprintf.h" -#include "base/test/scoped_path_override.h" -#include "base/threading/sequenced_worker_pool.h" -#include "build/build_config.h" -#include "chrome/browser/media_galleries/media_scan_types.h" -#include "chrome/common/chrome_paths.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "content/public/test/test_utils.h" -#include "testing/gtest/include/gtest/gtest.h" - -class MediaFolderFinderTest : public testing::Test { - public: - MediaFolderFinderTest() { - } - - ~MediaFolderFinderTest() override {} - - void SetUp() override { ASSERT_TRUE(fake_dir_.CreateUniqueTempDir()); } - - void TearDown() override { ASSERT_EQ(NULL, media_folder_finder_.get()); } - - protected: - void CreateMediaFolderFinder( - const std::vector<base::FilePath> roots, - bool expected_success, - const MediaFolderFinder::MediaFolderFinderResults& expected_results) { - EXPECT_EQ(NULL, media_folder_finder_.get()); - received_results_ = false; - expected_success_ = expected_success; - expected_results_ = expected_results; - media_folder_finder_.reset( - new MediaFolderFinder(base::Bind(&MediaFolderFinderTest::OnGotResults, - base::Unretained(this)))); - media_folder_finder_->SetRootsForTesting(roots); - } - - void StartScan() { - media_folder_finder_->StartScan(); - } - - void DeleteMediaFolderFinder() { - EXPECT_TRUE(media_folder_finder_.get() != NULL); - media_folder_finder_.reset(); - } - - bool received_results() const { - return received_results_; - } - - const base::FilePath& fake_dir() const { - return fake_dir_.path(); - } - - void CreateTestDir(const base::FilePath& parent_dir) { - if (parent_dir == fake_dir()) - return; - - ASSERT_TRUE(fake_dir().IsParent(parent_dir)); - ASSERT_TRUE(base::CreateDirectory(parent_dir)); - } - - void CreateTestFile(const base::FilePath& parent_dir, - MediaGalleryScanFileType type, - size_t count, - bool big, - MediaFolderFinder::MediaFolderFinderResults* results) { - CreateTestDir(parent_dir); - - std::string extension; - size_t filesize; - MediaGalleryScanResult& result = (*results)[parent_dir]; - switch (type) { - case MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE: - extension = "jpg"; - filesize = 10; - result.image_count += count; - break; - case MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO: - extension = "wav"; - filesize = 20; - result.audio_count += count; - break; - case MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO: - extension = "avi"; - filesize = 30; - result.video_count += count; - break; - case MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN: - extension = "txt"; - filesize = 10; - if (IsEmptyScanResult(result)) - results->erase(parent_dir); - break; - default: - NOTREACHED(); - return; - } - if (big) - filesize *= 100000; - - for (size_t i = 0; i < count; ++i) { - base::FilePath test_file(parent_dir.AppendASCII("dummy." + extension)); - int uniquifier = - base::GetUniquePathNumber(test_file, base::FilePath::StringType()); - if (uniquifier > 0) { - test_file = test_file.InsertBeforeExtensionASCII( - base::StringPrintf(" (%d)", uniquifier)); - filesize += uniquifier; - } - - std::string dummy_data; - dummy_data.resize(filesize); - - int bytes_written = - base::WriteFile(test_file, dummy_data.c_str(), filesize); - ASSERT_GE(bytes_written, 0); - ASSERT_EQ(filesize, static_cast<size_t>(bytes_written)); - } - } - - void RunLoopUntilReceivedCallback() { - while (!received_results()) - content::RunAllBlockingPoolTasksUntilIdle(); - } - - private: - void OnGotResults( - bool success, - const MediaFolderFinder::MediaFolderFinderResults& results) { - received_results_ = true; - EXPECT_EQ(expected_success_, success); - std::set<base::FilePath> expected_keys = - GetKeysFromResults(expected_results_); - ASSERT_EQ(expected_keys, GetKeysFromResults(results)); - for (MediaFolderFinder::MediaFolderFinderResults::const_iterator it = - results.begin(); - it != results.end(); ++it) { - const base::FilePath& folder = it->first; - const MediaGalleryScanResult& expected = it->second; - const MediaGalleryScanResult& actual = results.find(folder)->second; - EXPECT_EQ(expected.image_count, actual.image_count) - << " Image count for " << folder.value(); - EXPECT_EQ(expected.audio_count, actual.audio_count) - << " Audio count for " << folder.value(); - EXPECT_EQ(expected.video_count, actual.video_count) - << " Video count for " << folder.value(); - } - } - - std::set<base::FilePath> GetKeysFromResults( - const MediaFolderFinder::MediaFolderFinderResults& results) { - std::set<base::FilePath> keys; - for (MediaFolderFinder::MediaFolderFinderResults::const_iterator it = - results.begin(); - it != results.end(); ++it) { - keys.insert(it->first); - } - return keys; - } - - content::TestBrowserThreadBundle thread_bundle_; - - base::ScopedTempDir fake_dir_; - - scoped_ptr<MediaFolderFinder> media_folder_finder_; - - bool expected_success_; - MediaFolderFinder::MediaFolderFinderResults expected_results_; - bool received_results_; - - DISALLOW_COPY_AND_ASSIGN(MediaFolderFinderTest); -}; - -TEST_F(MediaFolderFinderTest, NoScan) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - folders.push_back(fake_dir()); - CreateMediaFolderFinder(folders, false, expected_results); - DeleteMediaFolderFinder(); - EXPECT_TRUE(received_results()); -} - -TEST_F(MediaFolderFinderTest, ScanAndCancel) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - folders.push_back(fake_dir()); - CreateMediaFolderFinder(folders, false, expected_results); - StartScan(); - DeleteMediaFolderFinder(); - content::RunAllBlockingPoolTasksUntilIdle(); - EXPECT_TRUE(received_results()); -} - -TEST_F(MediaFolderFinderTest, ScanNothing) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - CreateMediaFolderFinder(folders, true, expected_results); - StartScan(); - RunLoopUntilReceivedCallback(); - DeleteMediaFolderFinder(); -} - -TEST_F(MediaFolderFinderTest, EmptyScan) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - folders.push_back(fake_dir()); - CreateMediaFolderFinder(folders, true, expected_results); - StartScan(); - RunLoopUntilReceivedCallback(); - DeleteMediaFolderFinder(); -} - -TEST_F(MediaFolderFinderTest, ScanMediaFiles) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - folders.push_back(fake_dir()); - - base::FilePath dir1 = fake_dir().AppendASCII("dir1"); - base::FilePath dir2 = fake_dir().AppendASCII("dir2"); - base::FilePath dir2_3 = dir2.AppendASCII("dir2_3"); - base::FilePath dir2_4 = dir2.AppendASCII("dir2_4"); - base::FilePath dir2_4_5 = dir2_4.AppendASCII("dir2_4_5"); - base::FilePath dir2_4_empty = dir2_4.AppendASCII("dir2_4_empty"); - base::FilePath dir_empty = fake_dir().AppendASCII("dir_empty"); - - CreateTestFile(dir1, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 2, true, - &expected_results); - CreateTestFile(dir1, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 1, false, - &expected_results); - CreateTestFile(dir1, MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN, 1, false, - &expected_results); - CreateTestFile(dir2_3, MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO, 4, true, - &expected_results); - CreateTestFile(dir2_3, MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO, 3, false, - &expected_results); - CreateTestFile(dir2_4, MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN, 5, false, - &expected_results); - CreateTestFile(dir2_4_5, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 2, true, - &expected_results); - CreateTestFile(dir2_4_5, MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO, 4, true, - &expected_results); - CreateTestFile(dir2_4_5, MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO, 1, true, - &expected_results); - CreateTestFile(dir2_4_5, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 5, false, - &expected_results); - CreateTestFile(dir2_4_5, MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO, 3, false, - &expected_results); - CreateTestFile(dir2_4_5, MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN, 3, true, - &expected_results); - CreateTestDir(dir2_4_empty); - CreateTestDir(dir_empty); - - CreateMediaFolderFinder(folders, true, expected_results); - StartScan(); - RunLoopUntilReceivedCallback(); - DeleteMediaFolderFinder(); -} - -TEST_F(MediaFolderFinderTest, SkipHiddenFiles) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - folders.push_back(fake_dir()); - - base::FilePath hidden_dir = fake_dir().AppendASCII(".hidden"); - - CreateTestFile(hidden_dir, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 2, true, - &expected_results); - expected_results.erase(hidden_dir); - - CreateMediaFolderFinder(folders, true, expected_results); - StartScan(); - RunLoopUntilReceivedCallback(); - DeleteMediaFolderFinder(); -} - -TEST_F(MediaFolderFinderTest, ScanIgnoresSmallMediaFiles) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - folders.push_back(fake_dir()); - - base::FilePath dir1 = fake_dir().AppendASCII("dir1"); - base::FilePath dir2 = fake_dir().AppendASCII("dir2"); - base::FilePath dir_empty = fake_dir().AppendASCII("dir_empty"); - - CreateTestFile(dir1, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 2, true, - &expected_results); - CreateTestFile(dir1, MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO, 1, false, - &expected_results); - CreateTestFile(dir1, MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN, 1, false, - &expected_results); - CreateTestFile(dir2, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 1, false, - &expected_results); - CreateTestFile(dir2, MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO, 3, false, - &expected_results); - CreateTestFile(dir2, MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO, 5, false, - &expected_results); - CreateTestFile(dir2, MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN, 1, true, - &expected_results); - CreateTestDir(dir_empty); - ASSERT_EQ(1U, expected_results.erase(dir2)); - - CreateMediaFolderFinder(folders, true, expected_results); - StartScan(); - RunLoopUntilReceivedCallback(); - DeleteMediaFolderFinder(); -} - -TEST_F(MediaFolderFinderTest, Overlap) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - folders.push_back(fake_dir()); - folders.push_back(fake_dir()); - - base::FilePath dir1 = fake_dir().AppendASCII("dir1"); - folders.push_back(dir1); - folders.push_back(dir1); - - CreateTestFile(dir1, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 1, true, - &expected_results); - - CreateMediaFolderFinder(folders, true, expected_results); - StartScan(); - RunLoopUntilReceivedCallback(); - DeleteMediaFolderFinder(); -} - -TEST_F(MediaFolderFinderTest, Prune) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - folders.push_back(fake_dir()); - -#if defined(OS_WIN) - int pruned_dir_key = base::DIR_IE_INTERNET_CACHE; -#elif defined(OS_MACOSX) - int pruned_dir_key = chrome::DIR_USER_LIBRARY; -#else - int pruned_dir_key = base::DIR_CACHE; -#endif - - base::FilePath fake_pruned_dir = fake_dir().AppendASCII("dir1"); - base::ScopedPathOverride scoped_fake_pruned_dir_override(pruned_dir_key, - fake_pruned_dir); - - CreateTestFile(fake_dir(), MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 1, true, - &expected_results); - CreateTestFile(fake_pruned_dir, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 1, true, - &expected_results); - - base::FilePath test_dir = fake_pruned_dir.AppendASCII("dir2"); - CreateTestFile(test_dir, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 1, true, - &expected_results); - - // |fake_pruned_dir| and |test_dir| are pruned. - expected_results.erase(fake_pruned_dir); - expected_results.erase(test_dir); - - CreateMediaFolderFinder(folders, true, expected_results); - StartScan(); - RunLoopUntilReceivedCallback(); - DeleteMediaFolderFinder(); -} - -TEST_F(MediaFolderFinderTest, Graylist) { - MediaFolderFinder::MediaFolderFinderResults expected_results; - std::vector<base::FilePath> folders; - folders.push_back(fake_dir()); - - base::FilePath fake_home_dir = fake_dir().AppendASCII("dir1"); - base::FilePath test_dir = fake_home_dir.AppendASCII("dir2"); - base::ScopedPathOverride scoped_fake_home_dir_override(base::DIR_HOME, - fake_home_dir); - - CreateTestFile(fake_dir(), MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 1, true, - &expected_results); - CreateTestFile(fake_home_dir, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 1, true, - &expected_results); - CreateTestFile(test_dir, MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE, 1, true, - &expected_results); - - // |fake_home_dir| and its ancestors do not show up in results. - expected_results.erase(fake_dir()); - expected_results.erase(fake_home_dir); - - CreateMediaFolderFinder(folders, true, expected_results); - StartScan(); - RunLoopUntilReceivedCallback(); - DeleteMediaFolderFinder(); -} diff --git a/chrome/browser/media_galleries/media_galleries_dialog_controller.h b/chrome/browser/media_galleries/media_galleries_dialog_controller.h index 969dbcb..b333040c 100644 --- a/chrome/browser/media_galleries/media_galleries_dialog_controller.h +++ b/chrome/browser/media_galleries/media_galleries_dialog_controller.h @@ -68,9 +68,6 @@ class MediaGalleriesDialogController { // Initial state of whether the dialog's confirmation button will be enabled. virtual bool IsAcceptAllowed() const = 0; - // Should the dialog present UI for the user to view the entry contents. - virtual bool ShouldShowFolderViewer(const Entry& entry) const = 0; - // The titles for different sections of entries. Empty hides the header. virtual std::vector<base::string16> GetSectionHeaders() const = 0; @@ -87,9 +84,6 @@ class MediaGalleriesDialogController { // An entry checkbox was toggled. virtual void DidToggleEntry(MediaGalleryPrefId id, bool selected) = 0; - // A folder viewer button was clicked for one of the entries. - virtual void DidClickOpenFolderViewer(MediaGalleryPrefId id) = 0; - // The forget command in the context menu was selected. virtual void DidForgetEntry(MediaGalleryPrefId id) = 0; diff --git a/chrome/browser/media_galleries/media_galleries_dialog_controller_mock.h b/chrome/browser/media_galleries/media_galleries_dialog_controller_mock.h index 02369ad..3c1c825 100644 --- a/chrome/browser/media_galleries/media_galleries_dialog_controller_mock.h +++ b/chrome/browser/media_galleries/media_galleries_dialog_controller_mock.h @@ -13,20 +13,18 @@ class MediaGalleriesDialogControllerMock : public MediaGalleriesDialogController { public: - explicit MediaGalleriesDialogControllerMock(); + MediaGalleriesDialogControllerMock(); virtual ~MediaGalleriesDialogControllerMock(); MOCK_CONST_METHOD0(GetHeader, base::string16()); MOCK_CONST_METHOD0(GetSubtext, base::string16()); MOCK_CONST_METHOD0(IsAcceptAllowed, bool()); - MOCK_CONST_METHOD1(ShouldShowFolderViewer, bool(const Entry&)); MOCK_CONST_METHOD0(GetSectionHeaders, std::vector<base::string16>()); MOCK_CONST_METHOD1(GetSectionEntries, Entries(size_t)); MOCK_CONST_METHOD0(GetAuxiliaryButtonText, base::string16()); MOCK_METHOD0(DidClickAuxiliaryButton, void()); MOCK_METHOD2(DidToggleEntry, void(MediaGalleryPrefId id, bool selected)); - MOCK_METHOD1(DidClickOpenFolderViewer, void(MediaGalleryPrefId id)); MOCK_METHOD1(DidForgetEntry, void(MediaGalleryPrefId id)); MOCK_CONST_METHOD0(GetAcceptButtonText, base::string16()); MOCK_METHOD1(DialogFinished, void(bool)); diff --git a/chrome/browser/media_galleries/media_galleries_histograms.h b/chrome/browser/media_galleries/media_galleries_histograms.h index 583a2b2..0b106cb 100644 --- a/chrome/browser/media_galleries/media_galleries_histograms.h +++ b/chrome/browser/media_galleries/media_galleries_histograms.h @@ -22,13 +22,13 @@ enum MediaGalleriesUsages { GET_ALL_MEDIA_FILE_SYSTEM_METADATA, GET_METADATA, ADD_USER_SELECTED_FOLDER, - START_MEDIA_SCAN, - CANCEL_MEDIA_SCAN, - ADD_SCAN_RESULTS, - SCAN_FINISHED, - ADD_SCAN_RESULTS_CANCELLED, - ADD_SCAN_RESULTS_ACCEPTED, - ADD_SCAN_RESULTS_FORGET_GALLERY, + DELETED_START_MEDIA_SCAN, + DELETED_CANCEL_MEDIA_SCAN, + DELETED_ADD_SCAN_RESULTS, + DELETED_SCAN_FINISHED, + DELETED_ADD_SCAN_RESULTS_CANCELLED, + DELETED_ADD_SCAN_RESULTS_ACCEPTED, + DELETED_ADD_SCAN_RESULTS_FORGET_GALLERY, DIALOG_FORGET_GALLERY, DROP_PERMISSION_FOR_MEDIA_FILE_SYSTEM, GET_ALL_GALLERY_WATCH, diff --git a/chrome/browser/media_galleries/media_galleries_permission_controller.cc b/chrome/browser/media_galleries/media_galleries_permission_controller.cc index 130049a..cbd2ab8 100644 --- a/chrome/browser/media_galleries/media_galleries_permission_controller.cc +++ b/chrome/browser/media_galleries/media_galleries_permission_controller.cc @@ -160,11 +160,6 @@ bool MediaGalleriesPermissionController::IsAcceptAllowed() const { return false; } -bool MediaGalleriesPermissionController::ShouldShowFolderViewer( - const Entry& entry) const { - return false; -} - std::vector<base::string16> MediaGalleriesPermissionController::GetSectionHeaders() const { std::vector<base::string16> result; @@ -247,11 +242,6 @@ void MediaGalleriesPermissionController::DidToggleEntry( // redrawn. } -void MediaGalleriesPermissionController::DidClickOpenFolderViewer( - GalleryDialogId gallery_id) { - NOTREACHED(); -} - void MediaGalleriesPermissionController::DidForgetEntry( GalleryDialogId gallery_id) { media_galleries::UsageCount(media_galleries::DIALOG_FORGET_GALLERY); diff --git a/chrome/browser/media_galleries/media_galleries_permission_controller.h b/chrome/browser/media_galleries/media_galleries_permission_controller.h index a299106..b27e8ef 100644 --- a/chrome/browser/media_galleries/media_galleries_permission_controller.h +++ b/chrome/browser/media_galleries/media_galleries_permission_controller.h @@ -61,14 +61,12 @@ class MediaGalleriesPermissionController base::string16 GetHeader() const override; base::string16 GetSubtext() const override; bool IsAcceptAllowed() const override; - bool ShouldShowFolderViewer(const Entry& entry) const override; std::vector<base::string16> GetSectionHeaders() const override; Entries GetSectionEntries(size_t index) const override; // Auxiliary button for this dialog is the 'Add Folder' button. base::string16 GetAuxiliaryButtonText() const override; void DidClickAuxiliaryButton() override; void DidToggleEntry(GalleryDialogId gallery_id, bool selected) override; - void DidClickOpenFolderViewer(GalleryDialogId gallery_id) override; void DidForgetEntry(GalleryDialogId gallery_id) override; base::string16 GetAcceptButtonText() const override; void DialogFinished(bool accepted) override; diff --git a/chrome/browser/media_galleries/media_galleries_preferences.cc b/chrome/browser/media_galleries/media_galleries_preferences.cc index 867f263..35f1d89 100644 --- a/chrome/browser/media_galleries/media_galleries_preferences.cc +++ b/chrome/browser/media_galleries/media_galleries_preferences.cc @@ -1306,18 +1306,6 @@ const MediaGalleriesPrefInfoMap& MediaGalleriesPreferences::known_galleries() return known_galleries_; } -base::Time MediaGalleriesPreferences::GetLastScanCompletionTime() const { - int64_t last_scan_time_internal = - profile_->GetPrefs()->GetInt64(prefs::kMediaGalleriesLastScanTime); - return base::Time::FromInternalValue(last_scan_time_internal); -} - -void MediaGalleriesPreferences::SetLastScanCompletionTime( - const base::Time& time) { - profile_->GetPrefs()->SetInt64(prefs::kMediaGalleriesLastScanTime, - time.ToInternalValue()); -} - void MediaGalleriesPreferences::Shutdown() { weak_factory_.InvalidateWeakPtrs(); profile_ = NULL; @@ -1336,8 +1324,6 @@ void MediaGalleriesPreferences::RegisterProfilePrefs( registry->RegisterListPref(prefs::kMediaGalleriesRememberedGalleries); registry->RegisterUint64Pref(prefs::kMediaGalleriesUniqueId, kInvalidMediaGalleryPrefId + 1); - registry->RegisterInt64Pref(prefs::kMediaGalleriesLastScanTime, - base::Time().ToInternalValue()); } bool MediaGalleriesPreferences::SetGalleryPermissionInPrefs( diff --git a/chrome/browser/media_galleries/media_galleries_preferences.h b/chrome/browser/media_galleries/media_galleries_preferences.h index 12fe922..2525a4b2 100644 --- a/chrome/browser/media_galleries/media_galleries_preferences.h +++ b/chrome/browser/media_galleries/media_galleries_preferences.h @@ -270,11 +270,6 @@ class MediaGalleriesPreferences const MediaGalleriesPrefInfoMap& known_galleries() const; - // These keep track of when we last successfully completed a media scan. - // This is used to provide cached results when appropriate. - base::Time GetLastScanCompletionTime() const; - void SetLastScanCompletionTime(const base::Time& time); - // KeyedService implementation: void Shutdown() override; diff --git a/chrome/browser/media_galleries/media_galleries_scan_result_controller.cc b/chrome/browser/media_galleries/media_galleries_scan_result_controller.cc deleted file mode 100644 index 263d1e7..0000000 --- a/chrome/browser/media_galleries/media_galleries_scan_result_controller.cc +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/media_galleries/media_galleries_scan_result_controller.h" - -#include <algorithm> -#include <list> - -#include "base/bind.h" -#include "base/logging.h" -#include "base/metrics/histogram.h" -#include "base/stl_util.h" -#include "base/strings/utf_string_conversions.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/media_galleries/media_file_system_registry.h" -#include "chrome/browser/media_galleries/media_galleries_histograms.h" -#include "chrome/browser/media_galleries/media_gallery_context_menu.h" -#include "chrome/browser/platform_util.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/grit/generated_resources.h" -#include "components/storage_monitor/storage_info.h" -#include "components/storage_monitor/storage_monitor.h" -#include "content/public/browser/web_contents.h" -#include "extensions/common/extension.h" -#include "extensions/common/permissions/media_galleries_permission.h" -#include "extensions/common/permissions/permissions_data.h" -#include "ui/base/l10n/l10n_util.h" - -using storage_monitor::StorageInfo; -using storage_monitor::StorageMonitor; - -namespace { - -// Comparator for sorting Entries -- more files first and then sorts by -// absolute path. -bool ScanResultsComparator( - const MediaGalleriesDialogController::Entry& a, - const MediaGalleriesDialogController::Entry& b) { - int a_media_count = a.pref_info.audio_count + a.pref_info.image_count + - a.pref_info.video_count; - int b_media_count = b.pref_info.audio_count + b.pref_info.image_count + - b.pref_info.video_count; - if (a_media_count == b_media_count) - return a.pref_info.AbsolutePath() < b.pref_info.AbsolutePath(); - return a_media_count > b_media_count; -} - -} // namespace - -// static -size_t MediaGalleriesScanResultController::ScanResultCountForExtension( - MediaGalleriesPreferences* preferences, - const extensions::Extension* extension) { - ScanResults scan_results; - UpdateScanResultsFromPreferences(preferences, extension, - MediaGalleryPrefIdSet(), &scan_results); - return scan_results.size(); -} - -MediaGalleriesScanResultController::MediaGalleriesScanResultController( - content::WebContents* web_contents, - const extensions::Extension& extension, - const base::Closure& on_finish) - : web_contents_(web_contents), - extension_(&extension), - on_finish_(on_finish), - create_dialog_callback_(base::Bind(&MediaGalleriesDialog::Create)) { - preferences_ = - g_browser_process->media_file_system_registry()->GetPreferences( - GetProfile()); - // Passing unretained pointer is safe, since the dialog controller - // is self-deleting, and so won't be deleted until it can be shown - // and then closed. - preferences_->EnsureInitialized(base::Bind( - &MediaGalleriesScanResultController::OnPreferencesInitialized, - base::Unretained(this))); - - // Unretained is safe because |this| owns |context_menu_|. - context_menu_.reset(new MediaGalleryContextMenu(base::Bind( - &MediaGalleriesScanResultController::DidForgetEntry, - base::Unretained(this)))); -} - -MediaGalleriesScanResultController::MediaGalleriesScanResultController( - const extensions::Extension& extension, - MediaGalleriesPreferences* preferences, - const CreateDialogCallback& create_dialog_callback, - const base::Closure& on_finish) - : web_contents_(NULL), - extension_(&extension), - on_finish_(on_finish), - preferences_(preferences), - create_dialog_callback_(create_dialog_callback) { - OnPreferencesInitialized(); -} - -MediaGalleriesScanResultController::~MediaGalleriesScanResultController() { - // |preferences_| may be NULL in tests. - if (preferences_) - preferences_->RemoveGalleryChangeObserver(this); - if (StorageMonitor::GetInstance()) - StorageMonitor::GetInstance()->RemoveObserver(this); -} - -base::string16 MediaGalleriesScanResultController::GetHeader() const { - return l10n_util::GetStringFUTF16( - IDS_MEDIA_GALLERIES_SCAN_RESULT_DIALOG_HEADER, - base::UTF8ToUTF16(extension_->name())); -} - -base::string16 MediaGalleriesScanResultController::GetSubtext() const { - extensions::MediaGalleriesPermission::CheckParam copy_to_param( - extensions::MediaGalleriesPermission::kCopyToPermission); - extensions::MediaGalleriesPermission::CheckParam delete_param( - extensions::MediaGalleriesPermission::kDeletePermission); - const extensions::PermissionsData* permissions_data = - extension_->permissions_data(); - bool has_copy_to_permission = permissions_data->CheckAPIPermissionWithParam( - extensions::APIPermission::kMediaGalleries, ©_to_param); - bool has_delete_permission = permissions_data->CheckAPIPermissionWithParam( - extensions::APIPermission::kMediaGalleries, &delete_param); - - int id; - if (has_copy_to_permission) - id = IDS_MEDIA_GALLERIES_SCAN_RESULT_DIALOG_SUBTEXT_READ_WRITE; - else if (has_delete_permission) - id = IDS_MEDIA_GALLERIES_SCAN_RESULT_DIALOG_SUBTEXT_READ_DELETE; - else - id = IDS_MEDIA_GALLERIES_SCAN_RESULT_DIALOG_SUBTEXT_READ_ONLY; - - return l10n_util::GetStringFUTF16(id, base::UTF8ToUTF16(extension_->name())); -} - -bool MediaGalleriesScanResultController::IsAcceptAllowed() const { - return true; -} - -bool MediaGalleriesScanResultController::ShouldShowFolderViewer( - const Entry& entry) const { - return entry.pref_info.IsGalleryAvailable(); -} - -std::vector<base::string16> -MediaGalleriesScanResultController::GetSectionHeaders() const { - std::vector<base::string16> result; - result.push_back(base::string16()); - return result; -} - -MediaGalleriesDialogController::Entries -MediaGalleriesScanResultController::GetSectionEntries( - size_t index) const { - DCHECK_EQ(0U, index); - Entries result; - result.reserve(scan_results_.size()); - for (ScanResults::const_iterator it = scan_results_.begin(); - it != scan_results_.end(); - ++it) { - result.push_back(it->second); - } - std::sort(result.begin(), result.end(), ScanResultsComparator); - return result; -} - -base::string16 -MediaGalleriesScanResultController::GetAuxiliaryButtonText() const { - return base::string16(); -} - -void MediaGalleriesScanResultController::DidClickAuxiliaryButton() { - NOTREACHED(); -} - -void MediaGalleriesScanResultController::DidToggleEntry( - MediaGalleryPrefId pref_id, bool selected) { - DCHECK(ContainsKey(scan_results_, pref_id)); - ScanResults::iterator entry = scan_results_.find(pref_id); - entry->second.selected = selected; -} - -void MediaGalleriesScanResultController::DidClickOpenFolderViewer( - MediaGalleryPrefId pref_id) { - ScanResults::const_iterator entry = scan_results_.find(pref_id); - if (entry == scan_results_.end()) { - NOTREACHED(); - return; - } - platform_util::OpenItem(GetProfile(), entry->second.pref_info.AbsolutePath(), - platform_util::OPEN_FOLDER, - platform_util::OpenOperationCallback()); -} - -void MediaGalleriesScanResultController::DidForgetEntry( - MediaGalleryPrefId pref_id) { - media_galleries::UsageCount(media_galleries::ADD_SCAN_RESULTS_FORGET_GALLERY); - results_to_remove_.insert(pref_id); - scan_results_.erase(pref_id); - dialog_->UpdateGalleries(); -} - -base::string16 MediaGalleriesScanResultController::GetAcceptButtonText() const { - return l10n_util::GetStringUTF16( - IDS_MEDIA_GALLERIES_SCAN_RESULT_DIALOG_CONFIRM); -} - -void MediaGalleriesScanResultController::DialogFinished(bool accepted) { - // No longer interested in preference updates (and the below code generates - // some). - // |preferences_| may be NULL in tests. - if (preferences_) - preferences_->RemoveGalleryChangeObserver(this); - - if (accepted) { - DCHECK(preferences_); - media_galleries::UsageCount(media_galleries::ADD_SCAN_RESULTS_ACCEPTED); - int granted = 0; - int total = 0; - for (ScanResults::const_iterator it = scan_results_.begin(); - it != scan_results_.end(); - ++it) { - if (it->second.selected) { - bool changed = preferences_->SetGalleryPermissionForExtension( - *extension_, it->first, true); - DCHECK(changed); - granted++; - } - total++; - } - if (total > 0) { - UMA_HISTOGRAM_PERCENTAGE("MediaGalleries.ScanGalleriesGranted", - (granted * 100 / total)); - } - for (MediaGalleryPrefIdSet::const_iterator it = results_to_remove_.begin(); - it != results_to_remove_.end(); - ++it) { - preferences_->ForgetGalleryById(*it); - } - } else { - media_galleries::UsageCount(media_galleries::ADD_SCAN_RESULTS_CANCELLED); - } - - on_finish_.Run(); - delete this; -} - -ui::MenuModel* MediaGalleriesScanResultController::GetContextMenu( - MediaGalleryPrefId id) { - context_menu_->set_pref_id(id); - return context_menu_.get(); -} - -content::WebContents* MediaGalleriesScanResultController::WebContents() { - return web_contents_; -} - -// static -void MediaGalleriesScanResultController::UpdateScanResultsFromPreferences( - MediaGalleriesPreferences* preferences, - const extensions::Extension* extension, - MediaGalleryPrefIdSet ignore_list, - ScanResults* scan_results) { - DCHECK(preferences->IsInitialized()); - const MediaGalleriesPrefInfoMap& galleries = preferences->known_galleries(); - MediaGalleryPrefIdSet permitted = - preferences->GalleriesForExtension(*extension); - - // Add or update any scan results that the extension doesn't already have - // access to or isn't in |ignore_list|. - for (MediaGalleriesPrefInfoMap::const_iterator it = galleries.begin(); - it != galleries.end(); - ++it) { - const MediaGalleryPrefInfo& gallery = it->second; - if ((gallery.audio_count || gallery.image_count || gallery.video_count) && - !gallery.IsBlackListedType() && - !ContainsKey(permitted, gallery.pref_id) && - !ContainsKey(ignore_list, gallery.pref_id)) { - ScanResults::iterator existing = scan_results->find(gallery.pref_id); - if (existing == scan_results->end()) { - // Default to selected. - (*scan_results)[gallery.pref_id] = Entry(gallery, true); - } else { - // Update pref_info, in case anything has been updated. - existing->second.pref_info = gallery; - } - } - } - - // Remove anything from |scan_results| that's no longer valid or the user - // already has access to. - std::list<ScanResults::iterator> to_remove; - for (ScanResults::iterator it = scan_results->begin(); - it != scan_results->end(); - ++it) { - MediaGalleriesPrefInfoMap::const_iterator pref_gallery = - galleries.find(it->first); - if (pref_gallery == galleries.end() || - pref_gallery->second.IsBlackListedType() || - ContainsKey(permitted, it->first)) { - to_remove.push_back(it); - } - } - while (!to_remove.empty()) { - scan_results->erase(to_remove.front()); - to_remove.pop_front(); - } -} - -void MediaGalleriesScanResultController::OnPreferencesInitialized() { - // These may be NULL in tests. - if (StorageMonitor::GetInstance()) - StorageMonitor::GetInstance()->AddObserver(this); - if (preferences_) { - preferences_->AddGalleryChangeObserver(this); - UpdateScanResultsFromPreferences(preferences_, extension_, - results_to_remove_, &scan_results_); - } - - dialog_.reset(create_dialog_callback_.Run(this)); -} - -void MediaGalleriesScanResultController::OnPreferenceUpdate( - const std::string& extension_id) { - if (extension_id == extension_->id()) { - UpdateScanResultsFromPreferences(preferences_, extension_, - results_to_remove_, &scan_results_); - dialog_->UpdateGalleries(); - } -} - -void MediaGalleriesScanResultController::OnRemovableDeviceUpdate( - const std::string& device_id) { - for (ScanResults::const_iterator it = scan_results_.begin(); - it != scan_results_.end(); - ++it) { - if (it->second.pref_info.device_id == device_id) { - dialog_->UpdateGalleries(); - return; - } - } -} - -Profile* MediaGalleriesScanResultController::GetProfile() const { - return Profile::FromBrowserContext(web_contents_->GetBrowserContext()); -} - -void MediaGalleriesScanResultController::OnRemovableStorageAttached( - const StorageInfo& info) { - OnRemovableDeviceUpdate(info.device_id()); -} - -void MediaGalleriesScanResultController::OnRemovableStorageDetached( - const StorageInfo& info) { - OnRemovableDeviceUpdate(info.device_id()); -} - -void MediaGalleriesScanResultController::OnPermissionAdded( - MediaGalleriesPreferences* /*pref*/, - const std::string& extension_id, - MediaGalleryPrefId /*pref_id*/) { - OnPreferenceUpdate(extension_id); -} - -void MediaGalleriesScanResultController::OnPermissionRemoved( - MediaGalleriesPreferences* /*pref*/, - const std::string& extension_id, - MediaGalleryPrefId /*pref_id*/) { - OnPreferenceUpdate(extension_id); -} - -void MediaGalleriesScanResultController::OnGalleryAdded( - MediaGalleriesPreferences* /*prefs*/, - MediaGalleryPrefId /*pref_id*/) { - OnPreferenceUpdate(extension_->id()); -} - -void MediaGalleriesScanResultController::OnGalleryRemoved( - MediaGalleriesPreferences* /*prefs*/, - MediaGalleryPrefId /*pref_id*/) { - OnPreferenceUpdate(extension_->id()); -} - -void MediaGalleriesScanResultController::OnGalleryInfoUpdated( - MediaGalleriesPreferences* /*prefs*/, - MediaGalleryPrefId /*pref_id*/) { - OnPreferenceUpdate(extension_->id()); -} diff --git a/chrome/browser/media_galleries/media_galleries_scan_result_controller.h b/chrome/browser/media_galleries/media_galleries_scan_result_controller.h deleted file mode 100644 index 3774acd..0000000 --- a/chrome/browser/media_galleries/media_galleries_scan_result_controller.h +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_GALLERIES_SCAN_RESULT_CONTROLLER_H_ -#define CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_GALLERIES_SCAN_RESULT_CONTROLLER_H_ - -#include <stddef.h> - -#include <map> -#include <set> -#include <string> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" -#include "chrome/browser/media_galleries/media_galleries_dialog_controller.h" -#include "chrome/browser/media_galleries/media_galleries_preferences.h" -#include "components/storage_monitor/removable_storage_observer.h" - -namespace content { -class WebContents; -} - -namespace extensions { -class Extension; -} - -namespace ui { -class MenuModel; -} - -class MediaGalleriesScanResultController; -class MediaGalleryContextMenu; -class Profile; - -// The controller is responsible for handling the logic of the dialog and -// interfacing with the model (i.e., MediaGalleriesPreferences). It shows -// the dialog and owns itself. -class MediaGalleriesScanResultController - : public MediaGalleriesDialogController, - public storage_monitor::RemovableStorageObserver, - public MediaGalleriesPreferences::GalleryChangeObserver { - public: - // |preferences| must be already initialized. - static size_t ScanResultCountForExtension( - MediaGalleriesPreferences* preferences, - const extensions::Extension* extension); - - // The constructor creates a dialog controller which owns itself. - MediaGalleriesScanResultController( - content::WebContents* web_contents, - const extensions::Extension& extension, - const base::Closure& on_finish); - - // MediaGalleriesDialogController implementation. - base::string16 GetHeader() const override; - base::string16 GetSubtext() const override; - bool IsAcceptAllowed() const override; - bool ShouldShowFolderViewer(const Entry& entry) const override; - std::vector<base::string16> GetSectionHeaders() const override; - Entries GetSectionEntries(size_t index) const override; - base::string16 GetAuxiliaryButtonText() const override; - void DidClickAuxiliaryButton() override; - void DidToggleEntry(MediaGalleryPrefId id, bool selected) override; - void DidClickOpenFolderViewer(MediaGalleryPrefId id) override; - void DidForgetEntry(MediaGalleryPrefId id) override; - base::string16 GetAcceptButtonText() const override; - void DialogFinished(bool accepted) override; - ui::MenuModel* GetContextMenu(MediaGalleryPrefId id) override; - content::WebContents* WebContents() override; - - protected: - typedef base::Callback<MediaGalleriesDialog* ( - MediaGalleriesDialogController*)> CreateDialogCallback; - typedef std::map<MediaGalleryPrefId, Entry> ScanResults; - - // Updates |scan_results| from |preferences|. Will not add galleries from - // |ignore_list| onto |scan_results|. - static void UpdateScanResultsFromPreferences( - MediaGalleriesPreferences* preferences, - const extensions::Extension* extension, - MediaGalleryPrefIdSet ignore_list, - ScanResults* scan_results); - - // Used for unit tests. - MediaGalleriesScanResultController( - const extensions::Extension& extension, - MediaGalleriesPreferences* preferences_, - const CreateDialogCallback& create_dialog_callback, - const base::Closure& on_finish); - - ~MediaGalleriesScanResultController() override; - - private: - friend class MediaGalleriesScanResultControllerTest; - friend class MediaGalleriesScanResultCocoaTest; - friend class TestMediaGalleriesAddScanResultsFunction; - - // Bottom half of constructor -- called when |preferences_| is initialized. - void OnPreferencesInitialized(); - - // Used to keep the dialog in sync with the preferences. - void OnPreferenceUpdate(const std::string& extension_id); - - // Used to keep the dialog in sync with attached and detached devices. - void OnRemovableDeviceUpdate(const std::string& device_id); - - Profile* GetProfile() const; - - // RemovableStorageObserver implementation. - // Used to keep dialog in sync with removable device status. - void OnRemovableStorageAttached( - const storage_monitor::StorageInfo& info) override; - void OnRemovableStorageDetached( - const storage_monitor::StorageInfo& info) override; - - // MediaGalleriesPreferences::GalleryChangeObserver implementations. - // Used to keep the dialog in sync when the preferences change. - void OnPermissionAdded(MediaGalleriesPreferences* pref, - const std::string& extension_id, - MediaGalleryPrefId pref_id) override; - void OnPermissionRemoved(MediaGalleriesPreferences* pref, - const std::string& extension_id, - MediaGalleryPrefId pref_id) override; - void OnGalleryAdded(MediaGalleriesPreferences* pref, - MediaGalleryPrefId pref_id) override; - void OnGalleryRemoved(MediaGalleriesPreferences* pref, - MediaGalleryPrefId pref_id) override; - void OnGalleryInfoUpdated(MediaGalleriesPreferences* pref, - MediaGalleryPrefId pref_id) override; - - // The web contents from which the request originated. - content::WebContents* web_contents_; - - // This is just a reference, but it's assumed that it won't become invalid - // while the dialog is showing. - const extensions::Extension* extension_; - - // The scan results that aren't blacklisted and this extension doesn't - // already have access to. - ScanResults scan_results_; - - // The set of scan results which should be removed (blacklisted) - unless - // the user clicks Cancel. - MediaGalleryPrefIdSet results_to_remove_; - - // Callback to run when the dialog closes. - base::Closure on_finish_; - - // The model that tracks galleries and extensions' permissions. - // This is the authoritative source for gallery information. - MediaGalleriesPreferences* preferences_; - - // Creates the dialog. Only changed for unit tests. - CreateDialogCallback create_dialog_callback_; - - // The view that's showing. - scoped_ptr<MediaGalleriesDialog> dialog_; - - scoped_ptr<MediaGalleryContextMenu> context_menu_; - - DISALLOW_COPY_AND_ASSIGN(MediaGalleriesScanResultController); -}; - -#endif // CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_GALLERIES_SCAN_RESULT_CONTROLLER_H_ diff --git a/chrome/browser/media_galleries/media_galleries_scan_result_controller_unittest.cc b/chrome/browser/media_galleries/media_galleries_scan_result_controller_unittest.cc deleted file mode 100644 index c84f4f0..0000000 --- a/chrome/browser/media_galleries/media_galleries_scan_result_controller_unittest.cc +++ /dev/null @@ -1,426 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stddef.h> - -#include "base/bind.h" -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/run_loop.h" -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "build/build_config.h" -#include "chrome/browser/extensions/test_extension_system.h" -#include "chrome/browser/media_galleries/media_galleries_dialog_controller_test_util.h" -#include "chrome/browser/media_galleries/media_galleries_preferences.h" -#include "chrome/browser/media_galleries/media_galleries_scan_result_controller.h" -#include "chrome/browser/media_galleries/media_galleries_test_util.h" -#include "chrome/test/base/testing_profile.h" -#include "components/storage_monitor/test_storage_monitor.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "extensions/browser/extension_system.h" -#include "extensions/common/extension.h" -#include "extensions/common/permissions/media_galleries_permission.h" -#include "testing/gtest/include/gtest/gtest.h" - -#if defined(OS_CHROMEOS) -#include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h" -#include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chrome/browser/chromeos/settings/device_settings_service.h" -#endif - -class MediaGalleriesScanResultControllerTest : public testing::Test { - public: - MediaGalleriesScanResultControllerTest() - : dialog_(NULL), - dialog_update_count_at_destruction_(0), - controller_(NULL), - profile_(new TestingProfile()), - weak_factory_(this) { - } - - ~MediaGalleriesScanResultControllerTest() override { - EXPECT_FALSE(controller_); - EXPECT_FALSE(dialog_); - } - - void SetUp() override { - ASSERT_TRUE(storage_monitor::TestStorageMonitor::CreateAndInstall()); - - extensions::TestExtensionSystem* extension_system( - static_cast<extensions::TestExtensionSystem*>( - extensions::ExtensionSystem::Get(profile_.get()))); - extension_system->CreateExtensionService( - base::CommandLine::ForCurrentProcess(), base::FilePath(), false); - - gallery_prefs_.reset(new MediaGalleriesPreferences(profile_.get())); - base::RunLoop loop; - gallery_prefs_->EnsureInitialized(loop.QuitClosure()); - loop.Run(); - - std::vector<std::string> read_permissions; - read_permissions.push_back( - extensions::MediaGalleriesPermission::kReadPermission); - extension_ = AddMediaGalleriesApp("read", read_permissions, profile_.get()); - } - - void TearDown() override { storage_monitor::TestStorageMonitor::Destroy(); } - - void StartDialog() { - ASSERT_FALSE(controller_); - controller_ = new MediaGalleriesScanResultController( - *extension_.get(), - gallery_prefs_.get(), - base::Bind( - &MediaGalleriesScanResultControllerTest::CreateMockDialog, - base::Unretained(this)), - base::Bind( - &MediaGalleriesScanResultControllerTest::OnControllerDone, - base::Unretained(this))); - } - - size_t GetFirstSectionSize() const { - return controller()->GetSectionEntries(0).size(); - } - - MediaGalleriesScanResultController* controller() const { - return controller_; - } - - MockMediaGalleriesDialog* dialog() { - return dialog_; - } - - int dialog_update_count_at_destruction() { - EXPECT_FALSE(dialog_); - return dialog_update_count_at_destruction_; - } - - extensions::Extension* extension() { - return extension_.get(); - } - - MediaGalleriesPreferences* gallery_prefs() { - return gallery_prefs_.get(); - } - - MediaGalleryPrefId AddGallery(const std::string& path, - MediaGalleryPrefInfo::Type type, - int audio_count, int image_count, - int video_count) { - MediaGalleryPrefInfo gallery_info; - gallery_prefs_->LookUpGalleryByPath(MakeMediaGalleriesTestingPath(path), - &gallery_info); - return gallery_prefs_->AddGallery( - gallery_info.device_id, - gallery_info.path, - type, - gallery_info.volume_label, - gallery_info.vendor_name, - gallery_info.model_name, - gallery_info.total_size_in_bytes, - gallery_info.last_attach_time, - audio_count, image_count, video_count); - } - - MediaGalleryPrefId AddScanResult(const std::string& path, int audio_count, - int image_count, int video_count) { - return AddGallery(path, MediaGalleryPrefInfo::kScanResult, audio_count, - image_count, video_count); - } - - private: - MediaGalleriesDialog* CreateMockDialog( - MediaGalleriesDialogController* controller) { - EXPECT_FALSE(dialog_); - dialog_update_count_at_destruction_ = 0; - dialog_ = new MockMediaGalleriesDialog(base::Bind( - &MediaGalleriesScanResultControllerTest::OnDialogDestroyed, - weak_factory_.GetWeakPtr())); - return dialog_; - } - - void OnDialogDestroyed(int update_count) { - EXPECT_TRUE(dialog_); - dialog_update_count_at_destruction_ = update_count; - dialog_ = NULL; - } - - void OnControllerDone() { - controller_ = NULL; - } - - // Needed for extension service & friends to work. - content::TestBrowserThreadBundle thread_bundle_; - - // The dialog is owned by the controller, but this pointer should only be - // valid while the dialog is live within the controller. - MockMediaGalleriesDialog* dialog_; - int dialog_update_count_at_destruction_; - - // The controller owns itself. - MediaGalleriesScanResultController* controller_; - - scoped_refptr<extensions::Extension> extension_; - - EnsureMediaDirectoriesExists mock_gallery_locations_; - -#if defined OS_CHROMEOS - chromeos::ScopedTestDeviceSettingsService test_device_settings_service_; - chromeos::ScopedTestCrosSettings test_cros_settings_; - chromeos::ScopedTestUserManager test_user_manager_; -#endif - - storage_monitor::TestStorageMonitor monitor_; - scoped_ptr<TestingProfile> profile_; - scoped_ptr<MediaGalleriesPreferences> gallery_prefs_; - - base::WeakPtrFactory<MediaGalleriesScanResultControllerTest> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(MediaGalleriesScanResultControllerTest); -}; - -TEST_F(MediaGalleriesScanResultControllerTest, EmptyDialog) { - StartDialog(); - EXPECT_TRUE(controller()); - EXPECT_TRUE(dialog()); - EXPECT_EQ(0U, GetFirstSectionSize()); - - controller()->DialogFinished(true); - EXPECT_FALSE(controller()); - EXPECT_FALSE(dialog()); - EXPECT_EQ(0, dialog_update_count_at_destruction()); -} - -TEST_F(MediaGalleriesScanResultControllerTest, AddScanResults) { - // Start with two scan results. - MediaGalleryPrefId scan_id = AddScanResult("scan_id", 1, 0, 0); - MediaGalleryPrefId auto_id = - AddGallery("auto_id", MediaGalleryPrefInfo::kAutoDetected, 2, 0, 0); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - - // Show the dialog, but cancel it. - StartDialog(); - EXPECT_EQ(2U, GetFirstSectionSize()); - controller()->DialogFinished(false); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - - // Show the dialog, unselect both and accept it. - StartDialog(); - EXPECT_EQ(2U, GetFirstSectionSize()); - controller()->DidToggleEntry(scan_id, false); - controller()->DidToggleEntry(auto_id, false); - controller()->DialogFinished(true); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - - // Show the dialog, leave one selected and accept it. - StartDialog(); - EXPECT_EQ(2U, GetFirstSectionSize()); - controller()->DidToggleEntry(scan_id, false); - controller()->DialogFinished(true); - MediaGalleryPrefIdSet permitted = - gallery_prefs()->GalleriesForExtension(*extension()); - ASSERT_EQ(1U, permitted.size()); - EXPECT_EQ(auto_id, *permitted.begin()); - - // Show the dialog, toggle the remaining entry twice and then accept it. - StartDialog(); - EXPECT_EQ(1U, GetFirstSectionSize()); - controller()->DidToggleEntry(scan_id, false); - controller()->DidToggleEntry(scan_id, true); - controller()->DialogFinished(true); - EXPECT_EQ(2U, gallery_prefs()->GalleriesForExtension(*extension()).size()); -} - -TEST_F(MediaGalleriesScanResultControllerTest, Blacklisted) { - // Start with two scan results. - MediaGalleryPrefId scan_id = AddScanResult("scan_id", 1, 0, 0); - MediaGalleryPrefId auto_id = - AddGallery("auto_id", MediaGalleryPrefInfo::kAutoDetected, 2, 0, 0); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - - // Show the dialog, but cancel it. - StartDialog(); - EXPECT_EQ(2U, GetFirstSectionSize()); - controller()->DialogFinished(false); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - - // Blacklist one and try again. - gallery_prefs()->ForgetGalleryById(scan_id); - StartDialog(); - EXPECT_EQ(1U, GetFirstSectionSize()); - controller()->DialogFinished(false); - - // Adding it as a user gallery should change its type. - AddGallery("scan_id", MediaGalleryPrefInfo::kUserAdded, 1, 0, 0); - StartDialog(); - EXPECT_EQ(2U, GetFirstSectionSize()); - - // Blacklisting the other while the dialog is open should remove it. - gallery_prefs()->ForgetGalleryById(auto_id); - EXPECT_EQ(1U, GetFirstSectionSize()); - controller()->DialogFinished(false); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - EXPECT_EQ(1, dialog_update_count_at_destruction()); -} - -TEST_F(MediaGalleriesScanResultControllerTest, PrefUpdates) { - MediaGalleryPrefId selected = AddScanResult("selected", 1, 0, 0); - MediaGalleryPrefId unselected = AddScanResult("unselected", 1, 0, 0); - MediaGalleryPrefId selected_add_permission = - AddScanResult("selected_add_permission", 1, 0, 0); - MediaGalleryPrefId unselected_add_permission = - AddScanResult("unselected_add_permission", 1, 0, 0); - MediaGalleryPrefId selected_removed = - AddScanResult("selected_removed", 1, 0, 0); - MediaGalleryPrefId unselected_removed = - AddScanResult("unselected_removed", 1, 0, 0); - MediaGalleryPrefId selected_update = - AddScanResult("selected_update", 1, 0, 0); - MediaGalleryPrefId unselected_update = - AddScanResult("unselected_update", 1, 0, 0); - - gallery_prefs()->AddGalleryByPath(MakeMediaGalleriesTestingPath("user"), - MediaGalleryPrefInfo::kUserAdded); - gallery_prefs()->AddGalleryByPath( - MakeMediaGalleriesTestingPath("auto_detected"), - MediaGalleryPrefInfo::kAutoDetected); - MediaGalleryPrefId blacklisted = gallery_prefs()->AddGalleryByPath( - MakeMediaGalleriesTestingPath("blacklisted"), - MediaGalleryPrefInfo::kAutoDetected); - gallery_prefs()->ForgetGalleryById(blacklisted); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - - StartDialog(); - EXPECT_EQ(8U, GetFirstSectionSize()); - controller()->DidToggleEntry(unselected, false); - controller()->DidToggleEntry(unselected_add_permission, false); - controller()->DidToggleEntry(unselected_removed, false); - controller()->DidToggleEntry(unselected_update, false); - EXPECT_EQ(0, dialog()->update_count()); - EXPECT_EQ(8U, GetFirstSectionSize()); - - // Add permission. - gallery_prefs()->SetGalleryPermissionForExtension(*extension(), - unselected_add_permission, - true); - EXPECT_EQ(1, dialog()->update_count()); - EXPECT_EQ(7U, GetFirstSectionSize()); - gallery_prefs()->SetGalleryPermissionForExtension(*extension(), - selected_add_permission, - true); - EXPECT_EQ(2, dialog()->update_count()); - EXPECT_EQ(6U, GetFirstSectionSize()); - - // Blacklist scan results. - gallery_prefs()->ForgetGalleryById(unselected_removed); - EXPECT_EQ(3, dialog()->update_count()); - EXPECT_EQ(5U, GetFirstSectionSize()); - gallery_prefs()->ForgetGalleryById(selected_removed); - EXPECT_EQ(4, dialog()->update_count()); - EXPECT_EQ(4U, GetFirstSectionSize()); - - // Update names. - const MediaGalleryPrefInfo& unselected_update_info = - gallery_prefs()->known_galleries().find(unselected_update)->second; - gallery_prefs()->AddGallery( - unselected_update_info.device_id, base::FilePath(), - MediaGalleryPrefInfo::kScanResult, - base::ASCIIToUTF16("Updated & Unselected"), - base::string16(), base::string16(), 0, base::Time(), 1, 0, 0); - EXPECT_EQ(5, dialog()->update_count()); - EXPECT_EQ(4U, GetFirstSectionSize()); - const MediaGalleryPrefInfo& selected_update_info = - gallery_prefs()->known_galleries().find(selected_update)->second; - gallery_prefs()->AddGallery( - selected_update_info.device_id, base::FilePath(), - MediaGalleryPrefInfo::kScanResult, - base::ASCIIToUTF16("Updated & Selected"), - base::string16(), base::string16(), 0, base::Time(), 1, 0, 0); - EXPECT_EQ(6, dialog()->update_count()); - EXPECT_EQ(4U, GetFirstSectionSize()); - - MediaGalleriesDialogController::Entries results = - controller()->GetSectionEntries(0); - EXPECT_EQ(selected, results[0].pref_info.pref_id); - EXPECT_TRUE(results[0].selected); - EXPECT_EQ(selected_update, results[1].pref_info.pref_id); - EXPECT_TRUE(results[1].selected); - EXPECT_EQ(base::ASCIIToUTF16("Updated & Selected"), - results[1].pref_info.volume_label); - EXPECT_EQ(unselected, results[2].pref_info.pref_id); - EXPECT_FALSE(results[2].selected); - EXPECT_EQ(unselected_update, results[3].pref_info.pref_id); - EXPECT_FALSE(results[3].selected); - EXPECT_EQ(base::ASCIIToUTF16("Updated & Unselected"), - results[3].pref_info.volume_label); - - controller()->DialogFinished(true); - EXPECT_EQ(4U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - StartDialog(); - EXPECT_EQ(2U, GetFirstSectionSize()); - controller()->DialogFinished(false); -} - -TEST_F(MediaGalleriesScanResultControllerTest, ForgetGallery) { - // Start with two scan results. - MediaGalleryPrefId scan1 = AddScanResult("scan1", 1, 0, 0); - MediaGalleryPrefId scan2 = AddScanResult("scan2", 2, 0, 0); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - - // Remove one and then cancel. - StartDialog(); - EXPECT_EQ(2U, GetFirstSectionSize()); - controller()->DidForgetEntry(scan1); - controller()->DialogFinished(false); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - - // Remove one and then have it blacklisted from prefs. - StartDialog(); - EXPECT_EQ(2U, GetFirstSectionSize()); - controller()->DidForgetEntry(scan1); - EXPECT_EQ(1, dialog()->update_count()); - controller()->DidToggleEntry(scan2, false); // Uncheck the second. - gallery_prefs()->ForgetGalleryById(scan1); - controller()->DialogFinished(true); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - EXPECT_EQ(2, dialog_update_count_at_destruction()); - - // Remove the other. - StartDialog(); - EXPECT_EQ(1U, GetFirstSectionSize()); - controller()->DidForgetEntry(scan2); - controller()->DialogFinished(true); - EXPECT_EQ(0U, gallery_prefs()->GalleriesForExtension(*extension()).size()); - - // Check that nothing shows up. - StartDialog(); - EXPECT_EQ(0U, GetFirstSectionSize()); - controller()->DialogFinished(false); -} - -TEST_F(MediaGalleriesScanResultControllerTest, SortOrder) { - // Intentionally out of order numerically and alphabetically. - MediaGalleryPrefId third = AddScanResult("third", 2, 2, 2); - MediaGalleryPrefId second = - AddGallery("second", MediaGalleryPrefInfo::kAutoDetected, 9, 0, 0); - MediaGalleryPrefId first = AddScanResult("first", 8, 2, 3); - MediaGalleryPrefId fifth = AddScanResult("abb", 3, 0, 0); - MediaGalleryPrefId fourth = AddScanResult("aaa", 3, 0, 0); - - StartDialog(); - MediaGalleriesDialogController::Entries results = - controller()->GetSectionEntries(0); - ASSERT_EQ(5U, results.size()); - EXPECT_EQ(first, results[0].pref_info.pref_id); - EXPECT_EQ(second, results[1].pref_info.pref_id); - EXPECT_EQ(third, results[2].pref_info.pref_id); - EXPECT_EQ(fourth, results[3].pref_info.pref_id); - EXPECT_EQ(fifth, results[4].pref_info.pref_id); - controller()->DialogFinished(false); -} diff --git a/chrome/browser/media_galleries/media_scan_manager.cc b/chrome/browser/media_galleries/media_scan_manager.cc deleted file mode 100644 index 93fffb4..0000000 --- a/chrome/browser/media_galleries/media_scan_manager.cc +++ /dev/null @@ -1,558 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/media_galleries/media_scan_manager.h" - -#include <stddef.h> - -#include "base/files/file_enumerator.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/metrics/histogram.h" -#include "base/time/time.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/media_galleries/media_galleries_preferences.h" -#include "chrome/browser/media_galleries/media_galleries_preferences_factory.h" -#include "chrome/browser/media_galleries/media_scan_manager_observer.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/extensions/api/media_galleries.h" -#include "content/public/browser/browser_thread.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/browser/extension_system.h" -#include "extensions/common/extension.h" - -using extensions::ExtensionRegistry; - -namespace media_galleries = extensions::api::media_galleries; - -namespace { - -typedef std::set<std::string /*extension id*/> ScanningExtensionIdSet; - -// When multiple scan results have the same parent, sometimes it makes sense -// to combine them into a single scan result at the parent. This constant -// governs when that happens; kContainerDirectoryMinimumPercent percent of the -// directories in the parent directory must be scan results. -const int kContainerDirectoryMinimumPercent = 80; - -// How long after a completed media scan can we provide the cached results. -const int kScanResultsExpiryTimeInHours = 24; - -struct LocationInfo { - LocationInfo() - : pref_id(kInvalidMediaGalleryPrefId), - type(MediaGalleryPrefInfo::kInvalidType) {} - LocationInfo(MediaGalleryPrefId pref_id, MediaGalleryPrefInfo::Type type, - base::FilePath path) - : pref_id(pref_id), type(type), path(path) {} - // Highest priority comparison by path, next by type (scan result last), - // then by pref id (invalid last). - bool operator<(const LocationInfo& rhs) const { - if (path.value() == rhs.path.value()) { - if (type == rhs.type) { - return pref_id > rhs.pref_id; - } - return rhs.type == MediaGalleryPrefInfo::kScanResult; - } - return path.value() < rhs.path.value(); - } - - MediaGalleryPrefId pref_id; - MediaGalleryPrefInfo::Type type; - base::FilePath path; - MediaGalleryScanResult file_counts; -}; - -// Finds new scan results that are shadowed (the same location, or a child) by -// existing locations and moves them from |found_folders| to |child_folders|. -// Also moves new scan results that are shadowed by other new scan results -// to |child_folders|. -void PartitionChildScanResults( - MediaGalleriesPreferences* preferences, - MediaFolderFinder::MediaFolderFinderResults* found_folders, - MediaFolderFinder::MediaFolderFinderResults* child_folders) { - // Construct a list with everything in it. - std::vector<LocationInfo> all_locations; - for (MediaFolderFinder::MediaFolderFinderResults::const_iterator it = - found_folders->begin(); it != found_folders->end(); ++it) { - all_locations.push_back(LocationInfo(kInvalidMediaGalleryPrefId, - MediaGalleryPrefInfo::kScanResult, - it->first)); - all_locations.back().file_counts = it->second; - } - const MediaGalleriesPrefInfoMap& known_galleries = - preferences->known_galleries(); - for (MediaGalleriesPrefInfoMap::const_iterator it = known_galleries.begin(); - it != known_galleries.end(); - ++it) { - all_locations.push_back(LocationInfo(it->second.pref_id, it->second.type, - it->second.AbsolutePath())); - } - // Sorting on path should put all paths that are prefixes of other paths - // next to each other, with the shortest one first. - std::sort(all_locations.begin(), all_locations.end()); - - size_t previous_parent_index = 0; - for (size_t i = 1; i < all_locations.size(); i++) { - const LocationInfo& current = all_locations[i]; - const LocationInfo& previous_parent = all_locations[previous_parent_index]; - bool is_child = previous_parent.path.IsParent(current.path); - if (current.type == MediaGalleryPrefInfo::kScanResult && - current.pref_id == kInvalidMediaGalleryPrefId && - (is_child || previous_parent.path == current.path)) { - // Move new scan results that are shadowed. - (*child_folders)[current.path] = current.file_counts; - found_folders->erase(current.path); - } else if (!is_child) { - previous_parent_index = i; - } - } -} - -MediaGalleryScanResult SumFilesUnderPath( - const base::FilePath& path, - const MediaFolderFinder::MediaFolderFinderResults& candidates) { - MediaGalleryScanResult results; - for (MediaFolderFinder::MediaFolderFinderResults::const_iterator it = - candidates.begin(); it != candidates.end(); ++it) { - if (it->first == path || path.IsParent(it->first)) { - results.audio_count += it->second.audio_count; - results.image_count += it->second.image_count; - results.video_count += it->second.video_count; - } - } - return results; -} - -void AddScanResultsForProfile( - MediaGalleriesPreferences* preferences, - const MediaFolderFinder::MediaFolderFinderResults& found_folders) { - // First, remove any existing scan results where no app has been granted - // permission - either it is gone, or is already in the new scan results. - // This burns some pref ids, but not at an appreciable rate. - MediaGalleryPrefIdSet to_remove; - const MediaGalleriesPrefInfoMap& known_galleries = - preferences->known_galleries(); - for (MediaGalleriesPrefInfoMap::const_iterator it = known_galleries.begin(); - it != known_galleries.end(); - ++it) { - if (it->second.type == MediaGalleryPrefInfo::kScanResult && - !preferences->NonAutoGalleryHasPermission(it->first)) { - to_remove.insert(it->first); - } - } - for (MediaGalleryPrefIdSet::const_iterator it = to_remove.begin(); - it != to_remove.end(); - ++it) { - preferences->EraseGalleryById(*it); - } - - MediaFolderFinder::MediaFolderFinderResults child_folders; - MediaFolderFinder::MediaFolderFinderResults - unique_found_folders(found_folders); - PartitionChildScanResults(preferences, &unique_found_folders, &child_folders); - - // Updating prefs while iterating them will invalidate the pointer, so - // calculate the changes first and then apply them. - std::map<MediaGalleryPrefId, MediaGalleryScanResult> to_update; - for (MediaGalleriesPrefInfoMap::const_iterator it = known_galleries.begin(); - it != known_galleries.end(); - ++it) { - const MediaGalleryPrefInfo& gallery = it->second; - if (!gallery.IsBlackListedType()) { - MediaGalleryScanResult file_counts = - SumFilesUnderPath(gallery.AbsolutePath(), child_folders); - if (gallery.audio_count != file_counts.audio_count || - gallery.image_count != file_counts.image_count || - gallery.video_count != file_counts.video_count) { - to_update[it->first] = file_counts; - } - } - } - - for (std::map<MediaGalleryPrefId, - MediaGalleryScanResult>::const_iterator it = to_update.begin(); - it != to_update.end(); - ++it) { - const MediaGalleryPrefInfo& gallery = - preferences->known_galleries().find(it->first)->second; - preferences->AddGallery(gallery.device_id, gallery.path, gallery.type, - gallery.volume_label, gallery.vendor_name, - gallery.model_name, gallery.total_size_in_bytes, - gallery.last_attach_time, - it->second.audio_count, - it->second.image_count, - it->second.video_count); - } - - // Add new scan results. - for (MediaFolderFinder::MediaFolderFinderResults::const_iterator it = - unique_found_folders.begin(); - it != unique_found_folders.end(); - ++it) { - MediaGalleryScanResult file_counts = - SumFilesUnderPath(it->first, child_folders); - // The top level scan result is not in |child_folders|. Add it in as well. - file_counts.audio_count += it->second.audio_count; - file_counts.image_count += it->second.image_count; - file_counts.video_count += it->second.video_count; - - MediaGalleryPrefInfo gallery; - bool existing = preferences->LookUpGalleryByPath(it->first, &gallery); - DCHECK(!existing); - preferences->AddGallery(gallery.device_id, gallery.path, - MediaGalleryPrefInfo::kScanResult, - gallery.volume_label, gallery.vendor_name, - gallery.model_name, gallery.total_size_in_bytes, - gallery.last_attach_time, file_counts.audio_count, - file_counts.image_count, file_counts.video_count); - } - UMA_HISTOGRAM_COUNTS_10000("MediaGalleries.ScanGalleriesPopulated", - unique_found_folders.size() + to_update.size()); -} - -int CountScanResultsForExtension(MediaGalleriesPreferences* preferences, - const extensions::Extension* extension, - MediaGalleryScanResult* file_counts) { - int gallery_count = 0; - - MediaGalleryPrefIdSet permitted_galleries = - preferences->GalleriesForExtension(*extension); - const MediaGalleriesPrefInfoMap& known_galleries = - preferences->known_galleries(); - for (MediaGalleriesPrefInfoMap::const_iterator it = known_galleries.begin(); - it != known_galleries.end(); - ++it) { - if (it->second.type == MediaGalleryPrefInfo::kScanResult && - !ContainsKey(permitted_galleries, it->first)) { - gallery_count++; - file_counts->audio_count += it->second.audio_count; - file_counts->image_count += it->second.image_count; - file_counts->video_count += it->second.video_count; - } - } - return gallery_count; -} - -int CountDirectoryEntries(const base::FilePath& path) { - base::FileEnumerator dir_counter( - path, false /*recursive*/, base::FileEnumerator::DIRECTORIES); - int count = 0; - base::FileEnumerator::FileInfo info; - for (base::FilePath name = dir_counter.Next(); !name.empty(); - name = dir_counter.Next()) { - if (!base::IsLink(name)) - ++count; - } - return count; -} - -struct ContainerCount { - int seen_count, entries_count; - bool is_qualified; - - ContainerCount() : seen_count(0), entries_count(-1), is_qualified(false) {} -}; - -typedef std::map<base::FilePath, ContainerCount> ContainerCandidates; - -} // namespace - -MediaScanManager::MediaScanManager() - : scoped_extension_registry_observer_(this), - weak_factory_(this) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); -} - -MediaScanManager::~MediaScanManager() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); -} - -void MediaScanManager::AddObserver(Profile* profile, - MediaScanManagerObserver* observer) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(!ContainsKey(observers_, profile)); - observers_[profile].observer = observer; -} - -void MediaScanManager::RemoveObserver(Profile* profile) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - bool scan_in_progress = ScanInProgress(); - observers_.erase(profile); - DCHECK_EQ(scan_in_progress, ScanInProgress()); -} - -void MediaScanManager::CancelScansForProfile(Profile* profile) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - observers_[profile].scanning_extensions.clear(); - - if (!ScanInProgress()) - folder_finder_.reset(); -} - -void MediaScanManager::StartScan(Profile* profile, - const extensions::Extension* extension, - bool user_gesture) { - DCHECK(extension); - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - ScanObserverMap::iterator scans_for_profile = observers_.find(profile); - // We expect that an MediaScanManagerObserver has already been registered. - DCHECK(scans_for_profile != observers_.end()); - bool scan_in_progress = ScanInProgress(); - // Ignore requests for extensions that are already scanning. - ScanningExtensionIdSet* scanning_extensions; - scanning_extensions = &scans_for_profile->second.scanning_extensions; - if (scan_in_progress && ContainsKey(*scanning_extensions, extension->id())) - return; - - // Provide cached result if there is not already a scan in progress, - // there is no user gesture, and the previous results are unexpired. - MediaGalleriesPreferences* preferences = - MediaGalleriesPreferencesFactory::GetForProfile(profile); - base::TimeDelta time_since_last_scan = - base::Time::Now() - preferences->GetLastScanCompletionTime(); - if (!scan_in_progress && !user_gesture && time_since_last_scan < - base::TimeDelta::FromHours(kScanResultsExpiryTimeInHours)) { - MediaGalleryScanResult file_counts; - int gallery_count = - CountScanResultsForExtension(preferences, extension, &file_counts); - scans_for_profile->second.observer->OnScanStarted(extension->id()); - scans_for_profile->second.observer->OnScanFinished(extension->id(), - gallery_count, - file_counts); - return; - } - - // On first scan for the |profile|, register to listen for extension unload. - if (scanning_extensions->empty()) - scoped_extension_registry_observer_.Add(ExtensionRegistry::Get(profile)); - - scanning_extensions->insert(extension->id()); - scans_for_profile->second.observer->OnScanStarted(extension->id()); - - if (folder_finder_) - return; - - MediaFolderFinder::MediaFolderFinderResultsCallback callback = - base::Bind(&MediaScanManager::OnScanCompleted, - weak_factory_.GetWeakPtr()); - if (testing_folder_finder_factory_.is_null()) { - folder_finder_.reset(new MediaFolderFinder(callback)); - } else { - folder_finder_.reset(testing_folder_finder_factory_.Run(callback)); - } - scan_start_time_ = base::Time::Now(); - folder_finder_->StartScan(); -} - -void MediaScanManager::CancelScan(Profile* profile, - const extensions::Extension* extension) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - // Erases the logical scan if found, early exit otherwise. - ScanObserverMap::iterator scans_for_profile = observers_.find(profile); - if (scans_for_profile == observers_.end() || - !scans_for_profile->second.scanning_extensions.erase(extension->id())) { - return; - } - - scans_for_profile->second.observer->OnScanCancelled(extension->id()); - - // No more scanning extensions for |profile|, so stop listening for unloads. - if (scans_for_profile->second.scanning_extensions.empty()) - scoped_extension_registry_observer_.Remove(ExtensionRegistry::Get(profile)); - - if (!ScanInProgress()) { - folder_finder_.reset(); - DCHECK(!scan_start_time_.is_null()); - UMA_HISTOGRAM_LONG_TIMES("MediaGalleries.ScanCancelTime", - base::Time::Now() - scan_start_time_); - scan_start_time_ = base::Time(); - } -} - -void MediaScanManager::SetMediaFolderFinderFactory( - const MediaFolderFinderFactory& factory) { - testing_folder_finder_factory_ = factory; -} - -// A single directory may contain many folders with media in them, without -// containing any media itself. In fact, the primary purpose of that directory -// may be to contain media directories. This function tries to find those -// container directories. -MediaFolderFinder::MediaFolderFinderResults -MediaScanManager::FindContainerScanResults( - const MediaFolderFinder::MediaFolderFinderResults& found_folders, - const std::vector<base::FilePath>& sensitive_locations) { - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); - std::vector<base::FilePath> abs_sensitive_locations; - for (size_t i = 0; i < sensitive_locations.size(); ++i) { - base::FilePath path = base::MakeAbsoluteFilePath(sensitive_locations[i]); - if (!path.empty()) - abs_sensitive_locations.push_back(path); - } - // Recursively find parent directories with majority of media directories, - // or container directories. - // |candidates| keeps track of directories which might have enough - // such directories to have us return them. - typedef std::map<base::FilePath, ContainerCount> ContainerCandidates; - ContainerCandidates candidates; - for (MediaFolderFinder::MediaFolderFinderResults::const_iterator it = - found_folders.begin(); - it != found_folders.end(); - ++it) { - base::FilePath child_directory = it->first; - base::FilePath parent_directory = child_directory.DirName(); - - // Parent of root is root. - while (!parent_directory.empty() && child_directory != parent_directory) { - // Skip sensitive folders and their ancestors. - base::FilePath abs_parent_directory = - base::MakeAbsoluteFilePath(parent_directory); - if (abs_parent_directory.empty()) - break; - bool is_sensitive = false; - for (size_t i = 0; i < abs_sensitive_locations.size(); ++i) { - if (abs_parent_directory == abs_sensitive_locations[i] || - abs_parent_directory.IsParent(abs_sensitive_locations[i])) { - is_sensitive = true; - break; - } - } - if (is_sensitive) - break; - - // Don't bother with ones we already have. - if (found_folders.find(parent_directory) != found_folders.end()) - continue; - - ContainerCandidates::iterator parent_it = - candidates.find(parent_directory); - if (parent_it == candidates.end()) { - ContainerCount count; - count.seen_count = 1; - count.entries_count = CountDirectoryEntries(parent_directory); - parent_it = - candidates.insert(std::make_pair(parent_directory, count)).first; - } else { - ++candidates[parent_directory].seen_count; - } - // If previously sufficient, or not sufficient, bail. - if (parent_it->second.is_qualified || - parent_it->second.seen_count * 100 / parent_it->second.entries_count < - kContainerDirectoryMinimumPercent) { - break; - } - // Otherwise, mark qualified and check parent. - parent_it->second.is_qualified = true; - child_directory = parent_directory; - parent_directory = child_directory.DirName(); - } - } - MediaFolderFinder::MediaFolderFinderResults result; - // Copy and return worthy results. - for (ContainerCandidates::const_iterator it = candidates.begin(); - it != candidates.end(); - ++it) { - if (it->second.is_qualified && it->second.seen_count >= 2) - result[it->first] = MediaGalleryScanResult(); - } - return result; -} - -MediaScanManager::ScanObservers::ScanObservers() : observer(NULL) {} -MediaScanManager::ScanObservers::ScanObservers(const ScanObservers& other) = - default; -MediaScanManager::ScanObservers::~ScanObservers() {} - -void MediaScanManager::OnExtensionUnloaded( - content::BrowserContext* browser_context, - const extensions::Extension* extension, - extensions::UnloadedExtensionInfo::Reason reason) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - CancelScan(Profile::FromBrowserContext(browser_context), extension); -} - -bool MediaScanManager::ScanInProgress() const { - for (ScanObserverMap::const_iterator it = observers_.begin(); - it != observers_.end(); - ++it) { - if (!it->second.scanning_extensions.empty()) - return true; - } - return false; -} - -void MediaScanManager::OnScanCompleted( - bool success, - const MediaFolderFinder::MediaFolderFinderResults& found_folders) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (!folder_finder_ || !success) { - folder_finder_.reset(); - return; - } - - UMA_HISTOGRAM_COUNTS_10000("MediaGalleries.ScanDirectoriesFound", - found_folders.size()); - DCHECK(!scan_start_time_.is_null()); - UMA_HISTOGRAM_LONG_TIMES("MediaGalleries.ScanFinishedTime", - base::Time::Now() - scan_start_time_); - scan_start_time_ = base::Time(); - - content::BrowserThread::PostTaskAndReplyWithResult( - content::BrowserThread::FILE, FROM_HERE, - base::Bind(FindContainerScanResults, - found_folders, - folder_finder_->graylisted_folders()), - base::Bind(&MediaScanManager::OnFoundContainerDirectories, - weak_factory_.GetWeakPtr(), - found_folders)); -} - -void MediaScanManager::OnFoundContainerDirectories( - const MediaFolderFinder::MediaFolderFinderResults& found_folders, - const MediaFolderFinder::MediaFolderFinderResults& container_folders) { - MediaFolderFinder::MediaFolderFinderResults folders; - folders.insert(found_folders.begin(), found_folders.end()); - folders.insert(container_folders.begin(), container_folders.end()); - - for (ScanObserverMap::iterator scans_for_profile = observers_.begin(); - scans_for_profile != observers_.end(); - ++scans_for_profile) { - if (scans_for_profile->second.scanning_extensions.empty()) - continue; - Profile* profile = scans_for_profile->first; - MediaGalleriesPreferences* preferences = - MediaGalleriesPreferencesFactory::GetForProfile(profile); - ExtensionService* extension_service = - extensions::ExtensionSystem::Get(profile)->extension_service(); - if (!extension_service) - continue; - - AddScanResultsForProfile(preferences, folders); - - ScanningExtensionIdSet* scanning_extensions = - &scans_for_profile->second.scanning_extensions; - for (ScanningExtensionIdSet::const_iterator extension_id_it = - scanning_extensions->begin(); - extension_id_it != scanning_extensions->end(); - ++extension_id_it) { - const extensions::Extension* extension = - extension_service->GetExtensionById(*extension_id_it, false); - if (extension) { - MediaGalleryScanResult file_counts; - int gallery_count = CountScanResultsForExtension(preferences, extension, - &file_counts); - scans_for_profile->second.observer->OnScanFinished(*extension_id_it, - gallery_count, - file_counts); - } - } - scanning_extensions->clear(); - preferences->SetLastScanCompletionTime(base::Time::Now()); - } - scoped_extension_registry_observer_.RemoveAll(); - folder_finder_.reset(); -} diff --git a/chrome/browser/media_galleries/media_scan_manager.h b/chrome/browser/media_galleries/media_scan_manager.h deleted file mode 100644 index da0216a..0000000 --- a/chrome/browser/media_galleries/media_scan_manager.h +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_SCAN_MANAGER_H_ -#define CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_SCAN_MANAGER_H_ - -#include <map> -#include <set> -#include <string> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/scoped_observer.h" -#include "base/time/time.h" -#include "chrome/browser/media_galleries/media_folder_finder.h" -#include "chrome/browser/media_galleries/media_scan_types.h" -#include "extensions/browser/extension_registry_observer.h" - -class MediaScanManagerObserver; -class Profile; - -namespace extensions { -class Extension; -class ExtensionRegistry; -} - -// The MediaScanManager is owned by MediaFileSystemRegistry, which is global. -// This class manages multiple 'virtual' media scans, up to one per extension -// per profile, and also manages the one physical scan backing them. -// This class lives and is called on the UI thread. -class MediaScanManager : public extensions::ExtensionRegistryObserver { - public: - MediaScanManager(); - ~MediaScanManager() override; - - // There can only be ever one observer registered per profile. Does not take - // ownership of |observer|. An observer must be registered before scanning. - void AddObserver(Profile* profile, MediaScanManagerObserver* observer); - void RemoveObserver(Profile* profile); - - // Must be called when |profile| is shut down. - void CancelScansForProfile(Profile* profile); - - // The results of the scan are reported to the registered - // MediaScanManagerObserver via OnScanFinished. There must be an observer - // registered for |profile| before the scan starts. - void StartScan(Profile* profile, const extensions::Extension* extension, - bool user_gesture); - void CancelScan(Profile* profile, const extensions::Extension* extension); - - protected: - friend class MediaGalleriesPlatformAppBrowserTest; - friend class MediaScanManagerTest; - - typedef base::Callback<MediaFolderFinder*( - const MediaFolderFinder::MediaFolderFinderResultsCallback&)> - MediaFolderFinderFactory; - - void SetMediaFolderFinderFactory(const MediaFolderFinderFactory& factory); - - // Here so that friend MediaScanManagerTest can access it. - static MediaFolderFinder::MediaFolderFinderResults FindContainerScanResults( - const MediaFolderFinder::MediaFolderFinderResults& found_folders, - const std::vector<base::FilePath>& sensitive_locations); - - private: - struct ScanObservers { - ScanObservers(); - ScanObservers(const ScanObservers& other); - ~ScanObservers(); - MediaScanManagerObserver* observer; - std::set<std::string /*extension id*/> scanning_extensions; - }; - typedef std::map<Profile*, ScanObservers> ScanObserverMap; - - // extensions::ExtensionRegistryObserver implementation. - void OnExtensionUnloaded( - content::BrowserContext* browser_context, - const extensions::Extension* extension, - extensions::UnloadedExtensionInfo::Reason reason) override; - - bool ScanInProgress() const; - - void OnScanCompleted( - bool success, - const MediaFolderFinder::MediaFolderFinderResults& found_folders); - - void OnFoundContainerDirectories( - const MediaFolderFinder::MediaFolderFinderResults& found_folders, - const MediaFolderFinder::MediaFolderFinderResults& container_folders); - - scoped_ptr<MediaFolderFinder> folder_finder_; - - base::Time scan_start_time_; - - // If not NULL, used to create |folder_finder_|. Used for testing. - MediaFolderFinderFactory testing_folder_finder_factory_; - - // Set of extensions (on all profiles) that have an in-progress scan. - ScanObserverMap observers_; - - ScopedObserver<extensions::ExtensionRegistry, - extensions::ExtensionRegistryObserver> - scoped_extension_registry_observer_; - - base::WeakPtrFactory<MediaScanManager> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(MediaScanManager); -}; - -#endif // CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_SCAN_MANAGER_H_ diff --git a/chrome/browser/media_galleries/media_scan_manager_observer.h b/chrome/browser/media_galleries/media_scan_manager_observer.h deleted file mode 100644 index e20cf16..0000000 --- a/chrome/browser/media_galleries/media_scan_manager_observer.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_SCAN_MANAGER_OBSERVER_H_ -#define CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_SCAN_MANAGER_OBSERVER_H_ - -#include <string> - -#include "chrome/browser/media_galleries/media_scan_types.h" - -class MediaScanManagerObserver { - public: - virtual void OnScanStarted(const std::string& extension_id) {} - virtual void OnScanCancelled(const std::string& extension_id) {} - virtual void OnScanFinished( - const std::string& extension_id, - int gallery_count, - const MediaGalleryScanResult& file_counts) {} - virtual void OnScanError(const std::string& extension_id) {} -}; - -#endif // CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_SCAN_MANAGER_OBSERVER_H_ diff --git a/chrome/browser/media_galleries/media_scan_manager_unittest.cc b/chrome/browser/media_galleries/media_scan_manager_unittest.cc deleted file mode 100644 index 1a6adc2..0000000 --- a/chrome/browser/media_galleries/media_scan_manager_unittest.cc +++ /dev/null @@ -1,735 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stddef.h> - -#include "base/base_paths.h" -#include "base/bind.h" -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "base/run_loop.h" -#include "base/test/scoped_path_override.h" -#include "build/build_config.h" -#include "chrome/browser/extensions/test_extension_system.h" -#include "chrome/browser/media_galleries/media_folder_finder.h" -#include "chrome/browser/media_galleries/media_galleries_preferences.h" -#include "chrome/browser/media_galleries/media_galleries_preferences_factory.h" -#include "chrome/browser/media_galleries/media_galleries_test_util.h" -#include "chrome/browser/media_galleries/media_scan_manager.h" -#include "chrome/browser/media_galleries/media_scan_manager_observer.h" -#include "chrome/test/base/testing_profile.h" -#include "components/storage_monitor/test_storage_monitor.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "extensions/browser/extension_system.h" -#include "extensions/common/extension.h" -#include "extensions/common/permissions/media_galleries_permission.h" -#include "testing/gtest/include/gtest/gtest.h" - -#if defined(OS_CHROMEOS) -#include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h" -#include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chrome/browser/chromeos/settings/device_settings_service.h" -#endif - -namespace { - -class MockMediaFolderFinder : MediaFolderFinder { - public: - typedef base::Callback<void(MediaFolderFinderResultsCallback)> - FindFoldersStartedCallback; - - static MediaFolderFinder* CreateMockMediaFolderFinder( - const FindFoldersStartedCallback& started_callback, - const base::Closure destruction_callback, - const MediaFolderFinderResultsCallback& callback) { - return new MockMediaFolderFinder(started_callback, destruction_callback, - callback); - } - - MockMediaFolderFinder( - const FindFoldersStartedCallback& started_callback, - const base::Closure destruction_callback, - const MediaFolderFinderResultsCallback& callback) - : MediaFolderFinder(callback), - started_callback_(started_callback), - destruction_callback_(destruction_callback), - callback_(callback) { - } - ~MockMediaFolderFinder() override { destruction_callback_.Run(); } - - void StartScan() override { started_callback_.Run(callback_); } - - private: - FindFoldersStartedCallback started_callback_; - base::Closure destruction_callback_; - MediaFolderFinderResultsCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(MockMediaFolderFinder); -}; - -} // namespace - -class TestMediaScanManager : public MediaScanManager { - public: - typedef base::Callback<MediaFolderFinder*( - const MediaFolderFinder::MediaFolderFinderResultsCallback&)> - MediaFolderFinderFactory; - - explicit TestMediaScanManager(const MediaFolderFinderFactory& factory) { - SetMediaFolderFinderFactory(factory); - } - ~TestMediaScanManager() override {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestMediaScanManager); -}; - -class MediaScanManagerTest : public MediaScanManagerObserver, - public testing::Test { - public: - MediaScanManagerTest() - : find_folders_start_count_(0), - find_folders_destroy_count_(0), - find_folders_success_(false), - expected_gallery_count_(0), - profile_(new TestingProfile()) {} - - ~MediaScanManagerTest() override { - EXPECT_EQ(find_folders_start_count_, find_folders_destroy_count_); - } - - void SetUp() override { - ASSERT_TRUE(storage_monitor::TestStorageMonitor::CreateAndInstall()); - - extensions::TestExtensionSystem* extension_system( - static_cast<extensions::TestExtensionSystem*>( - extensions::ExtensionSystem::Get(profile_.get()))); - extension_system->CreateExtensionService( - base::CommandLine::ForCurrentProcess(), base::FilePath(), false); - - gallery_prefs_ = - MediaGalleriesPreferencesFactory::GetForProfile(profile_.get()); - base::RunLoop loop; - gallery_prefs_->EnsureInitialized(loop.QuitClosure()); - loop.Run(); - - std::vector<std::string> read_permissions; - read_permissions.push_back( - extensions::MediaGalleriesPermission::kReadPermission); - extension_ = AddMediaGalleriesApp("read", read_permissions, profile_.get()); - - ASSERT_TRUE(test_results_dir_.CreateUniqueTempDir()); - - MockMediaFolderFinder::FindFoldersStartedCallback started_callback = - base::Bind(&MediaScanManagerTest::OnFindFoldersStarted, - base::Unretained(this)); - base::Closure destruction_callback = - base::Bind(&MediaScanManagerTest::OnFindFoldersDestroyed, - base::Unretained(this)); - TestMediaScanManager::MediaFolderFinderFactory factory = - base::Bind(&MockMediaFolderFinder::CreateMockMediaFolderFinder, - started_callback, destruction_callback); - media_scan_manager_.reset(new TestMediaScanManager(factory)); - media_scan_manager_->AddObserver(profile_.get(), this); - } - - void TearDown() override { - media_scan_manager_->RemoveObserver(profile_.get()); - media_scan_manager_.reset(); - storage_monitor::TestStorageMonitor::Destroy(); - } - - // Create a test folder in the test specific scoped temp dir and return the - // final path in |full_path|. - void MakeTestFolder(const std::string& root_relative_path, - base::FilePath* full_path) { - ASSERT_TRUE(test_results_dir_.IsValid()); - *full_path = - test_results_dir_.path().AppendASCII(root_relative_path); - ASSERT_TRUE(base::CreateDirectory(*full_path)); - } - - // Create the specified path, and add it to preferences as a gallery. - MediaGalleryPrefId AddGallery(const std::string& rel_path, - MediaGalleryPrefInfo::Type type, - int audio_count, - int image_count, - int video_count) { - base::FilePath full_path; - MakeTestFolder(rel_path, &full_path); - MediaGalleryPrefInfo gallery_info; - gallery_prefs_->LookUpGalleryByPath(full_path, &gallery_info); - return gallery_prefs_->AddGallery(gallery_info.device_id, - gallery_info.path, - type, - gallery_info.volume_label, - gallery_info.vendor_name, - gallery_info.model_name, - gallery_info.total_size_in_bytes, - gallery_info.last_attach_time, - audio_count, image_count, video_count); - } - - void SetFindFoldersResults( - bool success, - const MediaFolderFinder::MediaFolderFinderResults& results) { - find_folders_success_ = success; - find_folders_results_ = results; - } - - void SetExpectedScanResults(int gallery_count, - const MediaGalleryScanResult& file_counts) { - expected_gallery_count_ = gallery_count; - expected_file_counts_ = file_counts; - } - - void StartScan() { - media_scan_manager_->StartScan( - profile_.get(), extension_.get(), true /* user_gesture */); - } - - MediaGalleriesPreferences* gallery_prefs() { - return gallery_prefs_; - } - - const MediaGalleriesPrefInfoMap& known_galleries() const { - return gallery_prefs_->known_galleries(); - } - - size_t gallery_count() const { - return known_galleries().size(); - } - - extensions::Extension* extension() { - return extension_.get(); - } - - int FindFoldersStartCount() { - return find_folders_start_count_; - } - - int FindFolderDestroyCount() { - return find_folders_destroy_count_; - } - - void CheckFileCounts(MediaGalleryPrefId pref_id, int audio_count, - int image_count, int video_count) { - if (!ContainsKey(known_galleries(), pref_id)) { - EXPECT_TRUE(false); - return; - } - MediaGalleriesPrefInfoMap::const_iterator pref_info = - known_galleries().find(pref_id); - EXPECT_EQ(audio_count, pref_info->second.audio_count); - EXPECT_EQ(image_count, pref_info->second.image_count); - EXPECT_EQ(video_count, pref_info->second.video_count); - } - - // MediaScanManagerObserver implementation. - void OnScanFinished(const std::string& extension_id, - int gallery_count, - const MediaGalleryScanResult& file_counts) override { - EXPECT_EQ(extension_->id(), extension_id); - EXPECT_EQ(expected_gallery_count_, gallery_count); - EXPECT_EQ(expected_file_counts_.audio_count, file_counts.audio_count); - EXPECT_EQ(expected_file_counts_.image_count, file_counts.image_count); - EXPECT_EQ(expected_file_counts_.video_count, file_counts.video_count); - } - - protected: - // So derived tests can access ...::FindContainerScanResults(). - MediaFolderFinder::MediaFolderFinderResults FindContainerScanResults( - const MediaFolderFinder::MediaFolderFinderResults& found_folders, - const std::vector<base::FilePath>& sensitive_locations) { - return MediaScanManager::FindContainerScanResults(found_folders, - sensitive_locations); - } - - private: - void OnFindFoldersStarted( - MediaFolderFinder::MediaFolderFinderResultsCallback callback) { - find_folders_start_count_++; - callback.Run(find_folders_success_, find_folders_results_); - } - - void OnFindFoldersDestroyed() { - find_folders_destroy_count_++; - } - - scoped_ptr<TestMediaScanManager> media_scan_manager_; - - int find_folders_start_count_; - int find_folders_destroy_count_; - bool find_folders_success_; - MediaFolderFinder::MediaFolderFinderResults find_folders_results_; - - int expected_gallery_count_; - MediaGalleryScanResult expected_file_counts_; - - base::ScopedTempDir test_results_dir_; - - // Needed for extension service & friends to work. - content::TestBrowserThreadBundle thread_bundle_; - - scoped_refptr<extensions::Extension> extension_; - - EnsureMediaDirectoriesExists mock_gallery_locations_; - -#if defined(OS_CHROMEOS) - chromeos::ScopedTestDeviceSettingsService test_device_settings_service_; - chromeos::ScopedTestCrosSettings test_cros_settings_; - chromeos::ScopedTestUserManager test_user_manager_; -#endif - - storage_monitor::TestStorageMonitor monitor_; - scoped_ptr<TestingProfile> profile_; - MediaGalleriesPreferences* gallery_prefs_; - - DISALLOW_COPY_AND_ASSIGN(MediaScanManagerTest); -}; - -TEST_F(MediaScanManagerTest, SingleResult) { - size_t galleries_before = gallery_count(); - MediaGalleryScanResult file_counts; - file_counts.audio_count = 1; - file_counts.image_count = 2; - file_counts.video_count = 3; - base::FilePath path; - MakeTestFolder("found_media_folder", &path); - - MediaFolderFinder::MediaFolderFinderResults found_folders; - found_folders[path] = file_counts; - SetFindFoldersResults(true, found_folders); - - SetExpectedScanResults(1 /*gallery_count*/, file_counts); - StartScan(); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, FindFolderDestroyCount()); - EXPECT_EQ(galleries_before + 1, gallery_count()); -} - -// Generally test that it includes directories with sufficient density -// and excludes others. -// -// A/ - NOT included -// A/B/ - NOT included -// A/B/C/files -// A/D/ - NOT included -// A/D/E/files -// A/D/F/files -// A/D/G/files -// A/D/H/ -// A/H/ - included in results -// A/H/I/files -// A/H/J/files -TEST_F(MediaScanManagerTest, MergeRedundant) { - base::FilePath path; - MediaFolderFinder::MediaFolderFinderResults found_folders; - std::vector<base::FilePath> sensitive_locations; - std::vector<base::FilePath> expected_folders; - MediaGalleryScanResult file_counts; - file_counts.audio_count = 1; - file_counts.image_count = 2; - file_counts.video_count = 3; - MakeTestFolder("A", &path); - MakeTestFolder("A/B", &path); - MakeTestFolder("A/B/C", &path); - found_folders[path] = file_counts; - // Not dense enough. - MakeTestFolder("A/D", &path); - MakeTestFolder("A/D/E", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/D/F", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/D/G", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/D/H", &path); - // Dense enough to be reported. - MakeTestFolder("A/H", &path); - expected_folders.push_back(path); - MakeTestFolder("A/H/I", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/H/J", &path); - found_folders[path] = file_counts; - MediaFolderFinder::MediaFolderFinderResults results = - FindContainerScanResults(found_folders, sensitive_locations); - EXPECT_EQ(expected_folders.size(), results.size()); - for (std::vector<base::FilePath>::const_iterator it = - expected_folders.begin(); - it != expected_folders.end(); - ++it) { - EXPECT_TRUE(results.find(*it) != results.end()); - } -} - -// Make sure intermediates are not included. -// -// A/ - included in results -// A/B1/ - NOT included -// A/B1/B2/files -// A/C1/ - NOT included -// A/C1/C2/files -TEST_F(MediaScanManagerTest, MergeRedundantNoIntermediates) { - base::FilePath path; - MediaFolderFinder::MediaFolderFinderResults found_folders; - std::vector<base::FilePath> sensitive_locations; - std::vector<base::FilePath> expected_folders; - MediaGalleryScanResult file_counts; - file_counts.audio_count = 1; - file_counts.image_count = 2; - file_counts.video_count = 3; - MakeTestFolder("A", &path); - expected_folders.push_back(path); - MakeTestFolder("A/B1", &path); - MakeTestFolder("A/B1/B2", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/C1", &path); - MakeTestFolder("A/C1/C2", &path); - found_folders[path] = file_counts; - // Make "home dir" not dense enough. - MakeTestFolder("D", &path); - MediaFolderFinder::MediaFolderFinderResults results = - FindContainerScanResults(found_folders, sensitive_locations); - EXPECT_EQ(expected_folders.size(), results.size()); - for (std::vector<base::FilePath>::const_iterator it = - expected_folders.begin(); - it != expected_folders.end(); - ++it) { - EXPECT_TRUE(results.find(*it) != results.end()); - } -} - -// Make sure "A/" only gets a count of 1, from "A/D/", -// not 2 from "A/D/H/" and "A/D/I/". -// -// A/ - NOT included -// A/D/ - included in results -// A/D/E/files -// A/D/F/files -// A/D/G/files -// A/D/H/files -// A/D/I/ - NOT included -// A/D/I/J/files -TEST_F(MediaScanManagerTest, MergeRedundantVerifyNoOvercount) { - base::FilePath path; - MediaFolderFinder::MediaFolderFinderResults found_folders; - std::vector<base::FilePath> sensitive_locations; - std::vector<base::FilePath> expected_folders; - MediaGalleryScanResult file_counts; - file_counts.audio_count = 1; - file_counts.image_count = 2; - file_counts.video_count = 3; - MakeTestFolder("A", &path); - MakeTestFolder("A/D", &path); - expected_folders.push_back(path); - MakeTestFolder("A/D/E", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/D/F", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/D/G", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/D/H", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/D/I", &path); - MakeTestFolder("A/D/I/J", &path); - found_folders[path] = file_counts; - MediaFolderFinder::MediaFolderFinderResults results = - FindContainerScanResults(found_folders, sensitive_locations); - EXPECT_EQ(expected_folders.size(), results.size()); - for (std::vector<base::FilePath>::const_iterator it = - expected_folders.begin(); - it != expected_folders.end(); - ++it) { - EXPECT_TRUE(results.find(*it) != results.end()); - } -} - -// Make sure that sensistive directories are pruned. -// -// A/ - NOT included -// A/B/ - sensitive -// A/C/ - included in results -// A/C/G/files -// A/C/H/files -// A/D/ - included in results -// A/D/I/files -// A/D/J/files -// A/E/ - included in results -// A/E/K/files -// A/E/L/files -// A/F/ - included in results -// A/F/M/files -// A/F/N/files -TEST_F(MediaScanManagerTest, MergeRedundantWithSensitive) { - base::FilePath path; - MediaFolderFinder::MediaFolderFinderResults found_folders; - std::vector<base::FilePath> sensitive_locations; - std::vector<base::FilePath> expected_folders; - MediaGalleryScanResult file_counts; - file_counts.audio_count = 1; - file_counts.image_count = 2; - file_counts.video_count = 3; - MakeTestFolder("A", &path); - MakeTestFolder("A/B", &path); - sensitive_locations.push_back(path); - MakeTestFolder("A/C", &path); - expected_folders.push_back(path); - MakeTestFolder("A/C/G", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/C/H", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/D", &path); - expected_folders.push_back(path); - MakeTestFolder("A/D/I", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/D/J", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/E", &path); - expected_folders.push_back(path); - MakeTestFolder("A/E/K", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/E/L", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/F", &path); - expected_folders.push_back(path); - MakeTestFolder("A/F/M", &path); - found_folders[path] = file_counts; - MakeTestFolder("A/F/N", &path); - found_folders[path] = file_counts; - MediaFolderFinder::MediaFolderFinderResults results = - FindContainerScanResults(found_folders, sensitive_locations); - EXPECT_EQ(expected_folders.size(), results.size()); - for (std::vector<base::FilePath>::const_iterator it = - expected_folders.begin(); - it != expected_folders.end(); - ++it) { - EXPECT_TRUE(results.find(*it) != results.end()); - } -} - -TEST_F(MediaScanManagerTest, Containers) { - MediaGalleryScanResult file_counts; - file_counts.audio_count = 1; - base::FilePath path; - std::set<base::FilePath> expected_galleries; - std::set<base::FilePath> bad_galleries; - MediaFolderFinder::MediaFolderFinderResults found_folders; - size_t galleries_before = gallery_count(); - - // Should manifest as a gallery in result1. - MakeTestFolder("dir1/result1", &path); - expected_galleries.insert(path); - found_folders[path] = file_counts; - - // Should manifest as a gallery in dir2. - MakeTestFolder("dir2/result2", &path); - bad_galleries.insert(path); - found_folders[path] = file_counts; - MakeTestFolder("dir2/result3", &path); - bad_galleries.insert(path); - found_folders[path] = file_counts; - expected_galleries.insert(path.DirName()); - - // Should manifest as a two galleries: result4 and result5. - MakeTestFolder("dir3/other", &path); - bad_galleries.insert(path); - MakeTestFolder("dir3/result4", &path); - expected_galleries.insert(path); - found_folders[path] = file_counts; - MakeTestFolder("dir3/result5", &path); - expected_galleries.insert(path); - found_folders[path] = file_counts; - - // Should manifest as a gallery in dir4. - MakeTestFolder("dir4/other", &path); - bad_galleries.insert(path); - MakeTestFolder("dir4/result6", &path); - bad_galleries.insert(path); - found_folders[path] = file_counts; - MakeTestFolder("dir4/result7", &path); - bad_galleries.insert(path); - found_folders[path] = file_counts; - MakeTestFolder("dir4/result8", &path); - bad_galleries.insert(path); - found_folders[path] = file_counts; - MakeTestFolder("dir4/result9", &path); - bad_galleries.insert(path); - found_folders[path] = file_counts; - expected_galleries.insert(path.DirName()); - - SetFindFoldersResults(true, found_folders); - - file_counts.audio_count = 9; - SetExpectedScanResults(5 /*gallery_count*/, file_counts); - StartScan(); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, FindFolderDestroyCount()); - EXPECT_EQ(galleries_before + 5, gallery_count()); - - std::set<base::FilePath> found_galleries; - for (MediaGalleriesPrefInfoMap::const_iterator it = known_galleries().begin(); - it != known_galleries().end(); - ++it) { - found_galleries.insert(it->second.AbsolutePath()); - DCHECK(!ContainsKey(bad_galleries, it->second.AbsolutePath())); - } - for (std::set<base::FilePath>::const_iterator it = expected_galleries.begin(); - it != expected_galleries.end(); - ++it) { - DCHECK(ContainsKey(found_galleries, *it)); - } -} - -TEST_F(MediaScanManagerTest, UpdateExistingScanResults) { - size_t galleries_before = gallery_count(); - - MediaGalleryPrefId ungranted_scan = - AddGallery("uscan", MediaGalleryPrefInfo::kScanResult, 1, 0, 0); - MediaGalleryPrefId granted_scan = - AddGallery("gscan", MediaGalleryPrefInfo::kScanResult, 0, 2, 0); - gallery_prefs()->SetGalleryPermissionForExtension(*extension(), granted_scan, - true); - EXPECT_EQ(galleries_before + 2, gallery_count()); - - // Run once with no scan results. "uscan" should go away and "gscan" should - // have its scan counts updated. - MediaFolderFinder::MediaFolderFinderResults found_folders; - SetFindFoldersResults(true, found_folders); - - MediaGalleryScanResult file_counts; - SetExpectedScanResults(0 /*gallery_count*/, file_counts); - StartScan(); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, FindFolderDestroyCount()); - EXPECT_EQ(galleries_before + 1, gallery_count()); - CheckFileCounts(granted_scan, 0, 0, 0); - - MediaGalleryPrefId id = - AddGallery("uscan", MediaGalleryPrefInfo::kScanResult, 1, 1, 1); - EXPECT_NE(id, ungranted_scan); - ungranted_scan = id; - - // Add scan results near the existing scan results. - file_counts.audio_count = 0; - file_counts.image_count = 0; - file_counts.video_count = 7; - base::FilePath path; - MakeTestFolder("uscan", &path); - found_folders[path] = file_counts; - - file_counts.video_count = 11; - MakeTestFolder("gscan/dir1", &path); - found_folders[path] = file_counts; - - MakeTestFolder("junk", &path); - - SetFindFoldersResults(true, found_folders); - file_counts.video_count = 7; - SetExpectedScanResults(1 /*gallery_count*/, file_counts); - StartScan(); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(2, FindFolderDestroyCount()); - EXPECT_EQ(galleries_before + 2, gallery_count()); - CheckFileCounts(granted_scan, 0, 0, 11); - // The new scan result should be one more than it's previous id. - CheckFileCounts(ungranted_scan + 1, 0, 0, 7); -} - -TEST_F(MediaScanManagerTest, UpdateExistingCounts) { - size_t galleries_before = gallery_count(); - - MediaGalleryPrefId auto_id = - AddGallery("auto", MediaGalleryPrefInfo::kAutoDetected, 1, 0, 0); - MediaGalleryPrefId user_id = - AddGallery("user", MediaGalleryPrefInfo::kUserAdded, 0, 2, 0); - MediaGalleryPrefId scan_id = - AddGallery("scan", MediaGalleryPrefInfo::kScanResult, 0, 0, 3); - // Grant permission so this one isn't removed and readded. - gallery_prefs()->SetGalleryPermissionForExtension(*extension(), scan_id, - true); - CheckFileCounts(auto_id, 1, 0, 0); - CheckFileCounts(user_id, 0, 2, 0); - CheckFileCounts(scan_id, 0, 0, 3); - - MediaFolderFinder::MediaFolderFinderResults found_folders; - MediaGalleryScanResult file_counts; - file_counts.audio_count = 4; - base::FilePath path; - MakeTestFolder("auto/dir1", &path); - found_folders[path] = file_counts; - - file_counts.audio_count = 6; - MakeTestFolder("scan", &path); - found_folders[path] = file_counts; - - MakeTestFolder("junk", &path); - - file_counts.audio_count = 5; - MakeTestFolder("user/dir2", &path); - found_folders[path] = file_counts; - - SetFindFoldersResults(true, found_folders); - - file_counts.audio_count = 0; - SetExpectedScanResults(0 /*gallery_count*/, file_counts); - StartScan(); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, FindFolderDestroyCount()); - EXPECT_EQ(galleries_before + 3, gallery_count()); - CheckFileCounts(auto_id, 4, 0, 0); - CheckFileCounts(user_id, 5, 0, 0); - CheckFileCounts(scan_id, 6, 0, 0); - - EXPECT_EQ(1U, found_folders.erase(path)); - SetFindFoldersResults(true, found_folders); - SetExpectedScanResults(0 /*gallery_count*/, file_counts); - StartScan(); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(2, FindFolderDestroyCount()); - EXPECT_EQ(galleries_before + 3, gallery_count()); - CheckFileCounts(auto_id, 4, 0, 0); - CheckFileCounts(user_id, 0, 0, 0); - CheckFileCounts(scan_id, 6, 0, 0); -} - -TEST_F(MediaScanManagerTest, Graylist) { - size_t galleries_before = gallery_count(); - MediaGalleryScanResult file_counts; - file_counts.audio_count = 1; - file_counts.image_count = 2; - file_counts.video_count = 3; - base::FilePath path; - MakeTestFolder("found_media_folder", &path); - base::ScopedPathOverride scoped_fake_home_dir_override(base::DIR_HOME, path); - - const size_t kGalleriesAdded = 3; - MediaFolderFinder::MediaFolderFinderResults found_folders; - MakeTestFolder("found_media_folder/dir1", &path); - found_folders[path] = file_counts; - MakeTestFolder("found_media_folder/dir2", &path); - found_folders[path] = file_counts; - MakeTestFolder("found_media_folder/dir3", &path); - found_folders[path] = file_counts; - SetFindFoldersResults(true, found_folders); - - file_counts.audio_count *= kGalleriesAdded; - file_counts.image_count *= kGalleriesAdded; - file_counts.video_count *= kGalleriesAdded; - SetExpectedScanResults(kGalleriesAdded, file_counts); - StartScan(); - - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, FindFolderDestroyCount()); - EXPECT_EQ(galleries_before + kGalleriesAdded, gallery_count()); -} diff --git a/chrome/browser/media_galleries/media_scan_types.cc b/chrome/browser/media_galleries/media_scan_types.cc deleted file mode 100644 index 4b3eba4..0000000 --- a/chrome/browser/media_galleries/media_scan_types.cc +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/media_galleries/media_scan_types.h" - -MediaGalleryScanResult::MediaGalleryScanResult() - : audio_count(0), - image_count(0), - video_count(0) { -} - -bool IsEmptyScanResult(const MediaGalleryScanResult& scan_result) { - return (scan_result.audio_count == 0 && - scan_result.image_count == 0 && - scan_result.video_count == 0); -} diff --git a/chrome/browser/media_galleries/media_scan_types.h b/chrome/browser/media_galleries/media_scan_types.h deleted file mode 100644 index 091d794..0000000 --- a/chrome/browser/media_galleries/media_scan_types.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_SCAN_TYPES_H_ -#define CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_SCAN_TYPES_H_ - -struct MediaGalleryScanResult { - MediaGalleryScanResult(); - int audio_count; - int image_count; - int video_count; -}; - -enum MediaGalleryScanFileType { - MEDIA_GALLERY_SCAN_FILE_TYPE_UNKNOWN = 0, - MEDIA_GALLERY_SCAN_FILE_TYPE_AUDIO = 1 << 0, - MEDIA_GALLERY_SCAN_FILE_TYPE_IMAGE = 1 << 1, - MEDIA_GALLERY_SCAN_FILE_TYPE_VIDEO = 1 << 2, -}; - -bool IsEmptyScanResult(const MediaGalleryScanResult& scan_result); - -#endif // CHROME_BROWSER_MEDIA_GALLERIES_MEDIA_SCAN_TYPES_H_ diff --git a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h index 42252af..9b3553a 100644 --- a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h +++ b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h @@ -50,7 +50,6 @@ class MediaGalleriesDialogCocoa : public ConstrainedWindowMacDelegate, // MediaGalleryListEntryController implementation. void OnCheckboxToggled(MediaGalleryPrefId pref_id, bool checked) override; - void OnFolderViewerClicked(MediaGalleryPrefId prefId) override; ui::MenuModel* GetContextMenu(MediaGalleryPrefId pref_id) override; private: diff --git a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm index 5dd8949..01cf67c 100644 --- a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm +++ b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm @@ -187,8 +187,7 @@ CGFloat MediaGalleriesDialogCocoa::CreateCheckboxes( [[MediaGalleryListEntry alloc] initWithFrame:NSZeroRect controller:this - prefInfo:entry.pref_info - showFolderViewer:controller_->ShouldShowFolderViewer(entry)]); + prefInfo:entry.pref_info]); [checkbox_entry setState:entry.selected]; @@ -268,11 +267,6 @@ void MediaGalleriesDialogCocoa::OnCheckboxToggled(MediaGalleryPrefId pref_id, controller_->IsAcceptAllowed()]; } -void MediaGalleriesDialogCocoa::OnFolderViewerClicked( - MediaGalleryPrefId prefId) { - controller_->DidClickOpenFolderViewer(prefId); -} - ui::MenuModel* MediaGalleriesDialogCocoa::GetContextMenu( MediaGalleryPrefId pref_id) { return controller_->GetContextMenu(pref_id); diff --git a/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.h b/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.h index 24916c2..6ab7b77 100644 --- a/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.h +++ b/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.h @@ -29,15 +29,13 @@ class MediaGalleryListEntryController { MediaGalleryPrefId prefId_; base::scoped_nsobject<MediaGalleryButton> checkbox_; - base::scoped_nsobject<MediaGalleryButton> folderViewer_; base::scoped_nsobject<NSTextField> details_; } // Does size to fit if frameRect is empty. - (id)initWithFrame:(NSRect)frameRect controller:(MediaGalleryListEntryController*)controller_ - prefInfo:(const MediaGalleryPrefInfo&)prefInfo - showFolderViewer:(bool)showFolderViewer; + prefInfo:(const MediaGalleryPrefInfo&)prefInfo; - (void)setState:(bool)selected; diff --git a/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.mm b/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.mm index 925b24f..1e5661f 100644 --- a/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.mm +++ b/chrome/browser/ui/cocoa/extensions/media_gallery_list_entry_view.mm @@ -62,8 +62,7 @@ ui::MenuModel* MediaGalleryListEntryController::GetContextMenu( - (id)initWithFrame:(NSRect)frameRect controller:(MediaGalleryListEntryController*)controller - prefInfo:(const MediaGalleryPrefInfo&)prefInfo - showFolderViewer:(bool)showFolderViewer { + prefInfo:(const MediaGalleryPrefInfo&)prefInfo { if ((self = [super initWithFrame:frameRect])) { controller_ = controller; prefId_ = prefInfo.pref_id; @@ -87,24 +86,6 @@ ui::MenuModel* MediaGalleryListEntryController::GetContextMenu( [checkbox_ setToolTip:nsTooltip]; [self addSubview:checkbox_]; - // Folder viewer button. - if (showFolderViewer) { - folderViewer_.reset( - [[MediaGalleryButton alloc] initWithFrame:NSZeroRect - controller:self]); - [folderViewer_ setButtonType:NSMomentaryChangeButton]; - [folderViewer_ setTarget:self]; - [folderViewer_ setAction:@selector(onFolderViewerClicked:)]; - - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - [folderViewer_ setImage:rb.GetNativeImageNamed( - IDR_FILE_FOLDER).ToNSImage()]; - [folderViewer_ setTitle:nil]; - [folderViewer_ setBordered:false]; - [folderViewer_ setToolTip:nsTooltip]; - [self addSubview:folderViewer_]; - } - // Additional details text. base::string16 subscript = prefInfo.GetGalleryAdditionalDetails(); if (!subscript.empty()) { @@ -164,7 +145,6 @@ ui::MenuModel* MediaGalleryListEntryController::GetContextMenu( bounds.size = NSMakeSize(10000, 10000); [checkbox_ sizeToFit]; - [folderViewer_ sizeToFit]; [details_ sizeToFit]; // Auto size everything and lay it out horizontally. @@ -197,11 +177,6 @@ ui::MenuModel* MediaGalleryListEntryController::GetContextMenu( if (overflow > 0) { checkboxFrame.size.width -= overflow; [checkbox_ setFrameSize:checkboxFrame.size]; - if (folderViewer_.get()) { - NSRect folderViewerFrame = [folderViewer_ frame]; - folderViewerFrame.origin.x -= overflow; - [folderViewer_ setFrameOrigin:folderViewerFrame.origin]; - } if (details_.get()) { detailsFrame.origin.x -= overflow; [details_ setFrameOrigin:detailsFrame.origin]; diff --git a/chrome/browser/ui/views/extensions/media_galleries_dialog_views.cc b/chrome/browser/ui/views/extensions/media_galleries_dialog_views.cc index db71475..11e868e 100644 --- a/chrome/browser/ui/views/extensions/media_galleries_dialog_views.cc +++ b/chrome/browser/ui/views/extensions/media_galleries_dialog_views.cc @@ -191,8 +191,6 @@ bool MediaGalleriesDialogViews::AddOrUpdateGallery( const MediaGalleriesDialogController::Entry& gallery, views::View* container, int trailing_vertical_space) { - bool show_folder_viewer = controller_->ShouldShowFolderViewer(gallery); - CheckboxMap::iterator iter = checkbox_map_.find(gallery.pref_info.pref_id); if (iter != checkbox_map_.end()) { views::Checkbox* checkbox = iter->second->checkbox(); @@ -202,13 +200,11 @@ bool MediaGalleriesDialogViews::AddOrUpdateGallery( base::string16 details = gallery.pref_info.GetGalleryAdditionalDetails(); iter->second->secondary_text()->SetText(details); iter->second->secondary_text()->SetVisible(details.length() > 0); - iter->second->folder_viewer_button()->SetVisible(show_folder_viewer); return false; } - MediaGalleryCheckboxView* gallery_view = - new MediaGalleryCheckboxView(gallery.pref_info, show_folder_viewer, - trailing_vertical_space, this, this); + MediaGalleryCheckboxView* gallery_view = new MediaGalleryCheckboxView( + gallery.pref_info, trailing_vertical_space, this, this); gallery_view->checkbox()->SetChecked(gallery.selected); container->AddChildView(gallery_view); checkbox_map_[gallery.pref_info.pref_id] = gallery_view; @@ -290,10 +286,6 @@ void MediaGalleriesDialogViews::ButtonPressed(views::Button* sender, iter->second->checkbox()->checked()); return; } - if (sender == iter->second->folder_viewer_button()) { - controller_->DidClickOpenFolderViewer(iter->first); - return; - } } } diff --git a/chrome/browser/ui/views/extensions/media_gallery_checkbox_view.cc b/chrome/browser/ui/views/extensions/media_gallery_checkbox_view.cc index 6d8c8c6..c74918d 100644 --- a/chrome/browser/ui/views/extensions/media_gallery_checkbox_view.cc +++ b/chrome/browser/ui/views/extensions/media_gallery_checkbox_view.cc @@ -9,13 +9,11 @@ #include "grit/theme_resources.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/border.h" #include "ui/views/context_menu_controller.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/checkbox.h" -#include "ui/views/controls/button/image_button.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/layout_constants.h" @@ -29,7 +27,6 @@ const SkColor kDeemphasizedTextColor = SkColorSetRGB(159, 159, 159); MediaGalleryCheckboxView::MediaGalleryCheckboxView( const MediaGalleryPrefInfo& pref_info, - bool show_folder_button, int trailing_vertical_space, views::ButtonListener* button_listener, views::ContextMenuController* menu_controller) { @@ -50,21 +47,6 @@ MediaGalleryCheckboxView::MediaGalleryCheckboxView( base::string16 tooltip_text = pref_info.GetGalleryTooltip(); checkbox_->SetTooltipText(tooltip_text); - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - folder_viewer_button_ = new views::ImageButton(button_listener); - if (menu_controller) - folder_viewer_button_->set_context_menu_controller(menu_controller); - folder_viewer_button_->SetImage(views::ImageButton::STATE_NORMAL, - rb.GetImageSkiaNamed(IDR_FILE_FOLDER)); - folder_viewer_button_->SetImageAlignment(views::ImageButton::ALIGN_CENTER, - views::ImageButton::ALIGN_MIDDLE); - folder_viewer_button_->SetAccessibleName(l10n_util::GetStringUTF16( - IDS_MEDIA_GALLERIES_SCAN_RESULT_OPEN_FOLDER_VIEW_ACCESSIBILITY_NAME)); - folder_viewer_button_->SetFocusable(true); - folder_viewer_button_->SetVisible(show_folder_button); - folder_viewer_button_->SetBorder(views::Border::CreateEmptyBorder( - 0, views::kRelatedControlSmallHorizontalSpacing, 0, 0)); - base::string16 details = pref_info.GetGalleryAdditionalDetails(); secondary_text_ = new views::Label(details); if (menu_controller) @@ -77,7 +59,6 @@ MediaGalleryCheckboxView::MediaGalleryCheckboxView( 0, views::kRelatedControlSmallHorizontalSpacing, 0, 0)); AddChildView(checkbox_); - AddChildView(folder_viewer_button_); AddChildView(secondary_text_); } @@ -88,35 +69,25 @@ void MediaGalleryCheckboxView::Layout() { if (GetPreferredSize().width() <= GetLocalBounds().width()) return; - // If box layout doesn't fit, do custom layout. The folder_viewer_button and - // the secondary text should take up at most half of the space and the - // checkbox can take up what ever is left. + // If box layout doesn't fit, do custom layout. The secondary text should take + // up at most half of the space and the checkbox can take up whatever is left. int checkbox_width = checkbox_->GetPreferredSize().width(); - int folder_viewer_width = folder_viewer_button_->GetPreferredSize().width(); int secondary_text_width = secondary_text_->GetPreferredSize().width(); - if (!folder_viewer_button_->visible()) - folder_viewer_width = 0; if (!secondary_text_->visible()) secondary_text_width = 0; gfx::Rect area(GetLocalBounds()); area.Inset(GetInsets()); - if (folder_viewer_width + secondary_text_width > area.width() / 2) { + if (secondary_text_width > area.width() / 2) { secondary_text_width = - std::max(area.width() / 2 - folder_viewer_width, - area.width() - folder_viewer_width - checkbox_width); + std::max(area.width() / 2, area.width() - checkbox_width); } - checkbox_width = area.width() - folder_viewer_width - secondary_text_width; + checkbox_width = area.width() - secondary_text_width; checkbox_->SetBounds(area.x(), area.y(), checkbox_width, area.height()); - if (folder_viewer_button_->visible()) { - folder_viewer_button_->SetBounds(checkbox_->x() + checkbox_width, area.y(), - folder_viewer_width, area.height()); - } if (secondary_text_->visible()) { - secondary_text_->SetBounds( - checkbox_->x() + checkbox_width + folder_viewer_width, - area.y(), secondary_text_width, area.height()); + secondary_text_->SetBounds(checkbox_->x() + checkbox_width, area.y(), + secondary_text_width, area.height()); } } diff --git a/chrome/browser/ui/views/extensions/media_gallery_checkbox_view.h b/chrome/browser/ui/views/extensions/media_gallery_checkbox_view.h index 25cb8bc..6efba29 100644 --- a/chrome/browser/ui/views/extensions/media_gallery_checkbox_view.h +++ b/chrome/browser/ui/views/extensions/media_gallery_checkbox_view.h @@ -16,17 +16,15 @@ namespace views { class ButtonListener; class Checkbox; class ContextMenuController; -class ImageButton; class Label; } // namespace views // A view composed of a checkbox, optional folder icon button, and secondary -// text that will elide to its parent's width; used by MediaGalleriesDialogViews -// and MediaGalleriesScanResultDialogViews. +// text that will elide to its parent's width. Used by +// MediaGalleriesDialogViews. class MediaGalleryCheckboxView : public views::View { public: MediaGalleryCheckboxView(const MediaGalleryPrefInfo& pref_info, - bool show_button, int trailing_vertical_space, views::ButtonListener* button_listener, views::ContextMenuController* menu_controller); @@ -36,13 +34,11 @@ class MediaGalleryCheckboxView : public views::View { void Layout() override; views::Checkbox* checkbox() { return checkbox_; } - views::ImageButton* folder_viewer_button() { return folder_viewer_button_; } views::Label* secondary_text() { return secondary_text_; } private: // Owned by the parent class (views::View). views::Checkbox* checkbox_; - views::ImageButton* folder_viewer_button_; views::Label* secondary_text_; DISALLOW_COPY_AND_ASSIGN(MediaGalleryCheckboxView); diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi index 4a0e46c..0b4e00a 100644 --- a/chrome/chrome_browser.gypi +++ b/chrome/chrome_browser.gypi @@ -1267,8 +1267,6 @@ 'browser/media_galleries/mac/mtp_device_delegate_impl_mac.mm', 'browser/media_galleries/media_file_system_registry.cc', 'browser/media_galleries/media_file_system_registry.h', - 'browser/media_galleries/media_folder_finder.cc', - 'browser/media_galleries/media_folder_finder.h', 'browser/media_galleries/media_galleries_dialog_controller.cc', 'browser/media_galleries/media_galleries_dialog_controller.h', 'browser/media_galleries/media_galleries_histograms.cc', @@ -1279,15 +1277,8 @@ 'browser/media_galleries/media_galleries_preferences.h', 'browser/media_galleries/media_galleries_preferences_factory.cc', 'browser/media_galleries/media_galleries_preferences_factory.h', - 'browser/media_galleries/media_galleries_scan_result_controller.cc', - 'browser/media_galleries/media_galleries_scan_result_controller.h', 'browser/media_galleries/media_gallery_context_menu.cc', 'browser/media_galleries/media_gallery_context_menu.h', - 'browser/media_galleries/media_scan_manager.cc', - 'browser/media_galleries/media_scan_manager.h', - 'browser/media_galleries/media_scan_manager_observer.h', - 'browser/media_galleries/media_scan_types.cc', - 'browser/media_galleries/media_scan_types.h', 'browser/media_galleries/win/mtp_device_delegate_impl_win.cc', 'browser/media_galleries/win/mtp_device_delegate_impl_win.h', 'browser/media_galleries/win/mtp_device_object_entry.cc', diff --git a/chrome/chrome_tests_unit.gypi b/chrome/chrome_tests_unit.gypi index 74cf745..4f48f9c 100644 --- a/chrome/chrome_tests_unit.gypi +++ b/chrome/chrome_tests_unit.gypi @@ -1479,7 +1479,6 @@ 'browser/media_galleries/linux/mtp_device_object_enumerator_unittest.cc', 'browser/media_galleries/mac/mtp_device_delegate_impl_mac_unittest.mm', 'browser/media_galleries/media_file_system_registry_unittest.cc', - 'browser/media_galleries/media_folder_finder_unittest.cc', 'browser/media_galleries/media_galleries_dialog_controller_mock.cc', 'browser/media_galleries/media_galleries_dialog_controller_mock.h', 'browser/media_galleries/media_galleries_dialog_controller_test_util.cc', @@ -1487,8 +1486,6 @@ 'browser/media_galleries/media_galleries_permission_controller_unittest.cc', 'browser/media_galleries/media_galleries_permissions_unittest.cc', 'browser/media_galleries/media_galleries_preferences_unittest.cc', - 'browser/media_galleries/media_galleries_scan_result_controller_unittest.cc', - 'browser/media_galleries/media_scan_manager_unittest.cc', 'browser/media_galleries/win/mtp_device_delegate_impl_win_unittest.cc', 'browser/media_galleries/win/mtp_device_object_enumerator_unittest.cc', 'browser/memory/tab_manager_delegate_chromeos_unittest.cc', diff --git a/chrome/common/chrome_paths.cc b/chrome/common/chrome_paths.cc index fbb116a..364a02d 100644 --- a/chrome/common/chrome_paths.cc +++ b/chrome/common/chrome_paths.cc @@ -480,22 +480,6 @@ bool PathProvider(int key, base::FilePath* result) { break; } #endif -#if defined(OS_MACOSX) - case chrome::DIR_USER_LIBRARY: { - if (!GetUserLibraryDirectory(&cur)) - return false; - if (!base::PathExists(cur)) // We don't want to create this. - return false; - break; - } - case chrome::DIR_USER_APPLICATIONS: { - if (!GetUserApplicationsDirectory(&cur)) - return false; - if (!base::PathExists(cur)) // We don't want to create this. - return false; - break; - } -#endif #if defined(OS_CHROMEOS) || (defined(OS_LINUX) && defined(CHROMIUM_BUILD)) || \ defined(OS_MACOSX) case chrome::DIR_USER_EXTERNAL_EXTENSIONS: { diff --git a/chrome/common/chrome_paths.h b/chrome/common/chrome_paths.h index 4c488cc..b651082 100644 --- a/chrome/common/chrome_paths.h +++ b/chrome/common/chrome_paths.h @@ -46,10 +46,6 @@ enum { // to set policies for chrome. This directory // contains subdirectories. #endif -#if defined(OS_MACOSX) - DIR_USER_APPLICATIONS, // ~/Applications - DIR_USER_LIBRARY, // ~/Library -#endif #if defined(OS_CHROMEOS) || (defined(OS_LINUX) && defined(CHROMIUM_BUILD)) || \ defined(OS_MACOSX) DIR_USER_EXTERNAL_EXTENSIONS, // Directory for per-user external extensions diff --git a/chrome/common/chrome_paths_internal.h b/chrome/common/chrome_paths_internal.h index a5c14f1..10aafba 100644 --- a/chrome/common/chrome_paths_internal.h +++ b/chrome/common/chrome_paths_internal.h @@ -80,12 +80,6 @@ base::FilePath GetFrameworkBundlePath(); // Get the local library directory. bool GetLocalLibraryDirectory(base::FilePath* result); -// Get the user library directory. -bool GetUserLibraryDirectory(base::FilePath* result); - -// Get the user applications directory. -bool GetUserApplicationsDirectory(base::FilePath* result); - // Get the global Application Support directory (under /Library/). bool GetGlobalApplicationSupportDirectory(base::FilePath* result); diff --git a/chrome/common/chrome_paths_mac.mm b/chrome/common/chrome_paths_mac.mm index 5d69520..da39eac 100644 --- a/chrome/common/chrome_paths_mac.mm +++ b/chrome/common/chrome_paths_mac.mm @@ -216,14 +216,6 @@ bool GetLocalLibraryDirectory(base::FilePath* result) { return base::mac::GetLocalDirectory(NSLibraryDirectory, result); } -bool GetUserLibraryDirectory(base::FilePath* result) { - return base::mac::GetUserDirectory(NSLibraryDirectory, result); -} - -bool GetUserApplicationsDirectory(base::FilePath* result) { - return base::mac::GetUserDirectory(NSApplicationDirectory, result); -} - bool GetGlobalApplicationSupportDirectory(base::FilePath* result) { return base::mac::GetLocalDirectory(NSApplicationSupportDirectory, result); } diff --git a/chrome/common/extensions/api/idltest.idl b/chrome/common/extensions/api/idltest.idl index 9cb8bb2..4bb0ab5 100644 --- a/chrome/common/extensions/api/idltest.idl +++ b/chrome/common/extensions/api/idltest.idl @@ -25,6 +25,11 @@ namespace idltest { // |switch| should cause compile errors if it does). But the name should // get defined and made visible from within extensions/apps code. [nocompile] static void nocompileFunc(long switch); + + // This function should not have C++ code autogenerated (the variable name + // |switch| should cause compile errors if it does). The name should also + // never be defined in Javascript and invisible to extensions/apps code. + [nodefine] static void nodefineFunc(long switch); }; }; diff --git a/chrome/common/extensions/api/media_galleries.idl b/chrome/common/extensions/api/media_galleries.idl index 9592673..8c257c4 100644 --- a/chrome/common/extensions/api/media_galleries.idl +++ b/chrome/common/extensions/api/media_galleries.idl @@ -33,7 +33,7 @@ namespace mediaGalleries { mimeTypeOnly }; - [inline_doc] enum ScanProgressType { + [nodefine, inline_doc] enum ScanProgressType { // The scan started. start, // The scan was cancelled. @@ -44,11 +44,11 @@ namespace mediaGalleries { // The scan encountered an error and could not proceed. error }; - + [inline_doc] dictionary GalleryChangeDetails { // Type of change event. GalleryChangeType type; - + // Identifies the modified gallery. DOMString galleryId; }; @@ -99,7 +99,7 @@ namespace mediaGalleries { boolean isAvailable; }; - [inline_doc] dictionary ScanProgressDetails { + [nodefine, inline_doc] dictionary ScanProgressDetails { // The type of progress event, i.e. start, finish, etc. ScanProgressType type; @@ -119,7 +119,7 @@ namespace mediaGalleries { dictionary StreamInfo { // Describes format of container or codec of stream, i.e. "mp3", "h264". DOMString type; - + // An unfiltered string->string dictionary of tags for the stream. object tags; }; @@ -138,7 +138,7 @@ namespace mediaGalleries { // Defined for audio and video. In seconds. double? duration; - + // Defined for images and video. In degrees. long? rotation; @@ -204,16 +204,19 @@ namespace mediaGalleries { // The scan may take a long time so progress and completion is communicated // by events. No permission is granted as a result of the scan, see // addScanResults. + [nodefine, deprecated="The mediaGalleries API no longer supports scanning."] static void startMediaScan(); // Cancel any pending media scan. Well behaved apps should provide a way // for the user to cancel scans they start. + [nodefine, deprecated="The mediaGalleries API no longer supports scanning."] static void cancelMediaScan(); // Show the user the scan results and let them add any or all of them as // galleries. This should be used after the 'finish' onScanProgress() // event has happened. All galleries the app has access to are returned, not // just the newly added galleries. + [nodefine, deprecated="The mediaGalleries API no longer supports scanning."] static void addScanResults(MediaFileSystemsCallback callback); // Get metadata about a specific media file system. @@ -251,6 +254,7 @@ namespace mediaGalleries { // The pending media scan has changed state. See details for more // information. + [nodefine, deprecated="The mediaGalleries API no longer supports scanning."] static void onScanProgress(ScanProgressDetails details); }; }; diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index eea95a4..83e3803 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc @@ -1967,9 +1967,6 @@ const char kMediaGalleriesUniqueId[] = "media_galleries.gallery_id"; // gallery. const char kMediaGalleriesRememberedGalleries[] = "media_galleries.remembered_galleries"; - -// The last time a media scan completed. -const char kMediaGalleriesLastScanTime[] = "media_galleries.last_scan_time"; #endif // !defined(OS_ANDROID) #if defined(USE_ASH) diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 4f2e79a..15417d7 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h @@ -694,7 +694,6 @@ extern const char kAttemptedToEnableAutoupdate[]; extern const char kMediaGalleriesUniqueId[]; extern const char kMediaGalleriesRememberedGalleries[]; -extern const char kMediaGalleriesLastScanTime[]; #endif // !defined(OS_ANDROID) #if defined(USE_ASH) diff --git a/chrome/renderer/resources/extensions/media_galleries_custom_bindings.js b/chrome/renderer/resources/extensions/media_galleries_custom_bindings.js index 8050ed1..277a222 100644 --- a/chrome/renderer/resources/extensions/media_galleries_custom_bindings.js +++ b/chrome/renderer/resources/extensions/media_galleries_custom_bindings.js @@ -30,9 +30,8 @@ function createFileSystemObjectsAndUpdateMetadata(response) { binding.registerCustomHook(function(bindingsAPI, extensionId) { var apiFunctions = bindingsAPI.apiFunctions; - // getMediaFileSystems, addUserSelectedFolder, and addScanResults use a - // custom callback so that they can instantiate and return an array of file - // system objects. + // getMediaFileSystems and addUserSelectedFolder use a custom callback so that + // they can instantiate and return an array of file system objects. apiFunctions.setCustomCallback('getMediaFileSystems', function(name, request, callback, response) { var result = createFileSystemObjectsAndUpdateMetadata(response); @@ -40,13 +39,6 @@ binding.registerCustomHook(function(bindingsAPI, extensionId) { callback(result); }); - apiFunctions.setCustomCallback('addScanResults', - function(name, request, callback, response) { - var result = createFileSystemObjectsAndUpdateMetadata(response); - if (callback) - callback(result); - }); - apiFunctions.setCustomCallback('addUserSelectedFolder', function(name, request, callback, response) { var fileSystems = []; diff --git a/chrome/test/data/extensions/api_test/idltest/nocompile/nocompile.js b/chrome/test/data/extensions/api_test/idltest/nocompile/nocompile.js index a7bbf9c..c7aa344 100644 --- a/chrome/test/data/extensions/api_test/idltest/nocompile/nocompile.js +++ b/chrome/test/data/extensions/api_test/idltest/nocompile/nocompile.js @@ -4,7 +4,7 @@ chrome.test.runTests([ - function functionDefinition() { + function nocompileFunc() { chrome.test.assertEq("function", typeof(chrome.idltest.nocompileFunc)); chrome.test.succeed(); } diff --git a/chrome/test/data/extensions/api_test/idltest/nodefine/manifest.json b/chrome/test/data/extensions/api_test/idltest/nodefine/manifest.json new file mode 100644 index 0000000..ee5fb1a --- /dev/null +++ b/chrome/test/data/extensions/api_test/idltest/nodefine/manifest.json @@ -0,0 +1,6 @@ +{ + "name": "IDLTest API test extension", + "version": "0.5", + "permissions": ["idltest"], + "manifest_version": 2 +} diff --git a/chrome/test/data/extensions/api_test/idltest/nodefine/nodefine.html b/chrome/test/data/extensions/api_test/idltest/nodefine/nodefine.html new file mode 100644 index 0000000..9bbd496 --- /dev/null +++ b/chrome/test/data/extensions/api_test/idltest/nodefine/nodefine.html @@ -0,0 +1 @@ +<script src="nodefine.js"></script> diff --git a/chrome/test/data/extensions/api_test/idltest/nodefine/nodefine.js b/chrome/test/data/extensions/api_test/idltest/nodefine/nodefine.js new file mode 100644 index 0000000..28547d4 --- /dev/null +++ b/chrome/test/data/extensions/api_test/idltest/nodefine/nodefine.js @@ -0,0 +1,12 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +chrome.test.runTests([ + + function nodefineFunc() { + chrome.test.assertEq("undefined", typeof(chrome.idltest.nodefineFunc)); + chrome.test.succeed(); + } + +]); diff --git a/chrome/test/data/extensions/api_test/media_galleries/cancel_scan/manifest.json b/chrome/test/data/extensions/api_test/media_galleries/cancel_scan/manifest.json deleted file mode 100644 index db7143c..0000000 --- a/chrome/test/data/extensions/api_test/media_galleries/cancel_scan/manifest.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "chrome.mediaGalleries.cancel_scan", - "version": "0.1", - "description": "test scan cancel callbacks", - "app": { - "background": { - "scripts": ["common_injected.js", "test.js"] - } - }, - "permissions": [{"mediaGalleries": ["read", "allAutoDetected", "scan"]}] -} diff --git a/chrome/test/data/extensions/api_test/media_galleries/cancel_scan/test.js b/chrome/test/data/extensions/api_test/media_galleries/cancel_scan/test.js deleted file mode 100644 index aae404f..0000000 --- a/chrome/test/data/extensions/api_test/media_galleries/cancel_scan/test.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var mediaGalleries = chrome.mediaGalleries; - -function StartAndCancelMediaScanTest() { - function StartMediaScanTest() { - var startEventListener = function(details) { - chrome.test.assertEq('start', details.type); - mediaGalleries.onScanProgress.removeListener(startEventListener); - CancelMediaScanTest(); - } - mediaGalleries.onScanProgress.addListener(startEventListener); - - mediaGalleries.startMediaScan(); - } - - function CancelMediaScanTest() { - var cancelEventListener = function(details) { - chrome.test.assertEq('cancel', details.type); - mediaGalleries.onScanProgress.removeListener(cancelEventListener); - chrome.test.succeed(); - }; - mediaGalleries.onScanProgress.addListener(cancelEventListener); - - mediaGalleries.cancelMediaScan(); - } - - StartMediaScanTest(); -} - -CreateDummyWindowToPreventSleep(); - -chrome.test.runTests([ - StartAndCancelMediaScanTest, -]); diff --git a/chrome/test/data/extensions/api_test/media_galleries/no_access/test.js b/chrome/test/data/extensions/api_test/media_galleries/no_access/test.js index 9d93ba4..7b74cf4 100644 --- a/chrome/test/data/extensions/api_test/media_galleries/no_access/test.js +++ b/chrome/test/data/extensions/api_test/media_galleries/no_access/test.js @@ -63,15 +63,5 @@ chrome.test.getConfig(function(config) { function invalidFileCopyToShouldFail() { runCopyToTest(invalidWEBPImageCase, false /* expect failure */); }, - function MediaScanWithoutPermission() { - var startListener = function(details) { - chrome.test.assertEq('error', details.type); - mediaGalleries.onScanProgress.removeListener(startListener); - chrome.test.succeed(); - } - mediaGalleries.onScanProgress.addListener(startListener); - - mediaGalleries.startMediaScan(); - } ]); }) diff --git a/chrome/test/data/extensions/api_test/media_galleries/scan/manifest.json b/chrome/test/data/extensions/api_test/media_galleries/scan/manifest.json deleted file mode 100644 index ab882a5..0000000 --- a/chrome/test/data/extensions/api_test/media_galleries/scan/manifest.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "chrome.mediaGalleries.scan", - "version": "0.1", - "description": "test scan callbacks", - "app": { - "background": { - "scripts": ["common_injected.js", "test.js"] - } - }, - "permissions": [{"mediaGalleries": ["read", "allAutoDetected", "scan"]}] -} diff --git a/chrome/test/data/extensions/api_test/media_galleries/scan/test.js b/chrome/test/data/extensions/api_test/media_galleries/scan/test.js deleted file mode 100644 index 21c061e..0000000 --- a/chrome/test/data/extensions/api_test/media_galleries/scan/test.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var mediaGalleries = chrome.mediaGalleries; - -function MediaScanTest() { - var scanProgress = 'start'; - var initialGalleryCount = 0; - - function OnScanResultsAdded(galleries) { - chrome.test.assertEq(initialGalleryCount + 1, galleries.length); - chrome.test.succeed(); - } - - function OnScanProgress(details) { - chrome.test.assertEq(scanProgress, details.type); - if (scanProgress == 'start') { - scanProgress = 'finish'; - } else { - scanProgress = 'done'; - chrome.test.runWithUserGesture(function() { - mediaGalleries.addScanResults(OnScanResultsAdded); - }); - } - } - - function OnInitialMediaGalleries(galleries) { - initialGalleryCount = galleries.length; - mediaGalleries.onScanProgress.addListener(OnScanProgress); - mediaGalleries.startMediaScan(); - } - - mediaGalleries.getMediaFileSystems(OnInitialMediaGalleries); -} - -CreateDummyWindowToPreventSleep(); - -chrome.test.runTests([ - MediaScanTest, -]); diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index a312c5a..3b9bf6a 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h @@ -721,9 +721,9 @@ enum HistogramValue { DELETED_READINGLISTPRIVATE_ADDENTRY, DELETED_READINGLISTPRIVATE_REMOVEENTRY, DELETED_READINGLISTPRIVATE_GETENTRIES, - MEDIAGALLERIES_STARTMEDIASCAN, - MEDIAGALLERIES_CANCELMEDIASCAN, - MEDIAGALLERIES_ADDSCANRESULTS, + DELETED_MEDIAGALLERIES_STARTMEDIASCAN, + DELETED_MEDIAGALLERIES_CANCELMEDIASCAN, + DELETED_MEDIAGALLERIES_ADDSCANRESULTS, LOGPRIVATE_STARTNETINTERNALSWATCH, LOGPRIVATE_STOPNETINTERNALSWATCH, FILEMANAGERPRIVATE_GETPROFILES, diff --git a/extensions/common/permissions/media_galleries_permission.cc b/extensions/common/permissions/media_galleries_permission.cc index 6a43268..4ac5ae6 100644 --- a/extensions/common/permissions/media_galleries_permission.cc +++ b/extensions/common/permissions/media_galleries_permission.cc @@ -96,7 +96,6 @@ void AddPermissionsToLists( const char MediaGalleriesPermission::kAllAutoDetectedPermission[] = "allAutoDetected"; -const char MediaGalleriesPermission::kScanPermission[] = "scan"; const char MediaGalleriesPermission::kReadPermission[] = "read"; const char MediaGalleriesPermission::kCopyToPermission[] = "copyTo"; const char MediaGalleriesPermission::kDeletePermission[] = "delete"; @@ -137,8 +136,7 @@ bool MediaGalleriesPermission::FromValue( bool has_delete = false; for (std::set<MediaGalleriesPermissionData>::const_iterator it = data_set_.begin(); it != data_set_.end(); ++it) { - if (it->permission() == kAllAutoDetectedPermission || - it->permission() == kScanPermission) { + if (it->permission() == kAllAutoDetectedPermission) { continue; } if (it->permission() == kReadPermission) { diff --git a/extensions/common/permissions/media_galleries_permission_data.cc b/extensions/common/permissions/media_galleries_permission_data.cc index d7e7937..495c1f9 100644 --- a/extensions/common/permissions/media_galleries_permission_data.cc +++ b/extensions/common/permissions/media_galleries_permission_data.cc @@ -39,7 +39,6 @@ bool MediaGalleriesPermissionData::FromValue(const base::Value* value) { base::TrimWhitespaceASCII(raw_permission, base::TRIM_ALL, &permission); if (permission == MediaGalleriesPermission::kAllAutoDetectedPermission || - permission == MediaGalleriesPermission::kScanPermission || permission == MediaGalleriesPermission::kReadPermission || permission == MediaGalleriesPermission::kCopyToPermission || permission == MediaGalleriesPermission::kDeletePermission) { diff --git a/tools/json_schema_compiler/compiler.py b/tools/json_schema_compiler/compiler.py index feb354d..c626f2f 100755 --- a/tools/json_schema_compiler/compiler.py +++ b/tools/json_schema_compiler/compiler.py @@ -59,6 +59,10 @@ def GenerateSchema(generator_name, # If compiling the C++ model code, delete 'nocompile' nodes. if generator_name == 'cpp': api_def = json_schema.DeleteNodes(api_def, 'nocompile') + + # Delete all 'nodefine' nodes. They are only for documentation. + api_def = json_schema.DeleteNodes(api_def, 'nodefine') + api_defs.extend(api_def) api_model = Model(allow_inline_enums=False) diff --git a/tools/json_schema_compiler/idl_schema.py b/tools/json_schema_compiler/idl_schema.py index 65d7bae..58efe28 100755 --- a/tools/json_schema_compiler/idl_schema.py +++ b/tools/json_schema_compiler/idl_schema.py @@ -149,6 +149,8 @@ class Dictionary(object): result = {'id': self.node.GetName(), 'properties': properties, 'type': 'object'} + if self.node.GetProperty('nodefine'): + result['nodefine'] = True if self.node.GetProperty('nodoc'): result['nodoc'] = True elif self.node.GetProperty('inline_doc'): @@ -175,7 +177,8 @@ class Member(object): properties['deprecated'] = self.node.GetProperty('deprecated') if self.node.GetProperty('allowAmbiguousOptionalArguments'): properties['allowAmbiguousOptionalArguments'] = True - for property_name in ('OPTIONAL', 'nodoc', 'nocompile', 'nodart'): + for property_name in ('OPTIONAL', 'nodoc', 'nocompile', 'nodart', + 'nodefine'): if self.node.GetProperty(property_name): properties[property_name.lower()] = True for option_name, sanitizer in [ @@ -357,8 +360,8 @@ class Enum(object): 'description': self.description, 'type': 'string', 'enum': enum} - for property_name in ( - 'inline_doc', 'noinline_doc', 'nodoc', 'cpp_enum_prefix_override',): + for property_name in ('cpp_enum_prefix_override', 'inline_doc', + 'noinline_doc', 'nodefine', 'nodoc',): if self.node.GetProperty(property_name): result[property_name] = self.node.GetProperty(property_name) if self.node.GetProperty('deprecated'): diff --git a/tools/json_schema_compiler/idl_schema_test.py b/tools/json_schema_compiler/idl_schema_test.py index 03960c3..3e0d3cc 100755 --- a/tools/json_schema_compiler/idl_schema_test.py +++ b/tools/json_schema_compiler/idl_schema_test.py @@ -126,6 +126,12 @@ class IdlSchemaTest(unittest.TestCase): self.assertTrue(func is not None) self.assertTrue(func['nocompile']) + def testNoDefine(self): + schema = self.idl_basics + func = getFunction(schema, 'function31') + self.assertTrue(func is not None) + self.assertTrue(func['nodefine']) + def testNoDocOnEnum(self): schema = self.idl_basics enum_with_nodoc = getType(schema, 'EnumTypeWithNoDoc') diff --git a/tools/json_schema_compiler/model.py b/tools/json_schema_compiler/model.py index 642e818..e0147b5 100644 --- a/tools/json_schema_compiler/model.py +++ b/tools/json_schema_compiler/model.py @@ -303,6 +303,7 @@ class Function(object): self.optional = json.get('optional', False) self.parent = parent self.nocompile = json.get('nocompile') + self.nodefine = json.get('nodefine') options = json.get('options', {}) self.conditions = options.get('conditions', []) self.actions = options.get('actions', []) diff --git a/tools/json_schema_compiler/test/idl_basics.idl b/tools/json_schema_compiler/test/idl_basics.idl index 9ee4922..bfa49dc 100644 --- a/tools/json_schema_compiler/test/idl_basics.idl +++ b/tools/json_schema_compiler/test/idl_basics.idl @@ -100,6 +100,8 @@ static EnumType[] function28(); static idl_other_namespace.SomeType function29(); static idl_other_namespace.SomeType[] function30(); + + [nodefine] static void function31(long switch); }; interface Events { diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 193a4e4..919f702 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml @@ -65422,9 +65422,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. <int value="660" label="DELETED_READINGLISTPRIVATE_ADDENTRY"/> <int value="661" label="DELETED_READINGLISTPRIVATE_REMOVEENTRY"/> <int value="662" label="DELETED_READINGLISTPRIVATE_GETENTRIES"/> - <int value="663" label="MEDIAGALLERIES_STARTMEDIASCAN"/> - <int value="664" label="MEDIAGALLERIES_CANCELMEDIASCAN"/> - <int value="665" label="MEDIAGALLERIES_ADDSCANRESULTS"/> + <int value="663" label="DELETED_MEDIAGALLERIES_STARTMEDIASCAN"/> + <int value="664" label="DELETED_MEDIAGALLERIES_CANCELMEDIASCAN"/> + <int value="665" label="DELETED_MEDIAGALLERIES_ADDSCANRESULTS"/> <int value="666" label="LOGPRIVATE_STARTNETINTERNALSWATCH"/> <int value="667" label="LOGPRIVATE_STOPNETINTERNALSWATCH"/> <int value="668" label="FILEMANAGERPRIVATE_GETPROFILES"/> @@ -73410,13 +73410,14 @@ To add a new entry, add it with any value and run test to compute valid value. <int value="11" label="GetAllMediaFileSystemMetadata API invocations"/> <int value="12" label="GetMetadata API invocations"/> <int value="13" label="AddUserSelectedFolder API invocations"/> - <int value="14" label="StartMediaScan API invocations"/> - <int value="15" label="CancelMediaScan API invocations"/> - <int value="16" label="AddScanResults API invocations"/> - <int value="17" label="A media scan completed"/> - <int value="18" label="AddScanResults dialog cancelled"/> - <int value="19" label="AddScanResults dialog accepted"/> - <int value="20" label="Gallery removed from AddScanResults dialog"/> + <int value="14" label="StartMediaScan API invocations (obsolete)"/> + <int value="15" label="CancelMediaScan API invocations (obsolete)"/> + <int value="16" label="AddScanResults API invocations (obsolete)"/> + <int value="17" label="A media scan completed (obsolete)"/> + <int value="18" label="AddScanResults dialog cancelled (obsolete)"/> + <int value="19" label="AddScanResults dialog accepted (obsolete)"/> + <int value="20" + label="Gallery removed from AddScanResults dialog (obsolete)"/> <int value="21" label="Gallery removed from permission dialog"/> <int value="22" label="DropPermissionForMediaFileSystem API invocations"/> <int value="23" label="GetAllGalleryWatch API invocations"/> |