Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 1003 lines (884 sloc) 25.126 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 1001 1002 1003
/*
* MacRuby ObjC helpers.
*
* This file is covered by the Ruby license. See COPYING for more details.
*
* Copyright (C) 2007-2011, Apple Inc. All rights reserved.
*/

#include <Foundation/Foundation.h>
#include "macruby_internal.h"
#include "ruby/node.h"
#include "ruby/encoding.h"
#include "ruby/objc.h"
#include "vm.h"
#include "objc.h"
#include "id.h"
#include "class.h"

#include <unistd.h>
#include <dlfcn.h>
#include <mach-o/dyld.h>
#include <sys/mman.h>
#if HAVE_BRIDGESUPPORT_FRAMEWORK
# include <BridgeSupport/BridgeSupport.h>
#else
# include "bs.h"
#endif

bool
rb_objc_get_types(VALUE recv, Class klass, SEL sel, Method method,
bs_element_method_t *bs_method, char *buf, size_t buflen)
{
    const char *type;
    unsigned i;

    memset(buf, 0, buflen);

    if (method != NULL) {
if (bs_method == NULL) {
type = method_getTypeEncoding(method);
assert(strlen(type) < buflen);
buf[0] = '\0';
do {
const char *type2 = SkipFirstType(type);
strncat(buf, type, type2 - type);
type = SkipStackSize(type2);
}
while (*type != '\0');
}
else {
char buf2[100];
type = rb_get_bs_method_type(bs_method, -1);
if (type != NULL) {
strlcpy(buf, type, buflen);
}
else {
method_getReturnType(method, buf2, sizeof buf2);
strlcpy(buf, buf2, buflen);
}

const unsigned int argc = rb_method_getNumberOfArguments(method);
for (i = 0; i < argc; i++) {
if (i >= 2 && (type = rb_get_bs_method_type(bs_method, i - 2))
!= NULL) {
strlcat(buf, type, buflen);
}
else {
method_getArgumentType(method, i, buf2, sizeof(buf2));
strlcat(buf, buf2, buflen);
}
}
}
return true;
    }
    else if (!SPECIAL_CONST_P(recv)) {
NSMethodSignature *msig = [(id)recv methodSignatureForSelector:sel];
if (msig != NULL) {
unsigned i;

type = rb_get_bs_method_type(bs_method, -1);
if (type == NULL) {
type = [msig methodReturnType];
}
strlcpy(buf, type, buflen);

const int argc = [msig numberOfArguments];
for (i = 0; i < argc; i++) {
if (i < 2 || (type = rb_get_bs_method_type(bs_method, i - 2))
== NULL) {
type = [msig getArgumentTypeAtIndex:i];
}
strlcat(buf, type, buflen);
}

return true;
}
    }
    return false;
}

bool
rb_objc_supports_forwarding(VALUE recv, SEL sel)
{
    if (!SPECIAL_CONST_P(recv)) {
return [(id)recv methodSignatureForSelector:sel] != nil;
    }
    return false;
}

static const char *
fileSystemPath(NSString *str)
{
    @try {
return [str fileSystemRepresentation];
    }
    @catch (id exc) {
// Sometimes, -fileSystemRepresentation can fail.
    }
    return [str UTF8String];
}

VALUE
rb_home_dir(VALUE user_name)
{
    NSString *user = nil;
    NSString *home_dir = nil;

    if (user_name != Qnil) {
user = (NSString *)user_name;
home_dir = NSHomeDirectoryForUser(user);
if (home_dir == nil) {
rb_raise(rb_eArgError, "user %s doesn't exist",
[user UTF8String]);
}
    }
    else {
home_dir = NSHomeDirectory();
if (home_dir == nil) {
return Qnil;
}
    }
    return rb_str_new2(fileSystemPath(home_dir));
}

static bool
is_absolute_path(NSString *path, bool expand_tilde)
{
    if (!expand_tilde && [path isAbsolutePath] && [path hasPrefix:@"~"]) {
return false;
    }
    return [path isAbsolutePath];
}

