This repository was archived by the owner on Aug 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathdskmac.cpp
More file actions
6007 lines (5182 loc) · 194 KB
/
dskmac.cpp
File metadata and controls
6007 lines (5182 loc) · 194 KB
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) 2003-2015 LiveCode Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "osxprefix.h"
#include "osxprefix-legacy.h"
#include "parsedef.h"
#include "filedefs.h"
#include "globdefs.h"
#include "objdefs.h"
#include "exec.h"
#include "globals.h"
#include "system.h"
#include "osspec.h"
#include "mcerror.h"
#include "util.h"
#include "mcio.h"
#include "stack.h"
#include "handler.h"
#include "dispatch.h"
#include "card.h"
#include "group.h"
#include "button.h"
#include "param.h"
#include "mode.h"
#include "securemode.h"
#include "text.h"
#include "socket.h"
#include <sys/stat.h>
#include <sys/utsname.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/sysctl.h>
// SN-2014-12-09: [[ Bug 14001 ]] Update the module loading for Mac server
#include <dlfcn.h>
#include "foundation.h"
#include <Security/Authorization.h>
#include <Security/AuthorizationTags.h>
#include <mach-o/dyld.h>
#define ENTRIES_CHUNK 1024
#define SERIAL_PORT_BUFFER_SIZE 16384 //set new buffer size for serial input port
#include <termios.h>
#define B16600 16600
#include <pwd.h>
#include <inttypes.h>
#define USE_FSCATALOGINFO
///////////////////////////////////////////////////////////////////////////////
#define keyReplyErr 'errn'
#define keyMCScript 'mcsc' //reply from apple event
#define AETIMEOUT 60.0
uint1 *MClowercasingtable = NULL;
uint1 *MCuppercasingtable = NULL;
static bool GetProcessIsTranslated()
{
static int s_state = -1;
if (s_state == -1)
{
int ret = 0;
size_t size = sizeof(ret);
if (sysctlbyname("sysctl.proc_translated", &ret, &size, NULL, 0) == -1)
{
if (errno == ENOENT)
{
s_state = 0;
}
}
else
{
s_state = ret;
}
}
return s_state == 1;
}
inline FourCharCode FourCharCodeFromString(const char *p_string)
{
return MCSwapInt32HostToNetwork(*(FourCharCode *)p_string);
}
bool FourCharCodeFromString(MCStringRef p_string, uindex_t p_start, FourCharCode& r_four_char_code)
{
MCAutoStringRefAsCString t_temp;
uint32_t t_four_char_code;
if (!t_temp.Lock(p_string))
return false;
memcpy(&t_four_char_code, *t_temp + p_start, 4);
r_four_char_code = MCSwapInt32HostToNetwork(t_four_char_code);
return true;
}
inline char *FourCharCodeToString(FourCharCode p_code)
{
char *t_result;
t_result = new (nothrow) char[5];
*(FourCharCode *)t_result = MCSwapInt32NetworkToHost(p_code);
t_result[4] = '\0';
return t_result;
}
bool FourCharCodeToStringRef(FourCharCode p_code, MCStringRef& r_string)
{
return MCStringCreateWithCStringAndRelease(FourCharCodeToString(p_code), r_string);
}
struct triplets
{
AEEventClass theEventClass;
AEEventID theEventID;
AEEventHandlerProcPtr theHandler;
AEEventHandlerUPP theUPP;
};
typedef struct triplets triplets;
typedef struct
{
MCStringRef compname;
OSType compsubtype;
ComponentInstance compinstance;
}
OSAcomponent;
static OSAcomponent *osacomponents = NULL;
static uint2 osancomponents = 0;
#define MINIMUM_FAKE_PID (1 << 29)
static int4 curpid = MINIMUM_FAKE_PID;
static AEKeyword replykeyword; // Use in DoSpecial & other routines
static MCStringRef AEReplyMessage;
static MCStringRef AEAnswerData;
static MCStringRef AEAnswerErr;
static const AppleEvent *aePtr; //current apple event for mcs_request_ae()
/***************************************************************************
* utility functions used by this module only *
***************************************************************************/
static OSStatus getDescFromAddress(MCStringRef address, AEDesc *retDesc);
static OSStatus getDesc(short locKind, MCStringRef zone, MCStringRef machine, MCStringRef app, AEDesc *retDesc);
static OSStatus getAEAttributes(const AppleEvent *ae, AEKeyword key, MCStringRef &r_result);
static OSStatus getAEParams(const AppleEvent *ae, AEKeyword key, MCStringRef &r_result);
static OSStatus getAddressFromDesc(AEAddressDesc targetDesc, char *address);
static void getosacomponents();
static OSStatus osacompile(MCStringRef s, ComponentInstance compinstance, OSAID &id);
static OSStatus osaexecute(MCStringRef& r_string,ComponentInstance compinstance, OSAID id);
// SN-2014-10-07: [[ Bug 13587 ]] Update to return an MCList
static bool fetch_ae_as_fsref_list(MCListRef &r_list);
static OSStatus MCS_mac_pathtoref(MCStringRef p_path, FSRef& r_ref);
static bool MCS_mac_fsref_to_path(FSRef& p_ref, MCStringRef& r_path);
/***************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// SN-2014-08-07: [[ MERG-6.7 ]] Porting updates from osxspec.cpp
OSErr MCAppleEventHandlerDoSpecial(const AppleEvent *ae, AppleEvent *reply, long refCon)
{
// MW-2013-08-07: [[ Bug 10865 ]] If AppleScript is disabled (secureMode) then
// don't handle the event.
if (!MCSecureModeCanAccessAppleScript())
return errAEEventNotHandled;
OSErr err = errAEEventNotHandled; //class, id, sender
DescType rType;
Size rSize;
AEEventClass aeclass;
AEGetAttributePtr(ae, keyEventClassAttr, typeType, &rType, &aeclass, sizeof(AEEventClass), &rSize);
AEEventID aeid;
AEGetAttributePtr(ae, keyEventIDAttr, typeType, &rType, &aeid, sizeof(AEEventID), &rSize);
if (aeclass == kTextServiceClass)
{
err = errAEEventNotHandled;
return err;
}
//trap for the AEAnswer event, let DoAEAnswer() to handle this event
if (aeclass == kCoreEventClass)
{
if (aeid == kAEAnswer)
return errAEEventNotHandled;
}
AEAddressDesc senderDesc;
//
char *p3val = new (nothrow) char[128];
//char *p3val = new (nothrow) char[kNBPEntityBufferSize + 1]; //sender's address 105 + 1
if (AEGetAttributeDesc(ae, keyOriginalAddressAttr,
typeWildCard, &senderDesc) == noErr)
{
getAddressFromDesc(senderDesc, p3val);
AEDisposeDesc(&senderDesc);
}
else
p3val[0] = '\0';
aePtr = ae; //saving the current AE pointer for use in mcs_request_ae()
MCParameter p1, p2, p3;
MCAutoStringRef s1;
MCAutoStringRef s2;
MCAutoStringRef s3;
/* UNCHECKED */ FourCharCodeToStringRef(aeclass, &s1);
/* UNCHECKED */ MCStringCreateWithCString(p3val, &s3);
p1.setvalueref_argument(*s1);
p1.setnext(&p2);
/* UNCHECKED */ FourCharCodeToStringRef(aeid, &s2);
p2.setvalueref_argument(*s2);
p2.setnext(&p3);
p3.setvalueref_argument(*s3);
/*for "appleEvent class, id, sender" message to inform script that
there is an AE arrived */
Exec_stat stat = MCdefaultstackptr->getcard()->message(MCM_apple_event, &p1);
if (stat != ES_PASS && stat != ES_NOT_HANDLED)
{ //if AE is handled by MC
if (stat == ES_ERROR)
{ //error in handling AE in MC
err = errAECorruptData;
if (reply->dataHandle != NULL)
{
int16_t e = err;
AEPutParamPtr(reply, keyReplyErr, typeSInt16, (Ptr)&e, sizeof(short));
}
}
else
{ //ES_NORMAL
if (AEReplyMessage == NULL) //no reply, will return no error code
err = noErr;
else
{
if (reply->descriptorType != typeNull && reply->dataHandle != NULL)
{
MCAutoStringRefAsUTF8String t_reply;
/* UNCHECKED */ t_reply.Lock(AEReplyMessage);
err = AEPutParamPtr(reply, replykeyword, typeUTF8Text, *t_reply, t_reply.Size());
if (err != noErr)
{
int16_t e = err;
AEPutParamPtr(reply, keyReplyErr, typeSInt16, (Ptr)&e, sizeof(short));
}
}
}
MCValueRelease(AEReplyMessage);
AEReplyMessage = NULL;
}
}
else
if (aeclass == kAEMiscStandards
&& (aeid == kAEDoScript || aeid == 'eval'))
{
if ((err = AEGetParamPtr(aePtr, keyDirectObject, typeUTF8Text, &rType, NULL, 0, &rSize)) == noErr)
{
byte_t *sptr = new (nothrow) byte_t[rSize + 1];
AEGetParamPtr(aePtr, keyDirectObject, typeUTF8Text, &rType, sptr, rSize, &rSize);
MCExecContext ctxt(MCdefaultstackptr -> getcard(), nil, nil);
MCAutoStringRef t_sptr;
/* UNCHECKED */ MCStringCreateWithBytesAndRelease(sptr, rSize, kMCStringEncodingUTF8, false, &t_sptr);
if (aeid == kAEDoScript)
{
MCdefaultstackptr->getcard()->domess(*t_sptr);
MCAutoValueRef t_value;
MCAutoStringRef t_string;
MCAutoStringRefAsUTF8String t_utf8_string;
/* UNCHECKED */ MCresult->eval(ctxt, &t_value);
/* UNCHECKED */ ctxt . ConvertToString(*t_value, &t_string);
/* UNCHECKED */ t_utf8_string.Lock(*t_string);
AEPutParamPtr(reply, '----', typeUTF8Text, *t_utf8_string, t_utf8_string.Size());
}
else
{
MCAutoValueRef t_val;
MCAutoStringRef t_string;
MCAutoStringRefAsUTF8String t_utf8;
MCdefaultstackptr->getcard()->eval(ctxt, *t_sptr, &t_val);
/* UNCHECKED */ ctxt.ConvertToString(*t_val, &t_string);
/* UNCHECKED */ t_utf8.Lock(*t_string);
AEPutParamPtr(reply, '----', typeUTF8Text, *t_utf8, t_utf8.Size());
}
}
}
else
err = errAEEventNotHandled;
// do nothing if the AE is not handled,
// let the standard AE dispacher to dispatch this AE
delete[] p3val;
return err;
}
OSErr MCAppleEventHandlerDoOpenDoc(const AppleEvent *theAppleEvent, AppleEvent *reply, long refCon)
{ //Apple Event for opening documnets, in our use is to open stacks when user
//double clicked on a MC stack icon
// MW-2013-08-07: [[ Bug 10865 ]] If AppleScript is disabled (secureMode) then
// don't handle the event.
if (!MCSecureModeCanAccessAppleScript())
return errAEEventNotHandled;
AEDescList docList; //get a list of alias records for the documents
errno = AEGetParamDesc(theAppleEvent, keyDirectObject, typeAEList, &docList);
if (errno != noErr)
return errno;
long count;
//get the number of docs descriptors in the list
AECountItems(&docList, &count);
if (count < 1) //if there is no doc to be opened
return errno;
AEKeyword rKeyword; //returned keyword
DescType rType; //returned type
FSRef t_doc_fsref;
Size rSize; //returned size, atual size of the docName
long item;
// get a FSSpec record, starts from count==1
for (item = 1; item <= count; item++)
{
errno = AEGetNthPtr(&docList, item, typeFSRef, &rKeyword, &rType, &t_doc_fsref, sizeof(FSRef), &rSize);
if (errno != noErr)
return errno;
// extract FSSpec record's info & form a file name for MC to use
MCAutoStringRef t_full_path_name;
MCS_mac_fsref_to_path(t_doc_fsref, &t_full_path_name);
if (MCModeShouldQueueOpeningStacks())
{
MCU_realloc((char **)&MCstacknames, MCnstacks, MCnstacks + 1, sizeof(MCStringRef));
MCstacknames[MCnstacks++] = MCValueRetain(*t_full_path_name);
}
else
{
MCStack *stkptr; //stack pointer
if (MCdispatcher->loadfile(*t_full_path_name, stkptr) == IO_NORMAL)
stkptr->open();
}
}
AEDisposeDesc(&docList);
return noErr;
}
OSErr MCAppleEventHandlerDoAEAnswer(const AppleEvent *ae, AppleEvent *reply, long refCon)
{
// MW-2013-08-07: [[ Bug 10865 ]] If AppleScript is disabled (secureMode) then
// don't handle the event.
if (!MCSecureModeCanAccessAppleScript())
return errAEEventNotHandled;
//process the repy(answer) returned from a server app. When MCS_send() with
// a reply, the reply is handled in this routine.
// This is different from MCS_reply()
//check if there is an error code
DescType rType; //returned type
Size rSize;
/*If the handler returns a result code other than noErr, and if the
client is waiting for a reply, it is returned in the keyErrorNumber
parameter of the reply Apple event. */
if (AEGetParamPtr(ae, keyErrorString, typeUTF8Text, &rType, NULL, 0, &rSize) == noErr)
{
byte_t* t_utf8 = new (nothrow) byte_t[rSize + 1];
AEGetParamPtr(ae, keyErrorString, typeUTF8Text, &rType, t_utf8, rSize, &rSize);
/* UNCHECKED */ MCStringCreateWithBytesAndRelease(t_utf8, rSize, kMCStringEncodingUTF8, false, AEAnswerErr);
}
else
{
int16_t e;
if (AEGetParamPtr(ae, keyErrorNumber, typeSInt16, &rType, (Ptr)&e, sizeof(short), &rSize) == noErr
&& e != noErr)
{
/* UNCHECKED */ MCStringFormat(AEAnswerErr, "Got error %d when sending Apple event", e);
}
else
{
if (AEAnswerData != NULL)
{
MCValueRelease(AEAnswerData);
AEAnswerData = NULL;
}
if ((errno = AEGetParamPtr(ae, keyDirectObject, typeUTF8Text, &rType, NULL, 0, &rSize)) != noErr)
{
if (errno == errAEDescNotFound)
{
AEAnswerData = MCValueRetain(kMCEmptyString);
return noErr;
}
/* UNCHECKED */ MCStringFormat(AEAnswerErr, "Got error %d when receiving Apple event", errno);
return errno;
}
byte_t *t_utf8 = new (nothrow) byte_t[rSize + 1];
AEGetParamPtr(ae, keyDirectObject, typeUTF8Text, &rType, t_utf8, rSize, &rSize);
/* UNCHECKED */ MCStringCreateWithBytesAndRelease(t_utf8, rSize, kMCStringEncodingUTF8, false, AEAnswerData);
}
}
return noErr;
}
/// END HERE
///////////////////////////////////////////////////////////////////////////////
static void MCS_launch_set_result_from_lsstatus(void)
{
int t_error;
t_error = 0;
switch(errno)
{
case kLSUnknownErr:
case kLSNotAnApplicationErr:
case kLSLaunchInProgressErr:
case kLSServerCommunicationErr:
#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1040
case kLSAppInTrashErr:
case kLSIncompatibleSystemVersionErr:
case kLSNoLaunchPermissionErr:
case kLSNoExecutableErr:
case kLSNoClassicEnvironmentErr:
case kLSMultipleSessionsNotSupportedErr:
#endif
t_error = 2;
break;
case kLSDataUnavailableErr:
case kLSApplicationNotFoundErr:
case kLSDataErr:
t_error = 3;
break;
}
switch(t_error)
{
case 0:
MCresult -> clear();
break;
case 1:
MCresult -> sets("can't open file");
break;
case 2:
MCresult -> sets("request failed");
break;
case 3:
MCresult -> sets("no association");
break;
}
}
///////////////////////////////////////////////////////////////////////////////
IO_stat MCS_mac_shellread(int fd, char *&buffer, uint4 &buffersize, uint4 &size)
{
MCshellfd = fd;
size = 0;
while (True)
{
int readsize = 0;
ioctl(fd, FIONREAD, (char *)&readsize);
readsize += READ_PIPE_SIZE;
if (size + readsize > buffersize)
{
MCU_realloc((char **)&buffer, buffersize,
buffersize + readsize + 1, sizeof(char));
buffersize += readsize;
}
errno = 0;
int4 amount = read(fd, &buffer[size], readsize);
if (amount <= 0)
{
if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
break;
if (!MCS_poll(SHELL_INTERVAL, 0))
if (!MCnoui && MCscreen->wait(SHELL_INTERVAL, False, True))
{
MCshellfd = -1;
return IO_ERROR;
}
}
else
size += amount;
}
MCshellfd = -1;
return IO_NORMAL;
}
///////////////////////////////////////////////////////////////////////////////
// Special Folders
// MW-2012-10-10: [[ Bug 10453 ]] Added 'mactag' field which is the tag to use in FSFindFolder.
// This allows macfolder to be 0, which means don't alias the tag to the specified disk.
typedef struct
{
MCNameRef *token;
unsigned long macfolder;
OSType domain;
unsigned long mactag;
}
sysfolders;
// MW-2008-01-18: [[ Bug 5799 ]] It seems that we are requesting things in the
// wrong domain - particularly for 'temp'. See:
// http://lists.apple.com/archives/carbon-development/2003/Oct/msg00318.html
static sysfolders sysfolderlist[] = {
{&MCN_desktop, 'desk', OSType(kOnAppropriateDisk), 'desk'},
{&MCN_fonts,'font', OSType(kOnAppropriateDisk), 'font'},
{&MCN_preferences,'pref', OSType(kUserDomain), 'pref'},
{&MCN_temporary,'temp', OSType(kUserDomain), 'temp'},
{&MCN_system, 'macs', OSType(kOnAppropriateDisk), 'macs'},
// TS-2007-08-20: Added to allow a common notion of "home" between all platforms
{&MCN_home, 'cusr', OSType(kUserDomain), 'cusr'},
// MW-2007-09-11: Added for uniformity across platforms
{&MCN_documents, 'docs', OSType(kUserDomain), 'docs'},
// MW-2007-10-08: [[ Bug 10277 ] Add support for the 'application support' at user level.
// FG-2014-09-26: [[ Bug 13523 ]] This entry must not match a request for "asup"
{&MCN_support, 0, OSType(kUserDomain), 'asup'},
};
static bool MCS_mac_specialfolder_to_mac_folder(MCStringRef p_type, uint32_t& r_folder, OSType& r_domain)
{
for (uindex_t i = 0; i < ELEMENTS(sysfolderlist); i++)
{
if (MCStringIsEqualTo(p_type, MCNameGetString(*(sysfolderlist[i].token)), kMCStringOptionCompareCaseless))
{
r_folder = sysfolderlist[i].mactag;
r_domain = sysfolderlist[i].domain;
return true;
}
}
return false;
}
/********************************************************************/
/* Serial Handling */
/********************************************************************/
// Utilities
static void parseSerialControlStr(MCStringRef setting, struct termios *theTermios)
{
int baud = 0;
MCAutoStringRef t_property, t_value;
if (MCStringDivideAtChar(setting, '=', kMCCompareExact, &t_property, &t_value))
{
if (MCStringIsEqualToCString(*t_property, "baud", kMCCompareCaseless))
{
integer_t baudrate;
/* UNCHECKED */ MCStringToInteger(*t_value, baudrate);
baud = baudrate;
cfsetispeed(theTermios, baud);
cfsetospeed(theTermios, baud);
}
else if (MCStringIsEqualToCString(*t_property, "parity", kMCCompareCaseless))
{
char first;
first = MCStringGetNativeCharAtIndex(*t_value, 0);
if (first == 'N' || first == 'n')
theTermios->c_cflag &= ~(PARENB | PARODD);
else if (first == 'O' || first == 'o')
theTermios->c_cflag |= PARENB | PARODD;
else if (first == 'E' || first == 'e')
theTermios->c_cflag |= PARENB;
}
else if (MCStringIsEqualToCString(*t_property, "data", kMCCompareCaseless))
{
integer_t data;
/* UNCHECKED */ MCStringToInteger(*t_value, data);
switch (data)
{
case 5:
theTermios->c_cflag |= CS5;
break;
case 6:
theTermios->c_cflag |= CS6;
break;
case 7:
theTermios->c_cflag |= CS7;
break;
case 8:
theTermios->c_cflag |= CS8;
break;
}
}
else if (MCStringIsEqualToCString(*t_property, "stop", kMCCompareCaseless))
{
double stopbit;
/* UNCHECKED */ MCStringToDouble(*t_value, stopbit);
if (stopbit == 1.0)
theTermios->c_cflag &= ~CSTOPB;
else if (stopbit == 1.5)
theTermios->c_cflag &= ~CSTOPB;
else if (stopbit == 2.0)
theTermios->c_cflag |= CSTOPB;
}
}
}
static void configureSerialPort(int sRefNum)
{/****************************************************************************
*parse MCserialcontrolstring and set the serial output port to the settings*
*defined by MCserialcontrolstring accordingly *
****************************************************************************/
//initialize to the default setting
struct termios theTermios;
if (tcgetattr(sRefNum, &theTermios) < 0)
{
// TODO: handle error appropriately
}
cfsetispeed(&theTermios, B9600);
theTermios.c_cflag = CS8;
// Split the string on the spaces
MCAutoArrayRef t_settings;
/* UNCHECKED */ MCStringSplit(MCserialcontrolsettings, MCSTR(" "), nil, kMCCompareExact, &t_settings);
uindex_t nsettings = MCArrayGetCount(*t_settings);
for (int i = 0 ; i < nsettings ; i++)
{
// Note: 't_settings' is an array of strings
MCValueRef t_settingval = nil;
/* UNCHECKED */ MCArrayFetchValueAtIndex(*t_settings, i + 1, t_settingval);
MCStringRef t_setting = (MCStringRef)t_settingval;
parseSerialControlStr(t_setting, &theTermios);
}
//configure the serial output device
if (tcsetattr(sRefNum, TCSANOW, &theTermios) < 0)
{
// TODO: handle error appropriately
}
return;
}
///////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// REFACTORED FROM TEXT.CPP
//
struct UnicodeInfoRecord
{
UnicodeInfoRecord *next;
TextEncoding encoding;
TextToUnicodeInfo info;
};
static TextToUnicodeInfo fetch_unicode_info(TextEncoding p_encoding)
{
static UnicodeInfoRecord *s_records = NULL;
UnicodeInfoRecord *t_previous, *t_current;
for(t_previous = NULL, t_current = s_records; t_current != NULL; t_previous = t_current, t_current = t_current -> next)
if (t_current -> encoding == p_encoding)
break;
if (t_current == NULL)
{
UnicodeMapping t_mapping;
t_mapping . unicodeEncoding = CreateTextEncoding(kTextEncodingUnicodeDefault, kUnicodeNoSubset, kUnicode16BitFormat);
t_mapping . otherEncoding = CreateTextEncoding(p_encoding, kTextEncodingDefaultVariant, kTextEncodingDefaultFormat);
t_mapping . mappingVersion = kUnicodeUseLatestMapping;
TextToUnicodeInfo t_info;
OSErr t_err;
t_err = CreateTextToUnicodeInfo(&t_mapping, &t_info);
if (t_err != noErr)
t_info = NULL;
UnicodeInfoRecord *t_record;
t_record = new (nothrow) UnicodeInfoRecord;
t_record -> next = s_records;
t_record -> encoding = p_encoding;
t_record -> info = t_info;
s_records = t_record;
return t_record -> info;
}
if (t_previous != NULL)
{
t_previous -> next = t_current -> next;
t_current -> next = s_records;
s_records = t_current;
}
return s_records -> info;
}
///////////////////////////////////////////////////////////////////////////////
static void MCS_mac_setfiletype(MCStringRef p_new_path)
{
FSRef t_fsref;
// TODO Check whether the double path resolution is an issue
if (MCS_mac_pathtoref(p_new_path, t_fsref) != noErr)
return; // ignore errors
FSCatalogInfo t_catalog;
if (FSGetCatalogInfo(&t_fsref, kFSCatInfoFinderInfo, &t_catalog, NULL, NULL, NULL) == noErr)
{
// Set the creator and filetype of the catalog.
FourCharCodeFromString(MCfiletype, 4, ((FileInfo *) t_catalog . finderInfo) -> fileType);
FourCharCodeFromString(MCfiletype, 0, ((FileInfo *) t_catalog . finderInfo) -> fileCreator);
FSSetCatalogInfo(&t_fsref, kFSCatInfoFinderInfo, &t_catalog);
}
}
///////////////////////////////////////////////////////////////////////////////
extern "C"
{
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#include <IOKit/IOBSD.h>
void NSLog(CFStringRef format, ...);
void NSLogv(CFStringRef format, va_list args);
}
static kern_return_t FindSerialPortDevices(io_iterator_t *serialIterator, mach_port_t *masterPort)
{
kern_return_t kernResult;
CFMutableDictionaryRef classesToMatch;
if ((kernResult = IOMasterPort(0, masterPort)) != KERN_SUCCESS)
return kernResult;
if ((classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue)) == NULL)
return kernResult;
CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey),
CFSTR(kIOSerialBSDRS232Type));
//kIOSerialBSDRS232Type filters KeySpan USB modems use
//kIOSerialBSDModemType to get 'real' serial modems for OSX
//computers with real serial ports - if there are any!
kernResult = IOServiceGetMatchingServices(*masterPort, classesToMatch,
serialIterator);
return kernResult;
}
static void getIOKitProp(io_object_t sObj, const char *propName,
char *dest, uint2 destlen)
{
CFTypeRef nameCFstring;
dest[0] = 0;
nameCFstring = IORegistryEntryCreateCFProperty(sObj,
CFStringCreateWithCString(kCFAllocatorDefault, propName,
kCFStringEncodingASCII),
kCFAllocatorDefault, 0);
if (nameCFstring)
{
CFStringGetCString((CFStringRef)nameCFstring, (char *)dest, (long)destlen,
(unsigned long)kCFStringEncodingASCII);
CFRelease(nameCFstring);
}
}
///////////////////////////////////////////////////////////////////////////////
//for setting serial port use
typedef struct
{
short baudrate;
short parity;
short stop;
short data;
}
SerialControl;
//struct
SerialControl portconfig; //serial port configuration structure
extern "C"
{
extern UInt32 SwapQDTextFlags(UInt32 newFlags);
typedef UInt32 (*SwapQDTextFlagsPtr)(UInt32 newFlags);
}
static void configureSerialPort(int sRefNum);
static bool getResourceInfo(MCListRef p_list, ResType p_type);
static void parseSerialControlStr(MCStringRef set, struct termios *theTermios);
static UnicodeToTextInfo unicodeconvertors[32];
static TextToUnicodeInfo texttounicodeinfo;
static TextToUnicodeInfo *texttounicodeconvertor = NULL;
static UnicodeToTextInfo utf8totextinfo;
static TextToUnicodeInfo texttoutf8info;
///////////////////////////////////////////////////////////////////////////////
static void init_utf8_converters(void)
{
if (texttoutf8info != nil)
return;
memset(unicodeconvertors, 0, sizeof(unicodeconvertors));
UnicodeMapping ucmapping;
ucmapping.unicodeEncoding = CreateTextEncoding(kTextEncodingUnicodeDefault,
kTextEncodingDefaultVariant,
kUnicodeUTF8Format);
ucmapping.otherEncoding = kTextEncodingMacRoman;
ucmapping.mappingVersion = -1;
CreateTextToUnicodeInfo(&ucmapping, &texttoutf8info);
CreateUnicodeToTextInfo(&ucmapping, &utf8totextinfo);
}
///////////////////////////////////////////////////////////////////////////////
/********************************************************************/
/* File Handling */
/********************************************************************/
// File opening and closing
// This function checks that a file really does exist at the given location.
// The path is expected to have been resolved but in native encoding.
static bool MCS_file_exists_at_path(MCStringRef p_path)
{
MCAutoStringRefAsUTF8String t_new_path;
/* UNCHECKED */ t_new_path . Lock(p_path);
bool t_found;
struct stat buf;
t_found = (stat(*t_new_path, (struct stat *)&buf) == 0);
if (t_found)
if (S_ISDIR(buf . st_mode))
t_found = false;
return t_found;
}
// MW-2014-09-17: [[ Bug 13455 ]] Attempt to redirect path. If p_is_file is false,
// the path is taken to be a directory and is always redirected if is within
// Contents/MacOS. If p_is_file is true, then the file is only redirected if
// the original doesn't exist, and the redirection does.
bool MCS_apply_redirect(MCStringRef p_path, bool p_is_file, MCStringRef& r_redirected)
{
// If the original file exists, do nothing.
if (p_is_file && MCS_file_exists_at_path(p_path))
return false;
uindex_t t_engine_path_length;
if (!MCStringLastIndexOfChar(MCcmd, '/', UINDEX_MAX, kMCStringOptionCompareExact, t_engine_path_length))
t_engine_path_length = MCStringGetLength(MCcmd);
// If the length of the path is less than the folder prefix of the exe, it
// cannot be inside <bundle>/Contents/MacOS/
if (MCStringGetLength(p_path) < t_engine_path_length)
return false;
// If the prefix of path is not the same as MCcmd up to the folder, it
// cannot be inside <bundle>/Contents/MacOS/
if (!MCStringSubstringIsEqualToSubstring(p_path, MCRangeMake(0, t_engine_path_length), MCcmd, MCRangeMake(0, t_engine_path_length), kMCCompareCaseless))
return false;
// If the final component is not MacOS then it is not inside the relevant
// folder.
if (MCStringGetLength(p_path) != t_engine_path_length &&
MCStringGetCodepointAtIndex(p_path, t_engine_path_length) != '/')
return false;
// Construct the new path from the path after MacOS/ inside Resources/_macos.
MCAutoStringRef t_new_path;
MCRange t_cmd_range = MCRangeMake(0, t_engine_path_length - 6);
uindex_t t_path_end = MCStringGetLength(p_path);
bool t_success = true;
if (MCStringGetCodepointAtIndex(p_path, t_path_end) == '/')
t_path_end--;
if (t_engine_path_length == t_path_end)
{
t_success = MCStringFormat(&t_new_path, "%*@/Resources/_MacOS", &t_cmd_range, MCcmd);
}
else
{
MCRange t_path_range = MCRangeMakeMinMax(t_engine_path_length + 1, t_path_end);
// AL-2014-09-19: Range argument to MCStringFormat is a pointer to an MCRange.
t_success = MCStringFormat(&t_new_path, "%*@/Resources/_MacOS/%*@", &t_cmd_range, MCcmd, &t_path_range, p_path);
}
if (!t_success || (p_is_file && !MCS_file_exists_at_path(*t_new_path)))
return false;
r_redirected = MCValueRetain(*t_new_path);
return true;
}
/* LEGACY */
extern char *path2utf(char *);
static void handle_signal(int sig)
{
MCHandler handler(HT_MESSAGE);
switch (sig)
{
case SIGUSR1:
MCsiguser1++;
break;
case SIGUSR2:
MCsiguser2++;
break;
case SIGTERM:
if (MCdefaultstackptr)
{
switch (MCdefaultstackptr->getcard()->message(MCM_shut_down_request))
{
case ES_NORMAL:
return;
case ES_PASS:
case ES_NOT_HANDLED:
MCdefaultstackptr->getcard()->message(MCM_shut_down);
MCquit = True; //set MC quit flag, to invoke quitting
return;
default:
break;
}
}
MCS_killall();
exit(-1);
// MW-2009-01-29: [[ Bug 6410 ]] If one of these signals occurs, we need
// to return, so that the OS can CrashReport away.
case SIGILL:
case SIGBUS:
case SIGSEGV:
{
MCAutoStringRefAsUTF8String t_utf8_MCcmd;
/* UNCHECKED */ t_utf8_MCcmd.Lock(MCcmd);
fprintf(stderr, "%s exiting on signal %d\n", *t_utf8_MCcmd, sig);
MCS_killall();
return;
}
case SIGHUP:
case SIGINT:
case SIGQUIT:
case SIGIOT:
if (MCnoui)
exit(1);
MCabortscript = True;
break;
case SIGFPE:
errno = EDOM;
break;
case SIGCHLD:
MCS_checkprocesses();
break;
case SIGALRM: