forked from adobe/brackets-shell
-
Notifications
You must be signed in to change notification settings - Fork 6
/
appshell_extensions_mac.mm
1968 lines (1624 loc) · 63.7 KB
/
appshell_extensions_mac.mm
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include "appshell_extensions_platform.h"
#include "appshell/appshell_helpers.h"
#include "native_menu_model.h"
#include "GoogleChrome.h"
#include <Cocoa/Cocoa.h>
#include <sys/sysctl.h>
#include <sstream>
#include <unicode/ucsdet.h>
#include <unicode/ucnv.h>
#include <fstream>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <ifaddrs.h>
#include <net/if_types.h>
#include <sys/resource.h>
#include <sys/utsname.h>
#include <mach-o/arch.h>
#define UTF8_BOM "\xEF\xBB\xBF"
NSMutableArray* pendingOpenFiles;
@interface ChromeWindowsTerminatedObserver : NSObject
- (void)appTerminated:(NSNotification *)note;
- (void)timeoutTimer:(NSTimer*)timer;
@end
// LiveBrowser helper functions
NSRunningApplication* GetLiveBrowserApp(NSString *bundleId, int debugPort);
// App ID for either Chrome or Chrome Canary (commented out)
NSString *const appId = @"com.google.Chrome";
//NSString *const appId = @"com.google.Chrome.canary";
// Live Development browser debug paramaters
int const debugPort = 9222;
NSString* debugPortCommandlineArguments = [NSString stringWithFormat:@"--remote-debugging-port=%d", debugPort];
NSString* debugProfilePath = [NSString stringWithFormat:@"--user-data-dir=%s/live-dev-profile", appshell::AppGetSupportDirectory().ToString().c_str()];
///////////////////////////////////////////////////////////////////////////////
// LiveBrowserMgrMac
class LiveBrowserMgrMac
{
public:
static LiveBrowserMgrMac* GetInstance();
static void Shutdown();
bool IsChromeRunning();
void CheckForChromeRunning();
void CheckForChromeRunningTimeout();
void SetWorkspaceNotifications();
void RemoveWorkspaceNotifications();
void CloseLiveBrowserKillTimers();
void CloseLiveBrowserFireCallback(int valToSend);
ChromeWindowsTerminatedObserver* GetTerminateObserver() { return m_chromeTerminateObserver; }
CefRefPtr<CefProcessMessage> GetCloseCallback() { return m_closeLiveBrowserCallback; }
NSRunningApplication* GetLiveBrowser() { return GetLiveBrowserApp(appId, debugPort); }
int GetLiveBrowserPid() { return m_liveBrowserPid; }
void SetCloseTimeoutTimer(NSTimer* closeLiveBrowserTimeoutTimer)
{ m_closeLiveBrowserTimeoutTimer = closeLiveBrowserTimeoutTimer; }
void SetTerminateObserver(ChromeWindowsTerminatedObserver* chromeTerminateObserver)
{ m_chromeTerminateObserver = chromeTerminateObserver; }
void SetCloseCallback(CefRefPtr<CefProcessMessage> response)
{ m_closeLiveBrowserCallback = response; }
void SetBrowser(CefRefPtr<CefBrowser> browser)
{ m_browser = browser; }
void SetLiveBrowserPid(int pid)
{ m_liveBrowserPid = pid; }
private:
// private so this class cannot be instantiated externally
LiveBrowserMgrMac();
virtual ~LiveBrowserMgrMac();
NSTimer* m_closeLiveBrowserTimeoutTimer;
CefRefPtr<CefProcessMessage> m_closeLiveBrowserCallback;
CefRefPtr<CefBrowser> m_browser;
ChromeWindowsTerminatedObserver* m_chromeTerminateObserver;
int m_liveBrowserPid;
static LiveBrowserMgrMac* s_instance;
};
LiveBrowserMgrMac::LiveBrowserMgrMac()
: m_closeLiveBrowserTimeoutTimer(nil)
, m_chromeTerminateObserver(nil)
, m_liveBrowserPid(ERR_PID_NOT_FOUND)
{
}
LiveBrowserMgrMac::~LiveBrowserMgrMac()
{
if (s_instance)
s_instance->CloseLiveBrowserKillTimers();
RemoveWorkspaceNotifications();
}
LiveBrowserMgrMac* LiveBrowserMgrMac::GetInstance()
{
if (!s_instance)
s_instance = new LiveBrowserMgrMac();
return s_instance;
}
void LiveBrowserMgrMac::Shutdown()
{
delete s_instance;
s_instance = NULL;
}
bool LiveBrowserMgrMac::IsChromeRunning()
{
return GetLiveBrowser() ? true : false;
}
void LiveBrowserMgrMac::CloseLiveBrowserKillTimers()
{
if (m_closeLiveBrowserTimeoutTimer) {
[m_closeLiveBrowserTimeoutTimer invalidate];
[m_closeLiveBrowserTimeoutTimer release];
m_closeLiveBrowserTimeoutTimer = nil;
}
}
void LiveBrowserMgrMac::CloseLiveBrowserFireCallback(int valToSend)
{
// kill the timers
CloseLiveBrowserKillTimers();
// Stop listening for ws shutdown notifications
RemoveWorkspaceNotifications();
// Prepare response
if (m_closeLiveBrowserCallback && m_browser) {
CefRefPtr<CefListValue> responseArgs = m_closeLiveBrowserCallback->GetArgumentList();
// Set common response args (callbackId and error)
responseArgs->SetInt(1, valToSend);
// Send response
m_browser->SendProcessMessage(PID_RENDERER, m_closeLiveBrowserCallback);
}
// Clear state
m_closeLiveBrowserCallback = NULL;
m_browser = NULL;
}
void LiveBrowserMgrMac::CheckForChromeRunning()
{
if (IsChromeRunning())
return;
// Unset the LiveBrowser pid
m_liveBrowserPid = ERR_PID_NOT_FOUND;
// Fire callback to browser
CloseLiveBrowserFireCallback(NO_ERROR);
}
void LiveBrowserMgrMac::CheckForChromeRunningTimeout()
{
int retVal = (IsChromeRunning() ? ERR_UNKNOWN : NO_ERROR);
//notify back to the app
CloseLiveBrowserFireCallback(retVal);
}
void LiveBrowserMgrMac::SetWorkspaceNotifications()
{
if (!GetTerminateObserver()) {
//register an observer to watch for the app terminations
SetTerminateObserver([[ChromeWindowsTerminatedObserver alloc] init]);
[[[NSWorkspace sharedWorkspace] notificationCenter]
addObserver:GetTerminateObserver()
selector:@selector(appTerminated:)
name:NSWorkspaceDidTerminateApplicationNotification
object:nil
];
}
}
void LiveBrowserMgrMac::RemoveWorkspaceNotifications()
{
if (m_chromeTerminateObserver) {
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:m_chromeTerminateObserver];
[m_chromeTerminateObserver release];
m_chromeTerminateObserver = nil;
}
}
LiveBrowserMgrMac* LiveBrowserMgrMac::s_instance = NULL;
// Forward declarations for functions defined later in this file
void NSArrayToCefList(NSArray* array, CefRefPtr<CefListValue>& list);
int32 ConvertNSErrorCode(NSError* error, bool isReading);
GoogleChromeApplication* GetGoogleChromeApplicationWithPid(int PID)
{
try {
// Ensure we have a valid process id before invoking ScriptingBridge.
// We need this because negative pids (e.g ERR_PID_NOT_FOUND) will not
// throw an exception, but rather will return a non-nil junk object
// that causes Brackets to hang on close
GoogleChromeApplication* app = PID < 0 ? nil : [SBApplication applicationWithProcessIdentifier:PID];
// Second check before returning
return [app respondsToSelector:@selector(name)] && [app.name isEqualToString:@"Google Chrome"] ? app : nil;
}
catch (...) {
return nil;
}
}
int32 OpenLiveBrowser(ExtensionString argURL, bool enableRemoteDebugging)
{
LiveBrowserMgrMac* liveBrowserMgr = LiveBrowserMgrMac::GetInstance();
// Parse the arguments
NSString *urlString = [NSString stringWithUTF8String:argURL.c_str()];
// Find instances of the Browser
NSRunningApplication* liveBrowser = liveBrowserMgr->GetLiveBrowser();
// Get the corresponding chromeApp scriptable browser object
GoogleChromeApplication* chromeApp = !liveBrowser ? nil : GetGoogleChromeApplicationWithPid([liveBrowser processIdentifier]);
// Launch Browser
if (!chromeApp) {
NSURL* appURL = [[NSWorkspace sharedWorkspace] URLForApplicationWithBundleIdentifier:appId];
if( !appURL ) {
return ERR_NOT_FOUND; //Chrome not installed
}
// Create the configuration dictionary for launching with custom parameters.
NSArray *parameters = [NSArray arrayWithObjects:
@"--no-first-run",
@"--no-default-browser-check",
@"--disable-default-apps",
debugPortCommandlineArguments,
debugProfilePath,
@"--disk-cache-size=250000000",
urlString,
nil];
NSDictionary* appConfig = [NSDictionary dictionaryWithObject:parameters forKey:NSWorkspaceLaunchConfigurationArguments];
NSUInteger launchOptions = NSWorkspaceLaunchDefault | NSWorkspaceLaunchNewInstance;
liveBrowser = [[NSWorkspace sharedWorkspace] launchApplicationAtURL:appURL options:launchOptions configuration:appConfig error:nil];
if (!liveBrowser) {
return ERR_UNKNOWN;
}
liveBrowserMgr->SetLiveBrowserPid([liveBrowser processIdentifier]);
liveBrowserMgr->SetWorkspaceNotifications();
return NO_ERROR;
}
[liveBrowser activateWithOptions:NSApplicationActivateIgnoringOtherApps];
// Check for existing tab with url already loaded
for (GoogleChromeWindow* chromeWindow in [chromeApp windows]) {
for (GoogleChromeTab* tab in [chromeWindow tabs]) {
if ([tab.URL isEqualToString:urlString]) {
// Found and open tab with url already loaded
return NO_ERROR;
}
}
}
// Tell the Browser to load the url
GoogleChromeWindow* chromeWindow = [[chromeApp windows] objectAtIndex:0];
if (!chromeWindow || [[chromeWindow tabs] count] == 0) {
// Create new Window
GoogleChromeWindow* chromeWindow = [[[chromeApp classForScriptingClass:@"window"] alloc] init];
[[chromeApp windows] addObject:chromeWindow];
chromeWindow.activeTab.URL = urlString;
[chromeWindow release];
} else {
// Create new Tab
GoogleChromeTab* chromeTab = [[[chromeApp classForScriptingClass:@"tab"] alloc] initWithProperties:@{@"URL": urlString}];
[[chromeWindow tabs] addObject:chromeTab];
[chromeTab release];
}
return NO_ERROR;
}
void CloseLiveBrowser(CefRefPtr<CefBrowser> browser, CefRefPtr<CefProcessMessage> response)
{
LiveBrowserMgrMac* liveBrowserMgr = LiveBrowserMgrMac::GetInstance();
if (liveBrowserMgr->GetCloseCallback() != NULL) {
// We can only handle a single async callback at a time. If there is already one that hasn't fired then
// we kill it now and get ready for the next.
liveBrowserMgr->CloseLiveBrowserFireCallback(ERR_UNKNOWN);
}
// Set up new Brackets CloseLiveBrowser callbacks
liveBrowserMgr->SetBrowser(browser);
liveBrowserMgr->SetCloseCallback(response);
// Get the currently active LiveBrowser session
NSRunningApplication* liveBrowser = liveBrowserMgr->GetLiveBrowser();
if (!liveBrowser) {
// No active LiveBrowser found
liveBrowserMgr->CloseLiveBrowserFireCallback(NO_ERROR);
return;
}
GoogleChromeApplication* chromeApp = GetGoogleChromeApplicationWithPid([liveBrowser processIdentifier]);
if (!chromeApp) {
// No corresponding scriptable browser object found
liveBrowserMgr->CloseLiveBrowserFireCallback(NO_ERROR);
return;
}
// Technically at this point we would locate the LiveBrowser window and
// close all tabs; however, the LiveDocument tab was already closed by Inspector!
// and there is no way to find which window to close.
// Do not close other windows
if ([[chromeApp windows] count] > 0 || [[[[chromeApp windows] objectAtIndex:0] tabs] count] > 0) {
liveBrowserMgr->CloseLiveBrowserFireCallback(NO_ERROR);
return;
}
// Set up workspace shutdown notifications
liveBrowserMgr->SetLiveBrowserPid([liveBrowser processIdentifier]);
liveBrowserMgr->SetWorkspaceNotifications();
// No more open windows found, so quit Chrome
[chromeApp quit];
// Set timeout timer
liveBrowserMgr->SetCloseTimeoutTimer([[NSTimer
scheduledTimerWithTimeInterval:(3 * 60)
target:liveBrowserMgr->GetTerminateObserver()
selector:@selector(timeoutTimer:)
userInfo:nil repeats:NO] retain]
);
}
int32 getSystemDefaultApp(const ExtensionString& fileTypes, ExtensionString& fileTypesWithdefaultApp)
{
char delim[] = ",";
char separator[] = "##";
std::vector<ExtensionString> extArray;
char* token = std::strtok((char*)fileTypes.c_str(), delim);
while (token) {
extArray.push_back(token);
token = std::strtok(NULL, delim);
}
for (std::vector<ExtensionString>::const_iterator it = extArray.begin(); it != extArray.end(); ++it)
{
ExtensionString appPath;
CFStringRef contentType = CFStringCreateWithCString (NULL, (*it).c_str(), kCFStringEncodingUTF8);
if(!contentType)
continue;
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
contentType,
NULL);
if(UTI)
{
CFURLRef bundle_id;
bundle_id = LSCopyDefaultApplicationURLForContentType(UTI, kLSRolesEditor, NULL);
if(bundle_id)
{
NSBundle *bundle = [NSBundle bundleWithURL: (NSURL*)bundle_id];
if (bundle)
{
appPath = [(NSString *)[bundle objectForInfoDictionaryKey: @"CFBundleExecutable"] cStringUsingEncoding:NSUTF8StringEncoding];
}
fileTypesWithdefaultApp = fileTypesWithdefaultApp + *it + separator + appPath + ",";
CFRelease(bundle_id);
}
CFRelease(UTI);
}
CFRelease(contentType);
}
return NO_ERROR;
}
int32 OpenURLInDefaultBrowser(ExtensionString url)
{
NSString* urlString = [NSString stringWithUTF8String:url.c_str()];
if ([[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString: urlString]] == NO) {
return ERR_UNKNOWN;
}
return NO_ERROR;
}
void ShowOpenDialog(bool allowMulitpleSelection,
bool chooseDirectory,
ExtensionString title,
ExtensionString initialDirectory,
ExtensionString fileTypes,
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefProcessMessage> response)
{
NSArray* allowedFileTypes = nil;
BOOL canChooseDirectories = chooseDirectory;
BOOL canChooseFiles = !canChooseDirectories;
if (fileTypes != "")
{
// fileTypes is a Space-delimited string
allowedFileTypes =
[[NSString stringWithUTF8String:fileTypes.c_str()]
componentsSeparatedByString:@" "];
}
// Initialize the dialog
NSOpenPanel* openPanel = [NSOpenPanel openPanel];
[openPanel setCanChooseFiles:canChooseFiles];
[openPanel setCanChooseDirectories:canChooseDirectories];
[openPanel setCanCreateDirectories:canChooseDirectories];
[openPanel setAllowsMultipleSelection:allowMulitpleSelection];
[openPanel setShowsHiddenFiles: YES];
[openPanel setTitle: [NSString stringWithUTF8String:title.c_str()]];
if (initialDirectory != "")
[openPanel setDirectoryURL:[NSURL URLWithString:[NSString stringWithUTF8String:initialDirectory.c_str()]]];
[openPanel setAllowedFileTypes:allowedFileTypes];
// cache the browser and response variables, so that these
// can be accessed from within the completionHandler block.
CefRefPtr<CefBrowser> _browser = browser;
CefRefPtr<CefProcessMessage> _response = response;
[openPanel beginSheetModalForWindow:[NSApp mainWindow] completionHandler: ^(NSInteger returnCode)
{
if(_browser && _response){
NSArray *urls = [openPanel URLs];
CefRefPtr<CefListValue> selectedFiles = CefListValue::Create();
if (returnCode == NSModalResponseOK){
for (NSUInteger i = 0; i < [urls count]; i++) {
selectedFiles->SetString(i, [[[urls objectAtIndex:i] path] UTF8String]);
}
}
// Set common response args (error and selectedfiles list)
_response->GetArgumentList()->SetInt(1, NO_ERROR);
_response->GetArgumentList()->SetList(2, selectedFiles);
_browser->SendProcessMessage(PID_RENDERER, _response);
}
}];
}
void ShowSaveDialog(ExtensionString title,
ExtensionString initialDirectory,
ExtensionString proposedNewFilename,
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefProcessMessage> response)
{
NSSavePanel* savePanel = [NSSavePanel savePanel];
[savePanel setTitle: [NSString stringWithUTF8String:title.c_str()]];
if (initialDirectory != "")
{
NSURL* initialDir = [NSURL fileURLWithPath:[NSString stringWithUTF8String:initialDirectory.c_str()]];
[savePanel setDirectoryURL:initialDir];
}
[savePanel setNameFieldStringValue:[NSString stringWithUTF8String:proposedNewFilename.c_str()]];
// cache the browser and response variables, so that these
// can be accessed from within the completionHandler block.
CefRefPtr<CefBrowser> _browser = browser;
CefRefPtr<CefProcessMessage> _response = response;
[savePanel beginSheetModalForWindow:[NSApp mainWindow] completionHandler: ^(NSInteger returnCode)
{
if(_response && _browser){
CefString pathStr;
if (returnCode == NSModalResponseOK){
NSURL* selectedFile = [savePanel URL];
if(selectedFile)
pathStr = [[selectedFile path] UTF8String];
}
// Set common response args (error and the new file name string)
_response->GetArgumentList()->SetInt(1, NO_ERROR);
_response->GetArgumentList()->SetString(2, pathStr);
_browser->SendProcessMessage(PID_RENDERER, _response);
}
}];
}
int32 IsNetworkDrive(ExtensionString path, bool& isRemote)
{
NSString* pathStr = [NSString stringWithUTF8String:path.c_str()];
isRemote = false;
if ([pathStr length] == 0) {
return ERR_INVALID_PARAMS;
}
// Detect remote drive
NSString *testPath = [[pathStr copy] autorelease];
NSNumber *isVolumeKey;
NSError *error = nil;
while (![testPath isEqualToString:@"/"]) {
NSURL *testUrl = [NSURL fileURLWithPath:testPath];
if (![testUrl getResourceValue:&isVolumeKey forKey:NSURLIsVolumeKey error:&error]) {
return ERR_NOT_FOUND;
}
if ([isVolumeKey boolValue]) {
isRemote = true;
break;
}
testPath = [testPath stringByDeletingLastPathComponent];
}
return NO_ERROR;
}
int32 ReadDir(ExtensionString path, CefRefPtr<CefListValue>& directoryContents)
{
NSString* pathStr = [NSString stringWithUTF8String:path.c_str()];
NSError* error = nil;
if ([pathStr length] == 0) {
return ERR_INVALID_PARAMS;
}
NSArray* contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathStr error:&error];
if (contents != nil)
{
NSArrayToCefList(contents, directoryContents);
return NO_ERROR;
}
return ConvertNSErrorCode(error, true);
}
int32 MakeDir(ExtensionString path, int32 mode)
{
NSError* error = nil;
NSString* pathStr = [NSString stringWithUTF8String:path.c_str()];
// TODO (issue #1759): honor mode
[[NSFileManager defaultManager] createDirectoryAtPath:pathStr withIntermediateDirectories:TRUE attributes:nil error:&error];
return ConvertNSErrorCode(error, false);
}
// perform a case insensitive filename comparison
int32 compareCaseInsensitive(std::string str1, std::string str2)
{
std::transform(str1.begin(), str1.end(), str1.begin(), toupper);
std::transform(str2.begin(), str2.end(), str2.begin(), toupper);
return str1.compare(str2);
}
int32 Rename(ExtensionString oldName, ExtensionString newName)
{
NSError* error = nil;
NSString* oldPathStr = [NSString stringWithUTF8String:oldName.c_str()];
NSString* newPathStr = [NSString stringWithUTF8String:newName.c_str()];
// check if the filename change is a case-only change
if (compareCaseInsensitive(oldName, newName) != 0) {
// Check to make sure newName doesn't already exist. On OS 10.7 and later, moveItemAtPath
// returns a nice "NSFileWriteFileExists" error in this case, but 10.6 returns a generic
// "can't write" error.
if ([[NSFileManager defaultManager] fileExistsAtPath:newPathStr]) {
return ERR_FILE_EXISTS;
}
[[NSFileManager defaultManager] moveItemAtPath:oldPathStr toPath:newPathStr error:&error];
} else {
// brackets issue #8127 - must rename case-only filename changes using an intermediate
// temp filename. Otherwise, NSFileManager -moveItemAtPath fails.
ExtensionString tmpName;
NSString* tmpPathStr = NULL;
// find an intermediate filename that doesn't already exist
int idx = 0;
std::ostringstream buff("");
do {
buff.str("");
buff << idx++;
tmpName = newName + "." + buff.str();
tmpPathStr = [NSString stringWithUTF8String:tmpName.c_str()];
} while ([[NSFileManager defaultManager] fileExistsAtPath:tmpPathStr]);
if ([[NSFileManager defaultManager] moveItemAtPath:oldPathStr toPath:tmpPathStr error:&error]) {
if (![[NSFileManager defaultManager] moveItemAtPath:tmpPathStr toPath:newPathStr error:&error]) {
// recover if can't move to final destination
[[NSFileManager defaultManager] moveItemAtPath:tmpPathStr toPath:oldPathStr error:&error];
}
}
}
return ConvertNSErrorCode(error, false);
}
int32 GetFileInfo(ExtensionString filename, uint32& modtime, bool& isDir, double& size, ExtensionString& realPath)
{
NSString* path = [NSString stringWithUTF8String:filename.c_str()];
BOOL isDirectory;
// Strip trailing "/"
if ([path hasSuffix:@"/"] && [path length] > 1) {
path = [path substringToIndex:[path length] - 1];
}
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory]) {
isDir = isDirectory;
} else {
return ERR_NOT_FOUND;
}
NSError* error = nil;
NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error];
// If path is a symlink, resolve it here and get the attributes at the
// resolved path
if ([[fileAttribs fileType] isEqualToString:NSFileTypeSymbolicLink]) {
NSString* realPathStr = [path stringByResolvingSymlinksInPath];
realPath = [realPathStr UTF8String];
fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:realPathStr error:&error];
} else {
realPath = "";
}
NSDate *modDate = [fileAttribs valueForKey:NSFileModificationDate];
modtime = [modDate timeIntervalSince1970];
NSNumber *filesize = [fileAttribs valueForKey:NSFileSize];
size = [filesize doubleValue];
return ConvertNSErrorCode(error, true);
}
int32 ReadFile(ExtensionString filename, ExtensionString& encoding, std::string& contents, bool& preserveBOM)
{
if (encoding == "utf8") {
encoding = "UTF-8";
}
NSString* path = [NSString stringWithUTF8String:filename.c_str()];
NSStringEncoding enc;
int32 error = NO_ERROR;
NSString* fileContents = nil;
if (encoding == "UTF-8") {
enc = NSUTF8StringEncoding;
NSError* NSerror = nil;
fileContents = [NSString stringWithContentsOfFile:path encoding:enc error:&NSerror];
}
if (fileContents)
{
contents = [fileContents UTF8String];
// We check if the file contains BOM or not
// if yes, then we set preserveBOM to true
// Please note we try to read first 3 characters
// again to check for BOM
CheckForUTF8BOM(filename, preserveBOM);
return NO_ERROR;
} else {
try {
std::ifstream file(filename.c_str());
std::stringstream ss;
ss << file.rdbuf();
contents = ss.str();
std::string detectedCharSet;
try {
if (encoding == "UTF-8") {
CharSetDetect ICUDetector;
ICUDetector(contents.c_str(), contents.size(), detectedCharSet);
}
else {
detectedCharSet = encoding;
}
if (detectedCharSet == "UTF-16LE" || detectedCharSet == "UTF-16BE") {
return ERR_UNSUPPORTED_UTF16_ENCODING;
}
if (!detectedCharSet.empty()) {
std::transform(detectedCharSet.begin(), detectedCharSet.end(), detectedCharSet.begin(), ::toupper);
DecodeContents(contents, detectedCharSet);
encoding = detectedCharSet;
}
else {
error = ERR_UNSUPPORTED_ENCODING;
}
} catch (...) {
error = ERR_UNSUPPORTED_ENCODING;
}
} catch (...) {
error = ERR_CANT_READ;
}
}
return error;}
int32 WriteFile(ExtensionString filename, std::string contents, ExtensionString encoding, bool preserveBOM)
{
const char *filenameStr = filename.c_str();
int32 error = NO_ERROR;
if (encoding == "utf8") {
encoding = "UTF-8";
}
if (encoding != "UTF-8") {
try {
CharSetEncode ICUEncoder(encoding);
ICUEncoder(contents);
} catch (...) {
error = ERR_ENCODE_FILE_FAILED;
}
} else if (encoding == "UTF-8" && preserveBOM) {
// The file originally contained BOM chars
// so we prepend BOM chars
contents = UTF8_BOM + contents;
}
try {
std::ofstream file;
file.open (filenameStr);
file << contents;
if (file.fail()) {
error = ERR_CANT_WRITE;
}
file.close();
} catch (...) {
return ERR_CANT_WRITE;
}
return error;
}
int32 SetPosixPermissions(ExtensionString filename, int32 mode)
{
NSError* error = nil;
NSString* path = [NSString stringWithUTF8String:filename.c_str()];
NSDictionary* attrs = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:mode] forKey:NSFilePosixPermissions];
if ([[NSFileManager defaultManager] setAttributes:attrs ofItemAtPath:path error:&error])
return NO_ERROR;
return ConvertNSErrorCode(error, false);
}
int32 DeleteFileOrDirectory(ExtensionString filename)
{
NSError* error = nil;
NSString* path = [NSString stringWithUTF8String:filename.c_str()];
// Make sure it exists
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
return ERR_NOT_FOUND;
}
if ([[NSFileManager defaultManager] removeItemAtPath:path error:&error])
return NO_ERROR;
return ConvertNSErrorCode(error, false);
}
void MoveFileOrDirectoryToTrash(ExtensionString filename, CefRefPtr<CefBrowser> browser, CefRefPtr<CefProcessMessage> response)
{
NSString* pathStr = [NSString stringWithUTF8String:filename.c_str()];
NSURL* fileUrl = [NSURL fileURLWithPath: pathStr];
static CefRefPtr<CefProcessMessage> s_response;
static CefRefPtr<CefBrowser> s_browser;
if (s_response) {
// Already a pending request. This will only happen if MoveFileOrDirectoryToTrash is called
// before the previous call has completed, which is not very likely.
response->GetArgumentList()->SetInt(1, ERR_UNKNOWN);
browser->SendProcessMessage(PID_RENDERER, response);
return;
}
s_browser = browser;
s_response = response;
[[NSWorkspace sharedWorkspace] recycleURLs:[NSArray arrayWithObject:fileUrl] completionHandler:^(NSDictionary *newURLs, NSError *error) {
// Invoke callback
s_response->GetArgumentList()->SetInt(1, ConvertNSErrorCode(error, false));
s_browser->SendProcessMessage(PID_RENDERER, s_response);
s_response = nil;
s_browser = nil;
}];
}
int32 CopyFile(ExtensionString src, ExtensionString dest)
{
NSError* error = nil;
NSString* source = [NSString stringWithUTF8String:src.c_str()];
NSString* destination = [NSString stringWithUTF8String:dest.c_str()];
if ( [[NSFileManager defaultManager] isReadableFileAtPath:source] ) {
if ( [[NSFileManager defaultManager] isReadableFileAtPath:destination] )
[[NSFileManager defaultManager] removeItemAtPath:destination error:&error];
[[NSFileManager defaultManager] copyItemAtPath:source toPath:destination error:&error];
return ConvertNSErrorCode(error, false);
}
return ERR_NOT_FOUND;
}
void NSArrayToCefList(NSArray* array, CefRefPtr<CefListValue>& list)
{
for (NSUInteger i = 0; i < [array count]; i++) {
list->SetString(i, [[[array objectAtIndex:i] precomposedStringWithCanonicalMapping] UTF8String]);
}
}
int32 ConvertNSErrorCode(NSError* error, bool isReading)
{
if (!error)
return NO_ERROR;
if( [[error domain] isEqualToString: NSPOSIXErrorDomain] )
{
switch ([error code])
{
case ENOENT:
return ERR_NOT_FOUND;
break;
case EPERM:
case EACCES:
return (isReading ? ERR_CANT_READ : ERR_CANT_WRITE);
break;
case EROFS:
return ERR_CANT_WRITE;
break;
case ENOSPC:
return ERR_OUT_OF_SPACE;
break;
}
}
switch ([error code])
{
case NSFileNoSuchFileError:
case NSFileReadNoSuchFileError:
return ERR_NOT_FOUND;
break;
case NSFileReadNoPermissionError:
return ERR_CANT_READ;
break;
case NSFileReadInapplicableStringEncodingError:
return ERR_UNSUPPORTED_ENCODING;
break;
case NSFileWriteNoPermissionError:
return ERR_CANT_WRITE;
break;
case NSFileWriteOutOfSpaceError:
return ERR_OUT_OF_SPACE;
break;
case NSFileWriteFileExistsError:
return ERR_FILE_EXISTS;
break;
}
// Unknown error
return ERR_UNKNOWN;
}
void OnBeforeShutdown()
{
LiveBrowserMgrMac::Shutdown();
}
void CloseWindow(CefRefPtr<CefBrowser> browser)
{
NSWindow* window = [browser->GetHost()->GetWindowHandle() window];
// Tell the window delegate it's really time to close
[[window delegate] performSelector:@selector(setIsReallyClosing)];
browser->GetHost()->CloseBrowser(true);
[window close];
}
void BringBrowserWindowToFront(CefRefPtr<CefBrowser> browser)
{
NSWindow* window = [browser->GetHost()->GetWindowHandle() window];
[window makeKeyAndOrderFront:nil];
}
@implementation ChromeWindowsTerminatedObserver
- (void) appTerminated:(NSNotification *)note
{
// Not Chrome? Not interested.
if ( ![[[note userInfo] objectForKey:@"NSApplicationBundleIdentifier"] isEqualToString:appId] ) {
return;
}
// Not LiveBrowser instance? Not interested.
if ( ![[[note userInfo] objectForKey:@"NSApplicationProcessIdentifier"] isEqualToNumber:[NSNumber numberWithInt:LiveBrowserMgrMac::GetInstance()->GetLiveBrowserPid()]] ) {
return;
}
LiveBrowserMgrMac::GetInstance()->CheckForChromeRunning();
}
- (void) timeoutTimer:(NSTimer*)timer
{
LiveBrowserMgrMac::GetInstance()->CheckForChromeRunningTimeout();
}
@end
int32 ShowFolderInOSWindow(ExtensionString pathname)
{
NSString *filepath = [NSString stringWithUTF8String:pathname.c_str()];
BOOL isDirectory;
if (![[NSFileManager defaultManager] fileExistsAtPath:filepath isDirectory:&isDirectory]) {
return ERR_NOT_FOUND;
}
if (isDirectory) {
[[NSWorkspace sharedWorkspace] openFile:filepath];