static VALUE
file_expand_path(VALUE fname, VALUE dname, bool absolute)
{
    NSString *res = (NSString *)FilePathValue(fname);

    if (is_absolute_path(res, !absolute)) {
// Resolve symlinks only in absolute mode.
NSString *tmp = absolute
? [res stringByResolvingSymlinksInPath]
: [[res stringByExpandingTildeInPath] stringByStandardizingPath];
// Make sure we don't have an invalid user path.
if ([res hasPrefix:@"~"] && [tmp isEqualToString:res]) {
NSString *user = [[[res pathComponents] objectAtIndex:0]
substringFromIndex:1];
rb_raise(rb_eArgError, "user %s doesn't exist", [user UTF8String]);
}
res = tmp;
    }
    else {
NSString *dir = dname != Qnil
? (NSString *)FilePathValue(dname)
: [[NSFileManager defaultManager] currentDirectoryPath];

if (!is_absolute_path(dir, !absolute)) {
dir = (NSString *)file_expand_path((VALUE)dir, Qnil, 0);
}

// stringByStandardizingPath does not expand "/." to "/".
if ([res isEqualToString:@"."] && [dir isEqualToString:@"/"]) {
res = @"/";
}
else {
res = [[dir stringByAppendingPathComponent:res]
stringByStandardizingPath];
}
    }

    return rb_str_new2(fileSystemPath(res));
}

VALUE
rb_file_expand_path(VALUE fname, VALUE dname)
{
    return file_expand_path(fname, dname, 0);
}

VALUE
rb_file_absolute_path(VALUE fname, VALUE dname)
{
    return file_expand_path(fname, dname, 1);
}

static VALUE
rb_objc_load_bs(VALUE recv, SEL sel, VALUE path)
{
#if MACRUBY_STATIC
    not_implemented_in_static(sel);
#else
    rb_vm_load_bridge_support(StringValuePtr(path), NULL, 0);
    return recv;
#endif
}

#if !defined(MACRUBY_STATIC)
static void
rb_objc_search_and_load_bridge_support(const char *framework_path)
{
    char path[PATH_MAX];

    if (bs_find_path(framework_path, path, sizeof path)) {
rb_vm_load_bridge_support(path, framework_path,
                                    BS_PARSE_OPTIONS_LOAD_DYLIBS);
    }
}
#endif

bool rb_objc_enable_ivar_set_kvo_notifications = false;

VALUE
rb_require_framework(VALUE recv, SEL sel, int argc, VALUE *argv)
{
#if MACRUBY_STATIC
    not_implemented_in_static(sel);
#else
    VALUE framework;
    VALUE search_network;
    const char *cstr;
    NSFileManager *fileManager;
    NSString *path;
    NSBundle *bundle;
    NSError *error;
    
    rb_scan_args(argc, argv, "11", &framework, &search_network);

    Check_Type(framework, T_STRING);
    cstr = RSTRING_PTR(framework);

    fileManager = [NSFileManager defaultManager];
    path = [fileManager stringWithFileSystemRepresentation:cstr
length:strlen(cstr)];

    if (![fileManager fileExistsAtPath:path]) {
/* framework name is given */
NSSearchPathDomainMask pathDomainMask;
NSString *frameworkName;
NSArray *dirs;
NSUInteger i, count;

cstr = NULL;

#define FIND_LOAD_PATH_IN_LIBRARY(dir) \
do { \
path = [[dir stringByAppendingPathComponent:@"Frameworks"] \
stringByAppendingPathComponent:frameworkName]; \
if ([fileManager fileExistsAtPath:path]) { \
goto success; \
} \
path = [[dir stringByAppendingPathComponent:@"PrivateFrameworks"] \
stringByAppendingPathComponent:frameworkName]; \
if ([fileManager fileExistsAtPath:path]) { \
goto success; \
} \
} \
while (0)

pathDomainMask = RTEST(search_network)
? NSAllDomainsMask
: NSUserDomainMask | NSLocalDomainMask | NSSystemDomainMask;

frameworkName = [path stringByAppendingPathExtension:@"framework"];

path = [[[[NSBundle mainBundle] bundlePath]
stringByAppendingPathComponent:@"Contents/Frameworks"]
stringByAppendingPathComponent:frameworkName];
if ([fileManager fileExistsAtPath:path]) {
goto success;
}

dirs = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
pathDomainMask, YES);
for (i = 0, count = [dirs count]; i < count; i++) {
NSString *dir = [dirs objectAtIndex:i];
FIND_LOAD_PATH_IN_LIBRARY(dir);
}

dirs = NSSearchPathForDirectoriesInDomains(NSDeveloperDirectory,
pathDomainMask, YES);
for (i = 0, count = [dirs count]; i < count; i++) {
NSString *dir = [[dirs objectAtIndex:i]
stringByAppendingPathComponent:@"Library"];
FIND_LOAD_PATH_IN_LIBRARY(dir);
}

    dirs = [[[[NSProcessInfo processInfo] environment] valueForKey:@"DYLD_FRAMEWORK_PATH"] componentsSeparatedByString: @":"];
    for (i = 0, count = [dirs count]; i < count; i++) {
        NSString *dir = [dirs objectAtIndex:i];
        path = [dir stringByAppendingPathComponent:frameworkName];
        if ([fileManager fileExistsAtPath:path]) {
            goto success;
}
    }

#undef FIND_LOAD_PATH_IN_LIBRARY

rb_raise(rb_eRuntimeError, "framework `%s' not found",
RSTRING_PTR(framework));
    }

