1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
|
// Copyright (c) 2012 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/chromeos/extensions/file_manager/file_manager_util.h"
#include "ash/shell.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/json/json_file_value_serializer.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/drive_file_system.h"
#include "chrome/browser/chromeos/drive/drive_file_system_util.h"
#include "chrome/browser/chromeos/drive/drive_system_service.h"
#include "chrome/browser/chromeos/extensions/file_manager/file_browser_handler.h"
#include "chrome/browser/chromeos/extensions/file_manager/file_handler_util.h"
#include "chrome/browser/chromeos/media/media_player.h"
#include "chrome/browser/extensions/crx_installer.h"
#include "chrome/browser/extensions/extension_install_prompt.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/google_apis/task_util.h"
#include "chrome/browser/plugins/plugin_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_iterator.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/simple_message_box.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/pepper_plugin_info.h"
#include "grit/generated_resources.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/screen.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_mount_point_provider.h"
#include "webkit/fileapi/file_system_operation.h"
#include "webkit/fileapi/file_system_url.h"
#include "webkit/fileapi/file_system_util.h"
#include "webkit/plugins/webplugininfo.h"
using base::DictionaryValue;
using base::ListValue;
using content::BrowserContext;
using content::BrowserThread;
using content::PluginService;
using content::UserMetricsAction;
using extensions::Extension;
using file_handler_util::FileTaskExecutor;
using fileapi::FileSystemURL;
#define FILEBROWSER_EXTENSON_ID "hhaomjibdihmijegdhdafkllkbggdgoj"
const char kFileBrowserDomain[] = FILEBROWSER_EXTENSON_ID;
const char kFileBrowserGalleryTaskId[] = "gallery";
const char kFileBrowserMountArchiveTaskId[] = "mount-archive";
const char kFileBrowserWatchTaskId[] = "watch";
const char kFileBrowserPlayTaskId[] = "play";
const char kVideoPlayerAppName[] = "videoplayer";
namespace file_manager_util {
namespace {
#define FILEBROWSER_URL(PATH) \
("chrome-extension://" FILEBROWSER_EXTENSON_ID "/" PATH)
// This is the "well known" url for the file manager extension from
// browser/resources/file_manager. In the future we may provide a way to swap
// out this file manager for an aftermarket part, but not yet.
const char kFileBrowserExtensionUrl[] = FILEBROWSER_URL("");
const char kBaseFileBrowserUrl[] = FILEBROWSER_URL("main.html");
const char kBaseFileBrowserNewUIUrl[] = FILEBROWSER_URL("main_new_ui.html");
const char kMediaPlayerUrl[] = FILEBROWSER_URL("mediaplayer.html");
const char kVideoPlayerUrl[] = FILEBROWSER_URL("video_player.html");
const char kActionChoiceUrl[] = FILEBROWSER_URL("action_choice.html");
#undef FILEBROWSER_URL
#undef FILEBROWSER_EXTENSON_ID
const char kCRXExtension[] = ".crx";
const char kPdfExtension[] = ".pdf";
const char kSwfExtension[] = ".swf";
// List of file extension we can open in tab.
const char* kBrowserSupportedExtensions[] = {
#if defined(GOOGLE_CHROME_BUILD)
".pdf", ".swf",
#endif
".bmp", ".jpg", ".jpeg", ".png", ".webp", ".gif", ".txt", ".html", ".htm",
".mhtml", ".mht", ".svg"
};
// Keep in sync with 'open-hosted' task handler in the File Browser manifest.
const char* kGDocsExtensions[] = {
".gdoc", ".gsheet", ".gslides", ".gdraw", ".gtable", ".glink"
};
// List of all extensions we want to be shown in histogram that keep track of
// files that were unsuccessfully tried to be opened.
// The list has to be synced with histogram values.
const char* kUMATrackingExtensions[] = {
"other", ".doc", ".docx", ".odt", ".rtf", ".pdf", ".ppt", ".pptx", ".odp",
".xls", ".xlsx", ".ods", ".csv", ".odf", ".rar", ".asf", ".wma", ".wmv",
".mov", ".mpg", ".log"
};
bool IsSupportedBrowserExtension(const char* file_extension) {
for (size_t i = 0; i < arraysize(kBrowserSupportedExtensions); i++) {
if (base::strcasecmp(file_extension, kBrowserSupportedExtensions[i]) == 0) {
return true;
}
}
return false;
}
bool IsSupportedGDocsExtension(const char* file_extension) {
for (size_t i = 0; i < arraysize(kGDocsExtensions); i++) {
if (base::strcasecmp(file_extension, kGDocsExtensions[i]) == 0) {
return true;
}
}
return false;
}
bool IsCRXFile(const char* file_extension) {
return base::strcasecmp(file_extension, kCRXExtension) == 0;
}
bool IsPepperPluginEnabled(Profile* profile,
const base::FilePath& plugin_path) {
content::PepperPluginInfo* pepper_info =
PluginService::GetInstance()->GetRegisteredPpapiPluginInfo(plugin_path);
if (!pepper_info)
return false;
PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(profile);
if (!plugin_prefs)
return false;
return plugin_prefs->IsPluginEnabled(pepper_info->ToWebPluginInfo());
}
bool IsPdfPluginEnabled(Profile* profile) {
base::FilePath plugin_path;
PathService::Get(chrome::FILE_PDF_PLUGIN, &plugin_path);
return IsPepperPluginEnabled(profile, plugin_path);
}
bool IsFlashPluginEnabled(Profile* profile) {
base::FilePath plugin_path(
CommandLine::ForCurrentProcess()->GetSwitchValueNative(
switches::kPpapiFlashPath));
if (plugin_path.empty())
PathService::Get(chrome::FILE_PEPPER_FLASH_PLUGIN, &plugin_path);
return IsPepperPluginEnabled(profile, plugin_path);
}
// Returns index |ext| has in the |array|. If there is no |ext| in |array|, last
// element's index is return (last element should have irrelevant value).
int UMAExtensionIndex(const char *file_extension,
const char** array,
size_t array_size) {
for (size_t i = 0; i < array_size; i++) {
if (base::strcasecmp(file_extension, array[i]) == 0) {
return i;
}
}
return 0;
}
// Convert numeric dialog type to a string.
std::string GetDialogTypeAsString(
ui::SelectFileDialog::Type dialog_type) {
std::string type_str;
switch (dialog_type) {
case ui::SelectFileDialog::SELECT_NONE:
type_str = "full-page";
break;
case ui::SelectFileDialog::SELECT_FOLDER:
type_str = "folder";
break;
case ui::SelectFileDialog::SELECT_SAVEAS_FILE:
type_str = "saveas-file";
break;
case ui::SelectFileDialog::SELECT_OPEN_FILE:
type_str = "open-file";
break;
case ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE:
type_str = "open-multi-file";
break;
default:
NOTREACHED();
}
return type_str;
}
DictionaryValue* ProgessStatusToDictionaryValue(
Profile* profile,
const std::string& extension_id,
const google_apis::OperationProgressStatus& status) {
scoped_ptr<DictionaryValue> result(new DictionaryValue());
GURL file_url;
if (file_manager_util::ConvertFileToFileSystemUrl(profile,
drive::util::GetSpecialRemoteRootPath().Append(
base::FilePath(status.file_path)),
extension_id,
&file_url)) {
result->SetString("fileUrl", file_url.spec());
}
result->SetString("transferState",
OperationTransferStateToString(status.transfer_state));
result->SetString("transferType",
OperationTypeToString(status.operation_type));
result->SetInteger("processed", static_cast<int>(status.progress_current));
result->SetInteger("total", static_cast<int>(status.progress_total));
return result.release();
}
void OpenNewTab(Profile* profile, const GURL& url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
Browser* browser = chrome::FindOrCreateTabbedBrowser(
profile ? profile : ProfileManager::GetDefaultProfileOrOffTheRecord(),
chrome::HOST_DESKTOP_TYPE_ASH);
chrome::AddSelectedTabWithURL(browser, url, content::PAGE_TRANSITION_LINK);
// If the current browser is not tabbed then the new tab will be created
// in a different browser. Make sure it is visible.
browser->window()->Show();
}
// Shows a warning message box saying that the file could not be opened.
void ShowWarningMessageBox(Profile* profile, const base::FilePath& path) {
// TODO: if FindOrCreateTabbedBrowser creates a new browser the returned
// browser is leaked.
Browser* browser =
chrome::FindOrCreateTabbedBrowser(profile,
chrome::HOST_DESKTOP_TYPE_ASH);
chrome::ShowMessageBox(
browser->window()->GetNativeWindow(),
l10n_util::GetStringFUTF16(
IDS_FILE_BROWSER_ERROR_VIEWING_FILE_TITLE,
UTF8ToUTF16(path.BaseName().value())),
l10n_util::GetStringUTF16(IDS_FILE_BROWSER_ERROR_VIEWING_FILE),
chrome::MESSAGE_BOX_TYPE_WARNING);
}
void InstallCRX(Browser* browser, const base::FilePath& path) {
ExtensionService* service =
extensions::ExtensionSystem::Get(browser->profile())->extension_service();
CHECK(service);
content::WebContents* web_contents =
browser->tab_strip_model()->GetActiveWebContents();
scoped_refptr<extensions::CrxInstaller> installer(
extensions::CrxInstaller::Create(
service,
new ExtensionInstallPrompt(web_contents)));
installer->set_error_on_unsupported_requirements(true);
installer->set_is_gallery_install(false);
installer->set_allow_silent_install(false);
installer->InstallCrx(path);
}
// Called when a crx file on Drive was downloaded.
void OnCRXDownloadCallback(Browser* browser,
drive::FileError error,
const base::FilePath& file,
const std::string& unused_mime_type,
drive::DriveFileType file_type) {
if (error != drive::FILE_ERROR_OK || file_type != drive::REGULAR_FILE)
return;
InstallCRX(browser, file);
}
enum TAB_REUSE_MODE {
REUSE_ANY_FILE_MANAGER,
REUSE_SAME_PATH,
REUSE_NEVER
};
bool FileManageTabExists(const base::FilePath& path, TAB_REUSE_MODE mode) {
if (mode == REUSE_NEVER)
return false;
// We always open full-tab File Manager via chrome://files URL, never
// chrome-extension://, so we only check against chrome://files
const GURL origin(chrome::kChromeUIFileManagerURL);
const std::string ref = std::string("/") + path.value();
for (chrome::BrowserIterator it; !it.done(); it.Next()) {
Browser* browser = *it;
TabStripModel* tab_strip = browser->tab_strip_model();
for (int idx = 0; idx < tab_strip->count(); idx++) {
content::WebContents* web_contents = tab_strip->GetWebContentsAt(idx);
const GURL& url = web_contents->GetURL();
if (origin == url.GetOrigin()) {
if (mode == REUSE_ANY_FILE_MANAGER || ref == url.ref()) {
if (mode == REUSE_SAME_PATH && tab_strip->active_index() != idx) {
browser->window()->Show();
tab_strip->ActivateTabAt(idx, false);
}
return true;
}
}
}
}
return false;
}
bool IsFileManagerPackaged() {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
return !command_line->HasSwitch(switches::kFileManagerLegacy);
}
bool IsFileManagerNewUI() {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
return !command_line->HasSwitch(switches::kFileManagerLegacyUI);
}
// Grants file system access to the file browser.
bool GrantFileSystemAccessToFileBrowser(Profile* profile) {
// File browser always runs in the site for its extension id, so that is the
// site for which file access permissions should be granted.
GURL site = extensions::ExtensionSystem::Get(profile)->extension_service()->
GetSiteForExtensionId(kFileBrowserDomain);
fileapi::ExternalFileSystemMountPointProvider* external_provider =
BrowserContext::GetStoragePartitionForSite(profile, site)->
GetFileSystemContext()->external_provider();
if (!external_provider)
return false;
external_provider->GrantFullAccessToExtension(GetFileBrowserUrl().host());
return true;
}
// Executes handler specifed with |extension_id| and |action_id| for |url|.
void ExecuteHandler(Profile* profile,
std::string extension_id,
std::string action_id,
const GURL& url) {
// If File Browser has not been open yet then it did not request access
// to the file system. Do it now.
if (!GrantFileSystemAccessToFileBrowser(profile))
return;
GURL site = extensions::ExtensionSystem::Get(profile)->extension_service()->
GetSiteForExtensionId(kFileBrowserDomain);
fileapi::FileSystemContext* file_system_context =
BrowserContext::GetStoragePartitionForSite(profile, site)->
GetFileSystemContext();
// We are executing the task on behalf of File Browser extension.
const GURL source_url = GetFileBrowserUrl();
std::vector<FileSystemURL> urls;
urls.push_back(file_system_context->CrackURL(url));
scoped_refptr<FileTaskExecutor> executor = FileTaskExecutor::Create(profile,
source_url, kFileBrowserDomain, 0 /* no tab id */, extension_id,
file_handler_util::kTaskFile, action_id);
executor->Execute(urls);
}
void OpenFileBrowserImpl(const base::FilePath& path,
TAB_REUSE_MODE mode,
const std::string& action_id) {
content::RecordAction(UserMetricsAction("ShowFileBrowserFullTab"));
if (FileManageTabExists(path, mode))
return;
Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
if (IsFileManagerPackaged() && !path.value().empty()) {
GURL url;
if (!ConvertFileToFileSystemUrl(profile, path, kFileBrowserDomain, &url))
return;
// Some values of |action_id| are not listed in the manifest and are used
// to parametrize the behavior when opening the Files app window.
ExecuteHandler(profile, kFileBrowserDomain, action_id, url);
return;
}
std::string url = chrome::kChromeUIFileManagerURL;
if (action_id.size()) {
DictionaryValue arg_value;
arg_value.SetString("action", action_id);
std::string query;
base::JSONWriter::Write(&arg_value, &query);
url += "?" +
net::EscapeUrlEncodedData(query,
false); // Space to %20 instead of +.
}
if (!path.empty()) {
base::FilePath virtual_path;
if (!ConvertFileToRelativeFileSystemPath(profile, kFileBrowserDomain, path,
&virtual_path))
return;
url += "#/" +
net::EscapeUrlEncodedData(virtual_path.value(),
false); // Space to %20 instead of +.
}
ExtensionService* service =
extensions::ExtensionSystem::Get(profile)->extension_service();
if (!service)
return;
const extensions::Extension* extension =
service->GetExtensionById(kFileBrowserDomain, false);
if (!extension)
return;
chrome::AppLaunchParams params(profile, extension,
extension_misc::LAUNCH_WINDOW,
NEW_FOREGROUND_TAB);
params.override_url = GURL(url);
chrome::OpenApplication(params);
}
Browser* GetBrowserForUrl(GURL target_url) {
for (chrome::BrowserIterator it; !it.done(); it.Next()) {
Browser* browser = *it;
TabStripModel* tab_strip = browser->tab_strip_model();
for (int idx = 0; idx < tab_strip->count(); idx++) {
content::WebContents* web_contents = tab_strip->GetWebContentsAt(idx);
const GURL& url = web_contents->GetURL();
if (url == target_url)
return browser;
}
}
return NULL;
}
bool ExecuteDefaultHandler(Profile* profile, const base::FilePath& path) {
GURL url;
if (!ConvertFileToFileSystemUrl(profile, path, kFileBrowserDomain, &url))
return false;
const FileBrowserHandler* handler;
if (!file_handler_util::GetTaskForURLAndPath(profile, url, path, &handler))
return false;
std::string extension_id = handler->extension_id();
std::string action_id = handler->id();
Browser* browser = chrome::FindLastActiveWithProfile(profile,
chrome::HOST_DESKTOP_TYPE_ASH);
// If there is no browsers for the profile, bail out. Return true so warning
// about file type not being supported is not displayed.
if (!browser)
return true;
if (extension_id == kFileBrowserDomain) {
if (IsFileManagerPackaged()) {
if (action_id == kFileBrowserGalleryTaskId ||
action_id == kFileBrowserMountArchiveTaskId ||
action_id == kFileBrowserPlayTaskId ||
action_id == kFileBrowserWatchTaskId) {
ExecuteHandler(profile, extension_id, action_id, url);
return true;
}
return ExecuteBuiltinHandler(browser, path, action_id);
}
// Only two of the built-in File Browser tasks require opening the File
// Browser tab.
if (action_id == kFileBrowserGalleryTaskId ||
action_id == kFileBrowserMountArchiveTaskId) {
// Tab reuse currently does not work for these two tasks.
// |gallery| tries to put the file url into the tab url but it does not
// work on Chrome OS.
// |mount-archive| does not even try.
OpenFileBrowserImpl(path, REUSE_SAME_PATH, "");
return true;
}
return ExecuteBuiltinHandler(browser, path, action_id);
}
ExecuteHandler(profile, extension_id, action_id, url);
return true;
}
// Reads JSON from a Google Docs file and extracts a document url. When the file
// is not in GDoc format, returns a file URL for |file_path| as fallback.
GURL ReadUrlFromGDocOnBlockingPool(const base::FilePath& file_path) {
const int64 kMaxGDocSize = 4096;
int64 file_size = 0;
if (!file_util::GetFileSize(file_path, &file_size) ||
file_size > kMaxGDocSize) {
DLOG(INFO) << "File too large to be a GDoc file " << file_path.value();
return net::FilePathToFileURL(file_path);
}
JSONFileValueSerializer reader(file_path);
std::string error_message;
scoped_ptr<base::Value> root_value(reader.Deserialize(NULL, &error_message));
if (!root_value.get()) {
DLOG(INFO) << "Failed to parse " << file_path.value() << "as JSON."
<< " error = " << error_message;
return net::FilePathToFileURL(file_path);
}
base::DictionaryValue* dictionary_value = NULL;
std::string edit_url_string;
if (!root_value->GetAsDictionary(&dictionary_value) ||
!dictionary_value->GetString("url", &edit_url_string)) {
DLOG(INFO) << "Non GDoc JSON in " << file_path.value();
return net::FilePathToFileURL(file_path);
}
return GURL(edit_url_string);
}
// Used to implement ViewItem().
void ContinueViewItem(Profile* profile,
const base::FilePath& path,
base::PlatformFileError error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (error == base::PLATFORM_FILE_OK) {
// A directory exists at |path|. Open it with FileBrowser.
OpenFileBrowserImpl(path, REUSE_SAME_PATH, "open");
} else {
if (!ExecuteDefaultHandler(profile, path))
ShowWarningMessageBox(profile, path);
}
}
// Used to implement CheckIfDirectoryExists().
void CheckIfDirectoryExistsOnIOThread(
scoped_refptr<fileapi::FileSystemContext> file_system_context,
const GURL& url,
const fileapi::FileSystemOperation::StatusCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
fileapi::FileSystemURL file_system_url = file_system_context->CrackURL(url);
base::PlatformFileError error = base::PLATFORM_FILE_OK;
fileapi::FileSystemOperation* operation =
file_system_context->CreateFileSystemOperation(file_system_url, &error);
if (error != base::PLATFORM_FILE_OK) {
callback.Run(error);
return;
}
operation->DirectoryExists(file_system_url, callback);
}
// Checks if a directory exists at |url|.
void CheckIfDirectoryExists(
scoped_refptr<fileapi::FileSystemContext> file_system_context,
const GURL& url,
const fileapi::FileSystemOperation::StatusCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&CheckIfDirectoryExistsOnIOThread,
file_system_context,
url,
google_apis::CreateRelayCallback(callback)));
}
} // namespace
GURL GetFileBrowserExtensionUrl() {
return GURL(kFileBrowserExtensionUrl);
}
GURL GetFileBrowserUrl() {
return GURL(IsFileManagerNewUI() ? kBaseFileBrowserNewUIUrl :
kBaseFileBrowserUrl);
}
GURL GetMediaPlayerUrl() {
return GURL(kMediaPlayerUrl);
}
GURL GetVideoPlayerUrl(const GURL& source_url) {
return GURL(kVideoPlayerUrl + std::string("?") + source_url.spec());
}
bool ConvertFileToFileSystemUrl(Profile* profile,
const base::FilePath& full_file_path,
const std::string& extension_id,
GURL* url) {
GURL origin_url = Extension::GetBaseURLFromExtensionId(extension_id);
base::FilePath virtual_path;
if (!ConvertFileToRelativeFileSystemPath(profile, extension_id,
full_file_path, &virtual_path)) {
return false;
}
GURL base_url = fileapi::GetFileSystemRootURI(origin_url,
fileapi::kFileSystemTypeExternal);
*url = GURL(base_url.spec() +
net::EscapeUrlEncodedData(virtual_path.value(),
false)); // Space to %20 instead of +.
return true;
}
bool ConvertFileToRelativeFileSystemPath(
Profile* profile,
const std::string& extension_id,
const base::FilePath& full_file_path,
base::FilePath* virtual_path) {
ExtensionService* service =
extensions::ExtensionSystem::Get(profile)->extension_service();
// May be NULL during unit_tests.
if (!service)
return false;
// File browser APIs are ment to be used only from extension context, so the
// extension's site is the one in whose file system context the virtual path
// should be found.
GURL site = service->GetSiteForExtensionId(extension_id);
fileapi::ExternalFileSystemMountPointProvider* provider =
BrowserContext::GetStoragePartitionForSite(profile, site)->
GetFileSystemContext()->external_provider();
if (!provider)
return false;
// Find if this file path is managed by the external provider.
if (!provider->GetVirtualPath(full_file_path, virtual_path))
return false;
return true;
}
GURL GetFileBrowserUrlWithParams(
ui::SelectFileDialog::Type type,
const string16& title,
const base::FilePath& default_virtual_path,
const ui::SelectFileDialog::FileTypeInfo* file_types,
int file_type_index,
const base::FilePath::StringType& default_extension) {
DictionaryValue arg_value;
arg_value.SetString("type", GetDialogTypeAsString(type));
arg_value.SetString("title", title);
arg_value.SetString("defaultPath", default_virtual_path.value());
arg_value.SetString("defaultExtension", default_extension);
if (file_types) {
ListValue* types_list = new ListValue();
for (size_t i = 0; i < file_types->extensions.size(); ++i) {
ListValue* extensions_list = new ListValue();
for (size_t j = 0; j < file_types->extensions[i].size(); ++j) {
extensions_list->Append(
new base::StringValue(file_types->extensions[i][j]));
}
DictionaryValue* dict = new DictionaryValue();
dict->Set("extensions", extensions_list);
if (i < file_types->extension_description_overrides.size()) {
string16 desc = file_types->extension_description_overrides[i];
dict->SetString("description", desc);
}
// file_type_index is 1-based. 0 means no selection at all.
dict->SetBoolean("selected",
(static_cast<size_t>(file_type_index) == (i + 1)));
types_list->Set(i, dict);
}
arg_value.Set("typeList", types_list);
arg_value.SetBoolean("includeAllFiles", file_types->include_all_files);
}
// If the caller cannot handle Drive path, the file chooser dialog need to
// return resolved local native paths to the selected files.
arg_value.SetBoolean("shouldReturnLocalPath",
!file_types || !file_types->support_drive);
std::string json_args;
base::JSONWriter::Write(&arg_value, &json_args);
// kChromeUIFileManagerURL could not be used since query parameters are not
// supported for it.
std::string url = GetFileBrowserUrl().spec() + '?' +
net::EscapeUrlEncodedData(json_args,
false); // Space to %20 instead of +.
return GURL(url);
}
string16 GetTitleFromType(ui::SelectFileDialog::Type dialog_type) {
string16 title;
switch (dialog_type) {
case ui::SelectFileDialog::SELECT_NONE:
// Full page file manager doesn't need a title.
break;
case ui::SelectFileDialog::SELECT_FOLDER:
title = l10n_util::GetStringUTF16(
IDS_FILE_BROWSER_SELECT_FOLDER_TITLE);
break;
case ui::SelectFileDialog::SELECT_SAVEAS_FILE:
title = l10n_util::GetStringUTF16(
IDS_FILE_BROWSER_SELECT_SAVEAS_FILE_TITLE);
break;
case ui::SelectFileDialog::SELECT_OPEN_FILE:
title = l10n_util::GetStringUTF16(
IDS_FILE_BROWSER_SELECT_OPEN_FILE_TITLE);
break;
case ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE:
title = l10n_util::GetStringUTF16(
IDS_FILE_BROWSER_SELECT_OPEN_MULTI_FILE_TITLE);
break;
default:
NOTREACHED();
}
return title;
}
void ViewRemovableDrive(const base::FilePath& path) {
OpenFileBrowserImpl(path, REUSE_ANY_FILE_MANAGER, "auto-open");
}
void OpenNewWindow(Profile* profile, const GURL& url) {
ExtensionService* service = extensions::ExtensionSystem::Get(
profile ? profile : ProfileManager::GetDefaultProfileOrOffTheRecord())->
extension_service();
if (!service)
return;
const extensions::Extension* extension =
service->GetExtensionById(kFileBrowserDomain, false);
if (!extension)
return;
chrome::AppLaunchParams params(profile, extension,
extension_misc::LAUNCH_WINDOW,
NEW_FOREGROUND_TAB);
params.override_url = url;
chrome::OpenApplication(params);
}
void OpenActionChoiceDialog(const base::FilePath& path, bool advanced_mode) {
const int kDialogWidth = 394;
// TODO(dgozman): remove 50, which is a title height once popup window
// will have no title.
const int kDialogHeight = 316 + 50;
Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
base::FilePath virtual_path;
if (!ConvertFileToRelativeFileSystemPath(profile, kFileBrowserDomain, path,
&virtual_path))
return;
std::string url = kActionChoiceUrl;
if (advanced_mode)
url += "?advanced-mode";
url += "#/" + net::EscapeUrlEncodedData(virtual_path.value(),
false); // Space to %20 instead of +.
GURL dialog_url(url);
const gfx::Size screen = ash::Shell::GetScreen()->GetPrimaryDisplay().size();
const gfx::Rect bounds((screen.width() - kDialogWidth) / 2,
(screen.height() - kDialogHeight) / 2,
kDialogWidth,
kDialogHeight);
Browser* browser = GetBrowserForUrl(dialog_url);
if (browser) {
browser->window()->Show();
return;
}
ExtensionService* service = extensions::ExtensionSystem::Get(
profile ? profile : ProfileManager::GetDefaultProfileOrOffTheRecord())->
extension_service();
if (!service)
return;
const extensions::Extension* extension =
service->GetExtensionById(kFileBrowserDomain, false);
if (!extension)
return;
chrome::AppLaunchParams params(profile, extension,
extension_misc::LAUNCH_WINDOW,
NEW_FOREGROUND_TAB);
params.override_url = dialog_url;
params.override_bounds = bounds;
chrome::OpenApplication(params);
}
void ViewItem(const base::FilePath& path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
GURL url;
if (!ConvertFileToFileSystemUrl(profile, path, kFileBrowserDomain, &url) ||
!GrantFileSystemAccessToFileBrowser(profile)) {
ShowWarningMessageBox(profile, path);
return;
}
GURL site = extensions::ExtensionSystem::Get(profile)->extension_service()->
GetSiteForExtensionId(kFileBrowserDomain);
scoped_refptr<fileapi::FileSystemContext> file_system_context =
BrowserContext::GetStoragePartitionForSite(profile, site)->
GetFileSystemContext();
CheckIfDirectoryExists(file_system_context, url,
base::Bind(&ContinueViewItem, profile, path));
}
void ShowFileInFolder(const base::FilePath& path) {
// This action changes the selection so we do not reuse existing tabs.
OpenFileBrowserImpl(path, REUSE_NEVER, "select");
}
void OpenFileBrowser() {
OpenFileBrowserImpl(base::FilePath(), REUSE_NEVER, "");
}
bool ExecuteBuiltinHandler(Browser* browser, const base::FilePath& path,
const std::string& internal_task_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
Profile* profile = browser->profile();
std::string file_extension = path.Extension();
// For things supported natively by the browser, we should open it
// in a tab.
if (IsSupportedBrowserExtension(file_extension.data()) ||
ShouldBeOpenedWithPlugin(profile, file_extension.data())) {
GURL page_url = net::FilePathToFileURL(path);
// Override drive resource to point to internal handler instead of file URL.
if (drive::util::IsUnderDriveMountPoint(path)) {
page_url = drive::util::FilePathToDriveURL(
drive::util::ExtractDrivePath(path));
}
OpenNewTab(profile, page_url);
return true;
}
if (IsSupportedGDocsExtension(file_extension.data())) {
if (drive::util::IsUnderDriveMountPoint(path)) {
// The file is on Google Docs. Open with drive URL.
GURL url = drive::util::FilePathToDriveURL(
drive::util::ExtractDrivePath(path));
OpenNewTab(profile, url);
} else {
// The file is local (downloaded from an attachment or otherwise copied).
// Parse the file to extract the Docs url and open this url.
base::PostTaskAndReplyWithResult(
BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&ReadUrlFromGDocOnBlockingPool, path),
base::Bind(&OpenNewTab, static_cast<Profile*>(NULL)));
}
return true;
}
if (!IsFileManagerPackaged()) {
if (internal_task_id == kFileBrowserPlayTaskId) {
GURL url;
if (!ConvertFileToFileSystemUrl(profile, path, kFileBrowserDomain, &url))
return false;
MediaPlayer* mediaplayer = MediaPlayer::GetInstance();
mediaplayer->PopupMediaPlayer();
mediaplayer->ForcePlayMediaURL(url);
return true;
}
if (internal_task_id == kFileBrowserWatchTaskId) {
GURL url;
if (!ConvertFileToFileSystemUrl(profile, path, kFileBrowserDomain, &url))
return false;
ExtensionService* service =
extensions::ExtensionSystem::Get(profile)->extension_service();
if (!service)
return false;
const extensions::Extension* extension =
service->GetExtensionById(kFileBrowserDomain, false);
if (!extension)
return false;
chrome::AppLaunchParams params(profile, extension,
extension_misc::LAUNCH_WINDOW,
NEW_FOREGROUND_TAB);
params.override_url = GetVideoPlayerUrl(url);
chrome::OpenApplication(params);
return true;
}
}
if (IsCRXFile(file_extension.data())) {
if (drive::util::IsUnderDriveMountPoint(path)) {
drive::DriveSystemService* system_service =
drive::DriveSystemServiceFactory::GetForProfile(profile);
if (!system_service)
return false;
system_service->file_system()->GetFileByPath(
drive::util::ExtractDrivePath(path),
base::Bind(&OnCRXDownloadCallback, browser));
} else {
InstallCRX(browser, path);
}
return true;
}
// Unknown file type. Record UMA and show an error message.
size_t extension_index = UMAExtensionIndex(file_extension.data(),
kUMATrackingExtensions,
arraysize(kUMATrackingExtensions));
UMA_HISTOGRAM_ENUMERATION("FileBrowser.OpeningFileType",
extension_index,
arraysize(kUMATrackingExtensions) - 1);
return false;
}
// If a bundled plugin is enabled, we should open pdf/swf files in a tab.
bool ShouldBeOpenedWithPlugin(Profile* profile, const char* file_extension) {
if (LowerCaseEqualsASCII(file_extension, kPdfExtension))
return IsPdfPluginEnabled(profile);
if (LowerCaseEqualsASCII(file_extension, kSwfExtension))
return IsFlashPluginEnabled(profile);
return false;
}
ListValue* ProgressStatusVectorToListValue(
Profile* profile,
const std::string& extension_id,
const google_apis::OperationProgressStatusList& list) {
scoped_ptr<ListValue> result_list(new ListValue());
for (google_apis::OperationProgressStatusList::const_iterator iter =
list.begin();
iter != list.end(); ++iter) {
result_list->Append(
ProgessStatusToDictionaryValue(profile, extension_id, *iter));
}
return result_list.release();
}
} // namespace file_manager_util
|