success:

    if (cstr == NULL) {
cstr = fileSystemPath(path);
    }

    bundle = [NSBundle bundleWithPath:path];
    if (bundle == nil) {
rb_raise(rb_eRuntimeError,
"framework at path `%s' cannot be located",
cstr);
    }

    const bool loaded = [bundle isLoaded];
    if (!loaded && ![bundle loadAndReturnError:&error]) {
rb_raise(rb_eRuntimeError,
"framework at path `%s' cannot be loaded: %s",
cstr,
[[error description] UTF8String]);
    }

    rb_objc_search_and_load_bridge_support(cstr);

    rb_objc_enable_ivar_set_kvo_notifications = true;

    return loaded ? Qfalse : Qtrue;
#endif
}

void rb_vm_init_compiler(void);

static void
rb_objc_kvo_setter_imp(void *recv, SEL sel, void *value)
{
    const char *selname;
    char buf[128];
    size_t s;

    selname = sel_getName(sel);
    buf[0] = '@';
    buf[1] = tolower(selname[3]);
    s = strlcpy(&buf[2], &selname[4], sizeof buf - 2);
    buf[s + 1] = '\0';

    rb_ivar_set((VALUE)recv, rb_intern(buf), value == NULL
? Qnil : OC2RB(value));
}

/*
Defines an attribute writer method which conforms to Key-Value Coding.
(See http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/KeyValueCoding.html)
attr_accessor :foo
Will create the normal accessor methods, plus <tt>setFoo</tt>
TODO: Does not handle the case were the user might override #foo=
*/
void
rb_objc_define_kvo_setter(VALUE klass, ID mid)
{
    char buf[100];
    const char *mid_name;

    buf[0] = 's'; buf[1] = 'e'; buf[2] = 't';
    mid_name = rb_id2name(mid);

    buf[3] = toupper(mid_name[0]);
    buf[4] = '\0';
    strlcat(buf, &mid_name[1], sizeof buf);
    strlcat(buf, ":", sizeof buf);

    if (!class_addMethod((Class)klass, sel_registerName(buf),
(IMP)rb_objc_kvo_setter_imp, "v@:@")) {
rb_warning("can't register `%s' as an KVO setter on class `%s' "\
"(method `%s')",
mid_name, rb_class2name(klass), buf);
    }
}

VALUE
rb_mod_objc_ib_outlet(VALUE recv, SEL sel, int argc, VALUE *argv)
{
    int i;

    rb_warn("ib_outlet has been deprecated, please use attr_writer instead");

    for (i = 0; i < argc; i++) {
VALUE sym = argv[i];

Check_Type(sym, T_SYMBOL);
rb_objc_define_kvo_setter(recv, SYM2ID(sym));
    }

    return recv;
}

static void *__obj_flags; // used as a static key

long
rb_objc_flag_get_mask(const void *obj)
{
    return (long)rb_objc_get_associative_ref((void *)obj, &__obj_flags);
}

bool
rb_objc_flag_check(const void *obj, int flag)
{
    const long v = rb_objc_flag_get_mask(obj);
    if (v == 0) {
return false;
    }
    return (v & flag) == flag;
}

void
rb_objc_flag_set(const void *obj, int flag, bool val)
{
    long v = (long)rb_objc_get_associative_ref((void *)obj, &__obj_flags);
    if (val) {
v |= flag;
    }
    else {
v ^= flag;
    }
    rb_objc_set_associative_ref((void *)obj, &__obj_flags, (void *)v);
}

static IMP old_imp_isaForAutonotifying;

static Class
rb_obj_imp_isaForAutonotifying(void *rcv, SEL sel)
{
    long ret_version;

    Class ret = ((Class (*)(void *, SEL))old_imp_isaForAutonotifying)(rcv, sel);

    if (ret != NULL && ((ret_version = RCLASS_VERSION(ret)) & RCLASS_KVO_CHECK_DONE) == 0) {
const char *name = class_getName(ret);
if (strncmp(name, "NSKVONotifying_", 15) == 0) {
Class ret_orig;
name += 15;
ret_orig = objc_getClass(name);
if (ret_orig != NULL) {
const long orig_v = RCLASS_VERSION(ret_orig);
if ((orig_v & RCLASS_IS_OBJECT_SUBCLASS) == RCLASS_IS_OBJECT_SUBCLASS) {
ret_version |= RCLASS_IS_OBJECT_SUBCLASS;
}
if ((orig_v & RCLASS_IS_RUBY_CLASS) == RCLASS_IS_RUBY_CLASS) {
ret_version |= RCLASS_IS_RUBY_CLASS;
}
}
}
ret_version |= RCLASS_KVO_CHECK_DONE;
RCLASS_SET_VERSION(ret, ret_version);
    }
    return ret;
}

id
rb_rb2oc_exception(VALUE exc)
{
    NSString *name = [NSString stringWithUTF8String:rb_obj_classname(exc)];
    NSString *reason = (NSString *)rb_format_exception_message(exc);
    NSDictionary *dict = [NSDictionary dictionaryWithObject:(id)exc
forKey:@"RubyException"];
    return [NSException exceptionWithName:name reason:reason userInfo:dict];
}

VALUE
rb_oc2rb_exception(id exc, bool *created)
{
    VALUE e;
    id rubyExc;

    rubyExc = [[exc userInfo] objectForKey:@"RubyException"];
    if (rubyExc == nil) {
*created = true;

char buf[1000];
snprintf(buf, sizeof buf, "%s: %s", [[exc name] UTF8String],
[[exc reason] UTF8String]);
e = rb_exc_new2(rb_eRuntimeError, buf);
// Set the backtrace for Obj-C exceptions
rb_iv_set(e, "bt", rb_vm_backtrace(0));
    }
    else {
*created = false;
e = (VALUE)rubyExc;
    }
    return e;
}

void
rb_objc_exception_raise(const char *name, const char *message)
{
    assert(name != NULL && message != NULL);
    [[NSException exceptionWithName:[NSString stringWithUTF8String:name]
reason:[NSString stringWithUTF8String:message] userInfo:nil] raise];
}

id
rb_objc_numeric2nsnumber(VALUE obj)
{
    if (FIXNUM_P(obj)) {
// TODO: this could be optimized in case we can fit the fixnum
// into an immediate NSNumber directly.
long val = FIX2LONG(obj);
CFNumberRef number = CFNumberCreate(NULL, kCFNumberLongType, &val);
CFMakeCollectable(number);
return (id)number;
    }
    if (FIXFLOAT_P(obj)) {
double val = NUM2DBL(obj);
CFNumberRef number = CFNumberCreate(NULL, kCFNumberDoubleType,
&val);
CFMakeCollectable(number);
return (id)number;
    }
    abort();
}

static SEL sel_at = 0;

VALUE
rb_objc_convert_immediate(id obj)
{
    const bool is_immediate = ((unsigned long)obj & 0x1) == 0x1;

    Class orig_k = object_getClass(obj); // might be an immediate
    Class k = orig_k;
    do {
if (k == (Class)rb_cNSNumber) {
// TODO: this could be optimized in case the object is an immediate.
if (CFNumberIsFloatType((CFNumberRef)obj)) {
double v = 0;
assert(CFNumberGetValue((CFNumberRef)obj, kCFNumberDoubleType, &v));
return DOUBLE2NUM(v);
}
else {
long v = 0;
assert(CFNumberGetValue((CFNumberRef)obj, kCFNumberLongType, &v));
return LONG2FIX(v);
}
}
else if (k == (Class)rb_cNSDate) {
@try {
CFAbsoluteTime time = CFDateGetAbsoluteTime((CFDateRef)obj) + CF_REFERENCE_DATE;
#if __LP64__
VALUE arg = DBL2NUM(time);
return rb_vm_call(rb_cTime, sel_at, 1, &arg);
#else
// immediate floats have not enough precision in 32-bit
// so instead of using Time.at(time in float),
// we use Time.at(sec, usec)
double integral, fractional;
fractional = modf(time, &integral);
VALUE args[] = {
LONG2NUM((long)integral),
LONG2NUM((long)(fractional * 1e6 + 0.5))
};
return rb_vm_call(rb_cTime, sel_at, 2, args);
#endif
}
@catch (NSException *e) {
// Some NSDates might return an exception (example: uninitialized objects).
break;
}
}
k = class_getSuperclass(k);
    }
    while (k != NULL);

    if (is_immediate) {
rb_bug("unknown Objective-C immediate: %p (%s)\n", obj, class_getName(orig_k));
    }
    return (VALUE)obj;
}

bool
rb_objc_ignored_sel(SEL sel)
{
    return sel == @selector(retain)
|| sel == @selector(release)
|| sel == @selector(autorelease)
|| sel == @selector(retainCount)
|| sel == @selector(dealloc);
}

bool
rb_objc_isEqual(VALUE x, VALUE y)
{
    return [RB2OC(x) isEqual:RB2OC(y)];
}

void
rb_objc_force_class_initialize(Class klass)
{
    // Do not do anything in case the class is not NSObject-based
    // (likely Proxy).
    bool ok = false;
    for (Class k = klass; k != NULL; k = class_getSuperclass(k)) {
if (k == (Class)rb_cNSObject) {
ok = true;
break;
}
    }
    if (!ok) {
return;
    }

    // This forces +initialize to be called.
    class_getMethodImplementation(klass, @selector(initialize));
}

size_t
rb_objc_type_size(const char *type)
{
    @try {
NSUInteger size, align;
NSGetSizeAndAlignment(type, &size, &align);
return size;
    }
    @catch (id ex) {
rb_raise(rb_eRuntimeError, "can't get the size of type `%s': %s",
type, [[ex description] UTF8String]);
    }
    return 0; // never reached
}

static NSString *
relocated_load_path(NSString *path, NSString *macruby_path)
{
    NSRange r = [path rangeOfString:@"MacRuby.framework"];
    if (r.location == NSNotFound) {
return nil;
    }
    r = NSMakeRange(0, r.location + r.length);
    return [path stringByReplacingCharactersInRange:r withString:macruby_path];
}

void
rb_objc_fix_relocatable_load_path(void)
{
    NSString *path = [[NSBundle mainBundle] privateFrameworksPath];
    path = [path stringByAppendingPathComponent:@"MacRuby.framework"];

    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:path]) {
VALUE ary = rb_vm_load_path();
for (long i = 0, count = RARRAY_LEN(ary); i < count; i++) {
NSString *p1 = (NSString *)RARRAY_AT(ary, i);
NSString *p2 = relocated_load_path(p1, path);
if (p2 != nil) {
rb_ary_store(ary, i, (VALUE)p2);
}
}
    }
}

void
rb_objc_load_loaded_frameworks_bridgesupport(void)
{
#if !defined(MACRUBY_STATIC)
    for (NSBundle *b in [NSBundle allFrameworks]) {
if ([b isLoaded]) {
NSString *path = [b bundlePath];
rb_objc_search_and_load_bridge_support(fileSystemPath(path));
}
    }
#endif
}

void
rb_objc_willChangeValueForKey(VALUE obj, NSString *key)
{
    if (!SPECIAL_CONST_P(obj)) {
[(id)obj willChangeValueForKey:key];
    }
}

void
rb_objc_didChangeValueForKey(VALUE obj, NSString *key)
{
    if (!SPECIAL_CONST_P(obj)) {
[(id)obj didChangeValueForKey:key];
    }
}

static VALUE
rb_objc_load_plist(VALUE recv, SEL sel, VALUE str)
{
    StringValue(str);
    VALUE bstr = rb_str_bstr(str);
    NSData *data = [NSData dataWithBytes:rb_bstr_bytes(bstr)
length:rb_bstr_length(bstr)];
    NSError *err = nil;
    id plist = [NSPropertyListSerialization propertyListWithData:data options:0
format:NULL error:&err];
    if (plist == nil) {
rb_raise(rb_eArgError, "error loading property list: '%s'",
[[err localizedDescription] UTF8String]);
    }
    return OC2RB(plist);
}

extern VALUE rb_cNSDate;

static VALUE
rb_objc_to_plist(VALUE recv, SEL sel)
{
    switch (TYPE(recv)) {
case T_STRING:
case T_FIXNUM:
case T_FLOAT:
case T_BIGNUM:
case T_HASH:
case T_ARRAY:
case T_TRUE:
case T_FALSE:
break;

default:
if (!rb_obj_is_kind_of(recv, rb_cNSDate)) {
rb_raise(rb_eArgError,
"object of class '%s' cannot be serialized to " \
"property-list format",
rb_obj_classname(recv));
}
    }

    id objc_obj = RB2OC(recv);
    NSError *err = nil;
    NSData *data = [NSPropertyListSerialization dataWithPropertyList:objc_obj
format:NSPropertyListXMLFormat_v1_0 options:0 error:&err];
    if (data == nil) {
rb_raise(rb_eArgError, "error serializing property list: '%s'",
[[err localizedDescription] UTF8String]);
    }
    const uint8_t* bytes = [data bytes];
    const size_t len = [data length];
    return rb_bstr_new_with_data(bytes, len);
}

static bool
implementsProtocolMethods(Protocol *p, Class klass, bool instanceMethods)
{
    unsigned int count = 0;
    struct objc_method_description *list =
protocol_copyMethodDescriptionList(p, true, instanceMethods, &count);
    if (list != NULL) {
bool success = true;
for (unsigned int i = 0; i < count; i++) {
SEL msel = list[i].name;
Method m;
if (instanceMethods) {
m = class_getInstanceMethod(klass, msel);
}
else {
m = class_getClassMethod(klass, msel);
}
if (m == NULL) {
success = false;
break;
}
}
free(list);
if (success) {
return true;
}
return false;
    }
    return true;
}

static bool
conformsToProtocol(Class klass, Protocol *p)
{
    if (implementsProtocolMethods(p, klass, true)
&& implementsProtocolMethods(p, klass, false)) {
unsigned int count = 0;
Protocol **list = protocol_copyProtocolList(p, &count);
bool success = true;
for (unsigned int i = 0; i < count; i++) {
if (!conformsToProtocol(klass, list[i])) {
success = false;
break;
}
}
free(list);
return success;
    }
    return false;
}

static bool
conformsToProtocolAndAncestors(void *self, SEL sel, Class klass,
void *protocol)
{
    if (protocol != NULL) {
for (Class k = klass; k != NULL; k = class_getSuperclass(k)) {
if (class_conformsToProtocol(k, protocol)) {
return true;
}
}

Protocol *p = (Protocol *)protocol;
if (conformsToProtocol(klass, p)) {
class_addProtocol(klass, p);
return true;
}
    }
    return false;
}

static bool
robj_conformsToProtocol(void *self, SEL sel, void *protocol)
{
    return conformsToProtocolAndAncestors(self, sel, object_getClass(self),
protocol);
}

static bool
robj_conformsToProtocol_m(void *self, SEL sel, void *protocol)
{
    return conformsToProtocolAndAncestors(self, sel, (Class)self, protocol);
}

static id
robj_performSelector(void *self, SEL sel, SEL msg)
{
    return RB2OC(rb_vm_call(OC2RB(self), msg, 0, NULL));
}

static id
robj_performSelectorWithObject(void *self, SEL sel, SEL msg, void *arg)
{
    VALUE rarg = OC2RB(arg);
    return RB2OC(rb_vm_call(OC2RB(self), msg, 1, &rarg));
}

static id
robj_performSelectorWithObjectWithObject(void *self, SEL sel, SEL msg,
void *arg1, void *arg2)
{
    VALUE rarg[2] = { OC2RB(arg1), OC2RB(arg2) };
    return RB2OC(rb_vm_call(OC2RB(self), msg, 2, rarg));
}

void
rb_objc_install_NSObject_special_methods(Class k)
{
    SEL sel = sel_registerName("conformsToProtocol:");
    rb_objc_install_method(k, sel, (IMP)robj_conformsToProtocol);
    rb_objc_install_method(*(Class *)k, sel, (IMP)robj_conformsToProtocol_m);

    rb_objc_install_method2(k, "performSelector:", (IMP)robj_performSelector);
    rb_objc_install_method2(k, "performSelector:withObject:",
(IMP)robj_performSelectorWithObject);
    rb_objc_install_method2(k, "performSelector:withObject:withObject:",
(IMP)robj_performSelectorWithObjectWithObject);
}

void
Init_ObjC(void)
{
    sel_at = sel_registerName("at:");

    rb_objc_define_module_function(rb_mKernel, "load_bridge_support_file",
rb_objc_load_bs, 1);
    rb_objc_define_module_function(rb_mKernel, "load_plist",
rb_objc_load_plist, 1);
    
    rb_objc_define_method(rb_cObject, "to_plist", rb_objc_to_plist, 0);

    // Overwrite -[NSKeyValueUnnestedProperty isaForAutonotifying].
    Class k = objc_getClass("NSKeyValueUnnestedProperty");
    assert(k != NULL);
    Method m = class_getInstanceMethod(k, @selector(isaForAutonotifying));
    assert(m != NULL);
    old_imp_isaForAutonotifying = method_getImplementation(m);
    method_setImplementation(m, (IMP)rb_obj_imp_isaForAutonotifying);

    // Mark Foundation as multithreaded.
    [NSThread detachNewThreadSelector:@selector(self) toTarget:[NSThread class]
withObject:nil];
}

@interface Protocol
@end

@implementation Protocol (MRFindProtocol)
+ (Protocol *)protocolWithName:(NSString *)name
{
    return (Protocol *)objc_getProtocol([name UTF8String]);
}
@end

#if !defined(MACRUBY_STATIC)
static NSString *
get_type(NSXMLElement *elem)
{
    NSXMLNode *node = nil;
#if __LP64__
    node = [elem attributeForName:@"type64"];
#endif
    if (node == nil) {
node = [elem attributeForName:@"type"];
if (node == nil) {
return nil;
}
    }
    return [node stringValue];
}

static void
add_stub_types(NSXMLElement *elem,
void (*add_stub_types_cb)(SEL, const char *, bool, void *),
void *ctx,
bool is_objc)
{
    NSXMLNode *name = [elem attributeForName:is_objc
? @"selector" : @"name"];
    if (name == nil) {
return;
    }
    NSArray *ary = [elem elementsForName:@"retval"];
    if ([ary count] != 1) {
return;
    }
    NSXMLElement *retval = [ary objectAtIndex:0];
    NSMutableString *types = [NSMutableString new];
    NSString *type = get_type(retval);
    if (type == nil) {
return;
    }
    [types appendString:type];
    if (is_objc) {
[types appendString:@"@:"]; // self, sel
    }
    ary = [elem elementsForName:@"arg"];
    for (NSXMLElement *a in ary) {
type = get_type(a);
if (type == nil) {
return;
}
[types appendString:type];
    }
    NSString *sel_str = [name stringValue];
    if (!is_objc && [ary count] > 0) {
sel_str = [sel_str stringByAppendingString:@":"];
    }
    SEL sel = sel_registerName([sel_str UTF8String]);
    add_stub_types_cb(sel, [types UTF8String], is_objc, ctx);
}

void
rb_vm_parse_bs_full_file(const char *path,
void (*add_stub_types_cb)(SEL, const char *, bool, void *),
void *ctx)
{
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path]];
    NSError *err = nil;
    NSXMLDocument *doc = [[NSXMLDocument alloc] initWithContentsOfURL: url
options: 0 error: &err];
    if (doc == nil) {
NSLog(@"can't open BridgeSupport full file at path `%s': %@",
path, err);
exit(1);
    }
    NSXMLElement *root = [doc rootElement];

    for (NSXMLElement *k in [root elementsForName:@"class"]) {
for (NSXMLElement *m in [k elementsForName:@"method"]) {
add_stub_types(m, add_stub_types_cb, ctx, true);
}
    }
    for (NSXMLElement *f in [root elementsForName:@"function"]) {
add_stub_types(f, add_stub_types_cb, ctx, false);
    }
}
#endif
Something went wrong with that request. Please try again.