/* ** $Id: lbaselib.c,v 1.191.1.6 2008/02/14 16:46:22 roberto Exp $ ** Basic library ** See Copyright Notice in lua.h */ #include #include #include #include #define lbaselib_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** If your system does not support `stdout', you can just remove this function. ** If you need, you can define your own `print' function, following this ** model but changing `fputs' to put the strings at a proper place ** (a console window or a log file, for instance). */ static int luaB_print (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int i; lua_getglobal(L, "tostring"); for (i=1; i<=n; i++) { const char *s; lua_pushvalue(L, -1); /* function to be called */ lua_pushvalue(L, i); /* value to print */ lua_call(L, 1, 1); s = lua_tostring(L, -1); /* get result */ if (s == NULL) return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("print")); if (i>1) fputs("\t", stdout); fputs(s, stdout); lua_pop(L, 1); /* pop result */ } fputs("\n", stdout); return 0; } static int luaB_tonumber (lua_State *L) { int base = luaL_optint(L, 2, 10); if (base == 10) { /* standard conversion */ luaL_checkany(L, 1); if (lua_isnumber(L, 1)) { lua_pushnumber(L, lua_tonumber(L, 1)); return 1; } } else { const char *s1 = luaL_checkstring(L, 1); char *s2; unsigned long n; luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); n = strtoul(s1, &s2, base); if (s1 != s2) { /* at least one valid digit? */ while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */ if (*s2 == '\0') { /* no invalid trailing characters? */ lua_pushnumber(L, (lua_Number)n); return 1; } } } lua_pushnil(L); /* else not a number */ return 1; } static int luaB_error (lua_State *L) { int level = luaL_optint(L, 2, 1); lua_settop(L, 1); if (lua_isstring(L, 1) && level > 0) { /* add extra information? */ luaL_where(L, level); lua_pushvalue(L, 1); lua_concat(L, 2); } return lua_error(L); } static int luaB_getmetatable (lua_State *L) { luaL_checkany(L, 1); if (!lua_getmetatable(L, 1)) { lua_pushnil(L); return 1; /* no metatable */ } luaL_getmetafield(L, 1, "__metatable"); return 1; /* returns either __metatable field (if present) or metatable */ } static int luaB_setmetatable (lua_State *L) { int t = lua_type(L, 2); luaL_checktype(L, 1, LUA_TTABLE); luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table expected"); if (luaL_getmetafield(L, 1, "__metatable")) luaL_error(L, "cannot change a protected metatable"); lua_settop(L, 2); lua_setmetatable(L, 1); return 1; } static void getfunc (lua_State *L, int opt) { if (lua_isfunction(L, 1)) lua_pushvalue(L, 1); else { lua_Debug ar; int level = opt ? luaL_optint(L, 1, 1) : luaL_checkint(L, 1); luaL_argcheck(L, level >= 0, 1, "level must be non-negative"); if (lua_getstack(L, level, &ar) == 0) luaL_argerror(L, 1, "invalid level"); lua_getinfo(L, "f", &ar); if (lua_isnil(L, -1)) luaL_error(L, "no function environment for tail call at level %d", level); } } static int luaB_getfenv (lua_State *L) { getfunc(L, 1); if (lua_iscfunction(L, -1)) /* is a C function? */ lua_pushvalue(L, LUA_GLOBALSINDEX); /* return the thread's global env. */ else lua_getfenv(L, -1); return 1; } static int luaB_setfenv (lua_State *L) { luaL_checktype(L, 2, LUA_TTABLE); getfunc(L, 0); lua_pushvalue(L, 2); if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0) { /* change environment of current thread */ lua_pushthread(L); lua_insert(L, -2); lua_setfenv(L, -2); return 0; } else if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0) luaL_error(L, LUA_QL("setfenv") " cannot change environment of given object"); return 1; } static int luaB_rawequal (lua_State *L) { luaL_checkany(L, 1); luaL_checkany(L, 2); lua_pushboolean(L, lua_rawequal(L, 1, 2)); return 1; } static int luaB_rawget (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); luaL_checkany(L, 2); lua_settop(L, 2); lua_rawget(L, 1); return 1; } static int luaB_rawset (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); luaL_checkany(L, 2); luaL_checkany(L, 3); lua_settop(L, 3); lua_rawset(L, 1); return 1; } static int luaB_gcinfo (lua_State *L) { lua_pushinteger(L, lua_getgccount(L)); return 1; } static int luaB_collectgarbage (lua_State *L) { static const char *const opts[] = {"stop", "restart", "collect", "count", "step", "setpause", "setstepmul", NULL}; static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL}; int o = luaL_checkoption(L, 1, "collect", opts); int ex = luaL_optint(L, 2, 0); int res = lua_gc(L, optsnum[o], ex); switch (optsnum[o]) { case LUA_GCCOUNT: { int b = lua_gc(L, LUA_GCCOUNTB, 0); lua_pushnumber(L, res + ((lua_Number)b/1024)); return 1; } case LUA_GCSTEP: { lua_pushboolean(L, res); return 1; } default: { lua_pushnumber(L, res); return 1; } } } static int luaB_type (lua_State *L) { luaL_checkany(L, 1); lua_pushstring(L, luaL_typename(L, 1)); return 1; } static int luaB_next (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 2); /* create a 2nd argument if there isn't one */ if (lua_next(L, 1)) return 2; else { lua_pushnil(L); return 1; } } static int luaB_pairs (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ lua_pushvalue(L, 1); /* state, */ lua_pushnil(L); /* and initial value */ return 3; } static int ipairsaux (lua_State *L) { int i = luaL_checkint(L, 2); luaL_checktype(L, 1, LUA_TTABLE); i++; /* next value */ lua_pushinteger(L, i); lua_rawgeti(L, 1, i); return (lua_isnil(L, -1)) ? 0 : 2; } static int luaB_ipairs (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */ lua_pushvalue(L, 1); /* state, */ lua_pushinteger(L, 0); /* and initial value */ return 3; } static int load_aux (lua_State *L, int status) { if (status == 0) /* OK? */ return 1; else { lua_pushnil(L); lua_insert(L, -2); /* put before error message */ return 2; /* return nil plus error message */ } } static int luaB_loadstring (lua_State *L) { size_t l; const char *s = luaL_checklstring(L, 1, &l); const char *chunkname = luaL_optstring(L, 2, s); return load_aux(L, luaL_loadbuffer(L, s, l, chunkname)); } static int luaB_loadfile (lua_State *L) { const char *fname = luaL_optstring(L, 1, NULL); return load_aux(L, luaL_loadfile(L, fname)); } /* ** Reader for generic `load' function: `lua_load' uses the ** stack for internal stuff, so the reader cannot change the ** stack top. Instead, it keeps its resulting string in a ** reserved slot inside the stack. */ static const char *generic_reader (lua_State *L, void *ud, size_t *size) { (void)ud; /* to avoid warnings */ luaL_checkstack(L, 2, "too many nested functions"); lua_pushvalue(L, 1); /* get function */ lua_call(L, 0, 1); /* call it */ if (lua_isnil(L, -1)) { *size = 0; return NULL; } else if (lua_isstring(L, -1)) { lua_replace(L, 3); /* save string in a reserved stack slot */ return lua_tolstring(L, 3, size); } else luaL_error(L, "reader function must return a string"); return NULL; /* to avoid warnings */ } static int luaB_load (lua_State *L) { int status; const char *cname = luaL_optstring(L, 2, "=(load)"); luaL_checktype(L, 1, LUA_TFUNCTION); lua_settop(L, 3); /* function, eventual name, plus one reserved slot */ status = lua_load(L, generic_reader, NULL, cname); return load_aux(L, status); } static int luaB_dofile (lua_State *L) { const char *fname = luaL_optstring(L, 1, NULL); int n = lua_gettop(L); if (luaL_loadfile(L, fname) != 0) lua_error(L); lua_call(L, 0, LUA_MULTRET); return lua_gettop(L) - n; } static int luaB_assert (lua_State *L) { luaL_checkany(L, 1); if (!lua_toboolean(L, 1)) return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!")); return lua_gettop(L); } static int luaB_unpack (lua_State *L) { int i, e, n; luaL_checktype(L, 1, LUA_TTABLE); i = luaL_optint(L, 2, 1); e = luaL_opt(L, luaL_checkint, 3, luaL_getn(L, 1)); if (i > e) return 0; /* empty range */ n = e - i + 1; /* number of elements */ if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */ return luaL_error(L, "too many results to unpack"); lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */ while (i++ < e) /* push arg[i + 1...e] */ lua_rawgeti(L, 1, i); return n; } static int luaB_select (lua_State *L) { int n = lua_gettop(L); if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { lua_pushinteger(L, n-1); return 1; } else { int i = luaL_checkint(L, 1); if (i < 0) i = n + i; else if (i > n) i = n; luaL_argcheck(L, 1 <= i, 1, "index out of range"); return n - i; } } static int luaB_pcall (lua_State *L) { int status; luaL_checkany(L, 1); status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0); lua_pushboolean(L, (status == 0)); lua_insert(L, 1); return lua_gettop(L); /* return status + all results */ } static int luaB_xpcall (lua_State *L) { int status; luaL_checkany(L, 2); lua_settop(L, 2); lua_insert(L, 1); /* put error function under function to be called */ status = lua_pcall(L, 0, LUA_MULTRET, 1); lua_pushboolean(L, (status == 0)); lua_replace(L, 1); return lua_gettop(L); /* return status + all results */ } static int luaB_tostring (lua_State *L) { luaL_checkany(L, 1); if (luaL_callmeta(L, 1, "__tostring")) /* is there a metafield? */ return 1; /* use its value */ switch (lua_type(L, 1)) { case LUA_TNUMBER: lua_pushstring(L, lua_tostring(L, 1)); break; case LUA_TSTRING: lua_pushvalue(L, 1); break; case LUA_TBOOLEAN: lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false")); break; case LUA_TNIL: lua_pushliteral(L, "nil"); break; default: lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1)); break; } return 1; } static int luaB_newproxy (lua_State *L) { lua_settop(L, 1); lua_newuserdata(L, 0); /* create proxy */ if (lua_toboolean(L, 1) == 0) return 1; /* no metatable */ else if (lua_isboolean(L, 1)) { lua_newtable(L); /* create a new metatable `m' ... */ lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */ lua_pushboolean(L, 1); lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */ } else { int validproxy = 0; /* to check if weaktable[metatable(u)] == true */ if (lua_getmetatable(L, 1)) { lua_rawget(L, lua_upvalueindex(1)); validproxy = lua_toboolean(L, -1); lua_pop(L, 1); /* remove value */ } luaL_argcheck(L, validproxy, 1, "boolean or proxy expected"); lua_getmetatable(L, 1); /* metatable is valid; get it */ } lua_setmetatable(L, 2); return 1; } static const luaL_Reg base_funcs[] = { {"assert", luaB_assert}, {"collectgarbage", luaB_collectgarbage}, {"dofile", luaB_dofile}, {"error", luaB_error}, {"gcinfo", luaB_gcinfo}, {"getfenv", luaB_getfenv}, {"getmetatable", luaB_getmetatable}, {"loadfile", luaB_loadfile}, {"load", luaB_load}, {"loadstring", luaB_loadstring}, {"next", luaB_next}, {"pcall", luaB_pcall}, {"print", luaB_print}, {"rawequal", luaB_rawequal}, {"rawget", luaB_rawget}, {"rawset", luaB_rawset}, {"select", luaB_select}, {"setfenv", luaB_setfenv}, {"setmetatable", luaB_setmetatable}, {"tonumber", luaB_tonumber}, {"tostring", luaB_tostring}, {"type", luaB_type}, {"unpack", luaB_unpack}, {"xpcall", luaB_xpcall}, {NULL, NULL} }; /* ** {====================================================== ** Coroutine library ** ======================================================= */ #define CO_RUN 0 /* running */ #define CO_SUS 1 /* suspended */ #define CO_NOR 2 /* 'normal' (it resumed another coroutine) */ #define CO_DEAD 3 static const char *const statnames[] = {"running", "suspended", "normal", "dead"}; static int costatus (lua_State *L, lua_State *co) { if (L == co) return CO_RUN; switch (lua_status(co)) { case LUA_YIELD: return CO_SUS; case 0: { lua_Debug ar; if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */ return CO_NOR; /* it is running */ else if (lua_gettop(co) == 0) return CO_DEAD; else return CO_SUS; /* initial state */ } default: /* some error occured */ return CO_DEAD; } } static int luaB_costatus (lua_State *L) { lua_State *co = lua_tothread(L, 1); luaL_argcheck(L, co, 1, "coroutine expected"); lua_pushstring(L, statnames[costatus(L, co)]); return 1; } static int auxresume (lua_State *L, lua_State *co, int narg) { int status = costatus(L, co); if (!lua_checkstack(co, narg)) luaL_error(L, "too many arguments to resume"); if (status != CO_SUS) { lua_pushfstring(L, "cannot resume %s coroutine", statnames[status]); return -1; /* error flag */ } lua_xmove(L, co, narg); lua_setlevel(L, co); status = lua_resume(co, narg); if (status == 0 || status == LUA_YIELD) { int nres = lua_gettop(co); if (!lua_checkstack(L, nres + 1)) luaL_error(L, "too many results to resume"); lua_xmove(co, L, nres); /* move yielded values */ return nres; } else { lua_xmove(co, L, 1); /* move error message */ return -1; /* error flag */ } } static int luaB_coresume (lua_State *L) { lua_State *co = lua_tothread(L, 1); int r; luaL_argcheck(L, co, 1, "coroutine expected"); r = auxresume(L, co, lua_gettop(L) - 1); if (r < 0) { lua_pushboolean(L, 0); lua_insert(L, -2); return 2; /* return false + error message */ } else { lua_pushboolean(L, 1); lua_insert(L, -(r + 1)); return r + 1; /* return true + `resume' returns */ } } static int luaB_auxwrap (lua_State *L) { lua_State *co = lua_tothread(L, lua_upvalueindex(1)); int r = auxresume(L, co, lua_gettop(L)); if (r < 0) { if (lua_isstring(L, -1)) { /* error object is a string? */ luaL_where(L, 1); /* add extra info */ lua_insert(L, -2); lua_concat(L, 2); } lua_error(L); /* propagate error */ } return r; } static int luaB_cocreate (lua_State *L) { lua_State *NL = lua_newthread(L); luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1, "Lua function expected"); lua_pushvalue(L, 1); /* move function to top */ lua_xmove(L, NL, 1); /* move function from L to NL */ return 1; } static int luaB_cowrap (lua_State *L) { luaB_cocreate(L); lua_pushcclosure(L, luaB_auxwrap, 1); return 1; } static int luaB_yield (lua_State *L) { return lua_yield(L, lua_gettop(L)); } static int luaB_corunning (lua_State *L) { if (lua_pushthread(L)) lua_pushnil(L); /* main thread is not a coroutine */ return 1; } static const luaL_Reg co_funcs[] = { {"create", luaB_cocreate}, {"resume", luaB_coresume}, {"running", luaB_corunning}, {"status", luaB_costatus}, {"wrap", luaB_cowrap}, {"yield", luaB_yield}, {NULL, NULL} }; /* }====================================================== */ static void auxopen (lua_State *L, const char *name, lua_CFunction f, lua_CFunction u) { lua_pushcfunction(L, u); lua_pushcclosure(L, f, 1); lua_setfield(L, -2, name); } static void base_open (lua_State *L) { /* set global _G */ lua_pushvalue(L, LUA_GLOBALSINDEX); lua_setglobal(L, "_G"); /* open lib into global table */ luaL_register(L, "_G", base_funcs); lua_pushliteral(L, LUA_VERSION); lua_setglobal(L, "_VERSION"); /* set global _VERSION */ /* `ipairs' and `pairs' need auxliliary functions as upvalues */ auxopen(L, "ipairs", luaB_ipairs, ipairsaux); auxopen(L, "pairs", luaB_pairs, luaB_next); /* `newproxy' needs a weaktable as upvalue */ lua_createtable(L, 0, 1); /* new table `w' */ lua_pushvalue(L, -1); /* `w' will be its own metatable */ lua_setmetatable(L, -2); lua_pushliteral(L, "kv"); lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */ lua_pushcclosure(L, luaB_newproxy, 1); lua_setglobal(L, "newproxy"); /* set global `newproxy' */ } LUALIB_API int luaopen_base (lua_State *L) { base_open(L); luaL_register(L, LUA_COLIBNAME, co_funcs); return 2; } 56' href='#n56'>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 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
/*******************************************************************************
 * Copyright (c) 2000, 2010 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.swt.browser;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;

import org.eclipse.swt.*;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.internal.*;
import org.eclipse.swt.internal.carbon.*;
import org.eclipse.swt.internal.cocoa.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

class WebKit extends WebBrowser {
	
	/* Objective-C WebView delegate */
	int delegate;
	
	/* Carbon HIView handle */
	int webViewHandle, webView;
	int windowBoundsHandler;
	int preferences;
	
	boolean loadingText, hasNewFocusElement, untrustedText;
	String lastHoveredLinkURL, lastNavigateURL;
	String html;
	int identifier;
	int resourceCount;
	int lastMouseMoveX, lastMouseMoveY;
	String url = ""; //$NON-NLS-1$
	Point location;
	Point size;
	boolean statusBar = true, toolBar = true, ignoreDispose;
	//TEMPORARY CODE
//	boolean doit;

	static boolean Initialized;
	static Callback Callback3, Callback7;

	static final int MIN_SIZE = 16;
	static final int MAX_PROGRESS = 100;
	static final String WebElementLinkURLKey = "WebElementLinkURL"; //$NON-NLS-1$
	static final String AGENT_STRING = "Safari/412.0"; /* Safari version on OSX 10.4 initial release */ //$NON-NLS-1$
	static final String URI_FILEROOT = "file:///"; //$NON-NLS-1$
	static final String PROTOCOL_FILE = "file://"; //$NON-NLS-1$
	static final String PROTOCOL_HTTP = "http://"; //$NON-NLS-1$
	static final String URI_APPLEWEBDATA = "applewebdata://"; //$NON-NLS-1$
	static final String ABOUT_BLANK = "about:blank"; //$NON-NLS-1$
	static final String HEADER_SETCOOKIE = "Set-Cookie"; //$NON-NLS-1$
	static final String POST = "POST"; //$NON-NLS-1$
	static final String USER_AGENT = "user-agent"; //$NON-NLS-1$
	static final String ADD_WIDGET_KEY = "org.eclipse.swt.internal.addWidget"; //$NON-NLS-1$
	static final String BROWSER_WINDOW = "org.eclipse.swt.browser.Browser.Window"; //$NON-NLS-1$
	static final String WEBKIT_EVENTS_FIX_KEY = "org.eclipse.swt.internal.webKitEventsFix"; //$NON-NLS-1$

	/* event strings */
	static final String DOMEVENT_KEYUP = "keyup"; //$NON-NLS-1$
	static final String DOMEVENT_KEYDOWN = "keydown"; //$NON-NLS-1$
	static final String DOMEVENT_MOUSEDOWN = "mousedown"; //$NON-NLS-1$
	static final String DOMEVENT_MOUSEUP = "mouseup"; //$NON-NLS-1$
	static final String DOMEVENT_MOUSEMOVE = "mousemove"; //$NON-NLS-1$
	static final String DOMEVENT_MOUSEWHEEL = "mousewheel"; //$NON-NLS-1$
	static final String DOMEVENT_FOCUSIN = "DOMFocusIn"; //$NON-NLS-1$
	static final String DOMEVENT_FOCUSOUT = "DOMFocusOut"; //$NON-NLS-1$

	static {
		Cocoa.WebInitForCarbon();

		NativeClearSessions = new Runnable() {
			public void run() {
				int storage = Cocoa.objc_msgSend (Cocoa.C_NSHTTPCookieStorage, Cocoa.S_sharedHTTPCookieStorage);
				int cookies = Cocoa.objc_msgSend (storage, Cocoa.S_cookies);
				int count = Cocoa.objc_msgSend (cookies, Cocoa.S_count);
				for (int i = 0; i < count; i++) {
					int cookie = Cocoa.objc_msgSend (cookies, Cocoa.S_objectAtIndex, i);
					boolean isSession = Cocoa.objc_msgSend (cookie, Cocoa.S_isSessionOnly) != 0;
					if (isSession) {
						Cocoa.objc_msgSend (storage, Cocoa.S_deleteCookie, cookie);
					}
				}
			}
		};

		NativeGetCookie = new Runnable () {
			public void run () {
				int storage = Cocoa.objc_msgSend (Cocoa.C_NSHTTPCookieStorage, Cocoa.S_sharedHTTPCookieStorage);
				int urlString = createNSString (CookieUrl);
				int url = Cocoa.objc_msgSend (Cocoa.C_NSURL, Cocoa.S_URLWithString, urlString);
				OS.CFRelease (urlString);
				int cookies = Cocoa.objc_msgSend (storage, Cocoa.S_cookiesForURL, url);
				int count = Cocoa.objc_msgSend (cookies, Cocoa.S_count);
				if (count == 0) return;

				int name = createNSString (CookieName);
				for (int i = 0; i < count; i++) {
					int current = Cocoa.objc_msgSend (cookies, Cocoa.S_objectAtIndex, i);
					int currentName = Cocoa.objc_msgSend (current, Cocoa.S_name);
					if (Cocoa.objc_msgSend (currentName, Cocoa.S_compare, name) == Cocoa.NSOrderedSame) {
						int value = Cocoa.objc_msgSend (current, Cocoa.S_value);
						int length = OS.CFStringGetLength (value);
						char[] buffer = new char[length];
						CFRange range = new CFRange ();
						range.length = length;
						OS.CFStringGetCharacters (value, range, buffer);
						CookieValue = new String (buffer);
						OS.CFRelease (name);
						return;
					}
				}
				OS.CFRelease (name);
			}
		};

		NativeSetCookie = new Runnable () {
			public void run () {
				int urlString = createNSString(CookieUrl);
				int url = Cocoa.objc_msgSend (Cocoa.C_NSURL, Cocoa.S_URLWithString, urlString);
				OS.CFRelease (urlString);

				int value = createNSString (CookieValue);
				int key = createNSString (HEADER_SETCOOKIE);
				int headers = Cocoa.objc_msgSend (Cocoa.C_NSMutableDictionary, Cocoa.S_dictionaryWithCapacity, 1);
				Cocoa.objc_msgSend (headers, Cocoa.S_setValue, value, key);
				OS.CFRelease (key);
				OS.CFRelease (value);

				int cookies = Cocoa.objc_msgSend (Cocoa.C_NSHTTPCookie, Cocoa.S_cookiesWithResponseHeaderFields, headers, url);
				if (Cocoa.objc_msgSend (cookies, Cocoa.S_count) == 0) return;
				int cookie = Cocoa.objc_msgSend (cookies, Cocoa.S_objectAtIndex, 0);
				int storage = Cocoa.objc_msgSend (Cocoa.C_NSHTTPCookieStorage, Cocoa.S_sharedHTTPCookieStorage);
				Cocoa.objc_msgSend (storage, Cocoa.S_setCookie, cookie);
				CookieResult = true;
			}
		};

		if (NativePendingCookies != null) {
			SetPendingCookies (NativePendingCookies);
		}
		NativePendingCookies = null;
	}

public void create (Composite parent, int style) {
	/*
	* Note.  Loading the webkit bundle on Jaguar causes a crash.
	* The workaround is to detect any OS prior to 10.30 and fail
	* without crashing.
	*/
	if (OS.VERSION < 0x1030) {
		browser.dispose();
		SWT.error(SWT.ERROR_NO_HANDLES);
	}
	
	/*
	* Bug in WebKit on OSX 10.5 (Leopard) only.  VoiceOver no longer follows focus when
	* HIWebViewCreate is used to create a WebView.  The VoiceOver cursor (activated by
	* Control+Alt+arrows) continues to work, but keyboard focus is not tracked.  The fix
	* is to create the WebView with HICocoaViewCreate (api introduced in OSX 10.5) when
	* running on OSX 10.5.
	*/
	int outControl[] = new int[1];
	if (OS.VERSION >= 0x1050) {
		webView = Cocoa.objc_msgSend(Cocoa.objc_msgSend(Cocoa.C_WebView, Cocoa.S_alloc), Cocoa.S_initWithFrame_frameName_groupName, new NSRect(), 0, 0);
		if (webView != 0) {
			Cocoa.HICocoaViewCreate(webView, 0, outControl);
			webViewHandle = outControl[0];
			Cocoa.objc_msgSend(webView, Cocoa.S_release);
		}
	} else {
		Cocoa.HIWebViewCreate(outControl);
		webViewHandle = outControl[0];
		if (webViewHandle != 0) {
			webView = Cocoa.HIWebViewGetWebView(webViewHandle);
		}
	}
	if (webViewHandle == 0) {
		browser.dispose();
		SWT.error(SWT.ERROR_NO_HANDLES);
	}

	Display display = browser.getDisplay();
	display.setData(ADD_WIDGET_KEY, new Object[] {new Integer(webViewHandle), browser});

	/*
	* WebKit's DOM listener api became functional in OSX 10.4.  If OSX 10.4 or 
	* later is detected then override the default event mechanism to not send key
	* events and some mouse events so that the browser can send them by listening
	* to the DOM instead.
	*/
	if (!(OS.VERSION < 0x1040)) {
		browser.setData(WEBKIT_EVENTS_FIX_KEY);
	}

	/*
	* Bug in WebKit.  For some reason, every application must contain
	* a visible window that has never had a WebView or mouse move events
	* are not delivered.  This seems to happen after a browser has been
	* either hidden or disposed in any window.  The fix is to create a
	* single transparent overlay window that is disposed when the display
	* is disposed.
	*/
	if (display.getData(BROWSER_WINDOW) == null) {
		Rect bounds = new Rect ();
		OS.SetRect (bounds, (short) 0, (short) 0, (short) 1, (short) 1);
		final int[] outWindow = new int[1];
		OS.CreateNewWindow(OS.kOverlayWindowClass, 0, bounds, outWindow);
		OS.ShowWindow(outWindow[0]);
		OS.HIObjectSetAccessibilityIgnored (outWindow[0], true);
		display.disposeExec(new Runnable() {
			public void run() {
				if (outWindow[0] != 0) {
					OS.DisposeWindow(outWindow[0]);
				}
				outWindow[0] = 0;
			}
		});
		display.setData(BROWSER_WINDOW, outWindow);
	}
	
	/*
	* Bug in WebKit. The WebView does not draw properly if it is embedded as
	* sub view of the browser handle.  The fix is to add the web view to the
	* window root control and resize it on top of the browser handle.
	* 
	* Note that when the browser is reparented, the web view has to
	* be reparented by hand by hooking kEventControlOwningWindowChanged.
	*/
	int window = OS.GetControlOwner(browser.handle);
	int[] contentView = new int[1];
	OS.HIViewFindByID(OS.HIViewGetRoot(window), OS.kHIViewWindowContentID(), contentView);
	OS.HIViewAddSubview(contentView[0], webViewHandle);
	OS.HIViewChangeFeatures(webViewHandle, OS.kHIViewFeatureIsOpaque, 0);

	/*
	* Bug in WebKit. The WebView does not receive mouse and key events when it is added
	* to a visible top window.  It is assumed that WebKit hooks its own event listener
	* when the top window emits the kEventWindowShown event. The workaround is to send a
	* fake kEventWindowShown event to the top window after the WebView has been added
	* to the HIView (after the top window is visible) to give WebKit a chance to hook
	* events.
	*/
	OS.HIViewSetVisible(webViewHandle, true);	
	if (browser.getShell().isVisible()) {
		int[] showEvent = new int[1];
		OS.CreateEvent(0, OS.kEventClassWindow, OS.kEventWindowShown, 0.0, OS.kEventAttributeUserEvent, showEvent);
		OS.SetEventParameter(showEvent[0], OS.kEventParamDirectObject, OS.typeWindowRef, 4, new int[] {OS.GetControlOwner(browser.handle)});
		OS.SendEventToEventTarget(showEvent[0], OS.GetWindowEventTarget(window));
		if (showEvent[0] != 0) OS.ReleaseEvent(showEvent[0]);
	}

	/*
	* This code is intentionally commented. Setting a group name is the right thing
	* to do in order to avoid multiple open window requests. For some reason, WebKit
	* crashes when requested to reopen the same window if that window was previously
	* closed. This may be because that window was not correctly closed. 
	*/	
//	String groupName = "MyDocument"; //$NON-NLS-1$
//	int length = groupName.length();
//	char[] buffer = new char[length];
//	groupName.getChars(0, length, buffer, 0);
//	int groupNameString = OS.CFStringCreateWithCharacters(0, buffer, length);
//	// [webView setGroupName:@"MyDocument"];
//	WebKit.objc_msgSend(webView, WebKit.S_setGroupName, groupNameString);
//	OS.CFRelease(groupNameString);
	
	final int notificationCenter = Cocoa.objc_msgSend(Cocoa.C_NSNotificationCenter, Cocoa.S_defaultCenter);

	Listener listener = new Listener() {
		public void handleEvent(Event e) {
			switch (e.type) {
				case SWT.Dispose: {
					/* make this handler run after other dispose listeners */
					if (ignoreDispose) {
						ignoreDispose = false;
						break;
					}
					ignoreDispose = true;
					browser.notifyListeners (e.type, e);
					e.type = SWT.NONE;

					/* invoke onbeforeunload handlers */
					if (!browser.isClosing && !browser.isDisposed()) {
						close (false);
					}

					OS.RemoveEventHandler(windowBoundsHandler);
					windowBoundsHandler = 0;

					e.display.setData(ADD_WIDGET_KEY, new Object[] {new Integer(webViewHandle), null});

					Cocoa.objc_msgSend(webView, Cocoa.S_setFrameLoadDelegate, 0);
					Cocoa.objc_msgSend(webView, Cocoa.S_setResourceLoadDelegate, 0);
					Cocoa.objc_msgSend(webView, Cocoa.S_setUIDelegate, 0);
					Cocoa.objc_msgSend(webView, Cocoa.S_setPolicyDelegate, 0);
					Cocoa.objc_msgSend(webView, Cocoa.S_setDownloadDelegate, 0);
					Cocoa.objc_msgSend(notificationCenter, Cocoa.S_removeObserver, delegate);
					
					Cocoa.objc_msgSend(delegate, Cocoa.S_release);
					OS.DisposeControl(webViewHandle);
					webView = webViewHandle = 0;
					html = null;
					lastHoveredLinkURL = lastNavigateURL = null;

					Enumeration elements = functions.elements ();
					while (elements.hasMoreElements ()) {
						((BrowserFunction)elements.nextElement ()).dispose (false);
					}
					functions = null;

					if (preferences != 0) {
						Cocoa.objc_msgSend (preferences, Cocoa.S_release);
					}
					preferences = 0;
					break;
				}
				case SWT.FocusIn: {
					hasNewFocusElement = true;
					OS.SetKeyboardFocus(OS.GetControlOwner(browser.handle), webViewHandle, (short)-1);
					break;
				}
			}
		}
	};
	browser.addListener(SWT.Dispose, listener);
	browser.addListener(SWT.FocusIn, listener);
	browser.addListener(SWT.KeyDown, listener); /* needed to make browser traversable */
	
	if (Callback3 == null) Callback3 = new Callback(this.getClass(), "eventProc3", 3); //$NON-NLS-1$
	int callback3Address = Callback3.getAddress();
	if (callback3Address == 0) SWT.error(SWT.ERROR_NO_MORE_CALLBACKS);

	int[] mask = new int[] {
		OS.kEventClassKeyboard, OS.kEventRawKeyDown,
		OS.kEventClassControl, OS.kEventControlDraw,
		OS.kEventClassControl, OS.kEventControlGetClickActivation,
		OS.kEventClassControl, OS.kEventControlSetCursor,
		OS.kEventClassTextInput, OS.kEventTextInputUnicodeForKeyEvent,
	};
	OS.InstallEventHandler(OS.GetControlEventTarget(webViewHandle), callback3Address, mask.length / 2, mask, webViewHandle, null);
	int[] mask1 = new int[] {
		OS.kEventClassControl, OS.kEventControlBoundsChanged,
		OS.kEventClassControl, OS.kEventControlVisibilityChanged,
		OS.kEventClassControl, OS.kEventControlOwningWindowChanged,
	};
	OS.InstallEventHandler(OS.GetControlEventTarget(browser.handle), callback3Address, mask1.length / 2, mask1, browser.handle, null);
	int[] mask2 = new int[] {
		OS.kEventClassWindow, OS.kEventWindowBoundsChanged,
	};
	int[] outRef = new int[1];
	OS.InstallEventHandler(OS.GetWindowEventTarget(window), callback3Address, mask2.length / 2, mask2, browser.handle, outRef);
	windowBoundsHandler = outRef[0];

	if (Callback7 == null) Callback7 = new Callback(this.getClass(), "eventProc7", 7); //$NON-NLS-1$
	int callback7Address = Callback7.getAddress();
	if (callback7Address == 0) SWT.error(SWT.ERROR_NO_MORE_CALLBACKS);
	
	// delegate = [[WebResourceLoadDelegate alloc] init eventProc];
	delegate = Cocoa.objc_msgSend(Cocoa.C_WebKitDelegate, Cocoa.S_alloc);
	delegate = Cocoa.objc_msgSend(delegate, Cocoa.S_initWithProc, callback7Address, webViewHandle);

	// [webView setFrameLoadDelegate:delegate];
	Cocoa.objc_msgSend(webView, Cocoa.S_setFrameLoadDelegate, delegate);
		
	// [webView setResourceLoadDelegate:delegate];
	Cocoa.objc_msgSend(webView, Cocoa.S_setResourceLoadDelegate, delegate);

	// [webView setUIDelegate:delegate];
	Cocoa.objc_msgSend(webView, Cocoa.S_setUIDelegate, delegate);
	
	/* register delegate for all notifications sent out from webview */
	Cocoa.objc_msgSend(notificationCenter, Cocoa.S_addObserver_selector_name_object, delegate, Cocoa.S_handleNotification, 0, webView);
	
	// [webView setPolicyDelegate:delegate];
	Cocoa.objc_msgSend(webView, Cocoa.S_setPolicyDelegate, delegate);

	// [webView setDownloadDelegate:delegate];
	Cocoa.objc_msgSend(webView, Cocoa.S_setDownloadDelegate, delegate);

	// [webView setApplicationNameForUserAgent:applicationName];
	int sHandle = createNSString(AGENT_STRING);
	Cocoa.objc_msgSend(webView, Cocoa.S_setApplicationNameForUserAgent, sHandle);
	OS.CFRelease(sHandle);

	if (OS.VERSION < 0x1050 && display.getActiveShell() == browser.getShell()) {
		Cocoa.objc_msgSend(Cocoa.objc_msgSend(webView, Cocoa.S_window), Cocoa.S_makeKeyWindow);
	}

	if (!Initialized) {
		Initialized = true;
		/* disable applets */
		int preferences = Cocoa.objc_msgSend(Cocoa.C_WebPreferences, Cocoa.S_standardPreferences);
		Cocoa.objc_msgSend(preferences, Cocoa.S_setJavaEnabled, 0);
	}
}

static int eventProc3(int nextHandler, int theEvent, int userData) {
	Widget widget = Display.getCurrent().findWidget(userData);
	if (widget instanceof Browser) {
		return ((WebKit)((Browser)widget).webBrowser).handleCallback(nextHandler, theEvent);
	}
	return OS.eventNotHandledErr;
}

static int eventProc7(int webview, int userData, int selector, int arg0, int arg1, int arg2, int arg3) {
	Widget widget = Display.getCurrent().findWidget(userData);
	if (widget instanceof Browser) {
		return ((WebKit)((Browser)widget).webBrowser).handleCallback(selector, arg0, arg1, arg2, arg3);
	}
	return 0;
}

static int createNSString(String string) {
	int length = string.length ();
	char[] buffer = new char[length];
	string.getChars (0, length, buffer, 0);
	return OS.CFStringCreateWithCharacters (0, buffer, length);
}

static String getString (int ptr) {
	int length = OS.CFStringGetLength (ptr);
	char[] buffer = new char[length];
	CFRange range = new CFRange ();
	range.length = length;
	OS.CFStringGetCharacters (ptr, range, buffer);
	return new String (buffer);
}

public boolean back() {
	html = null;
	return Cocoa.objc_msgSend(webView, Cocoa.S_goBack) != 0;
}

public boolean close () {
	return close (true);
}

boolean close (boolean showPrompters) {
	if (!jsEnabled) return true;

	String functionName = EXECUTE_ID + "CLOSE"; // $NON-NLS-1$
	StringBuffer buffer = new StringBuffer ("function "); // $NON-NLS-1$
	buffer.append (functionName);
	buffer.append ("(win) {\n"); // $NON-NLS-1$
	buffer.append ("var fn = win.onbeforeunload; if (fn != null) {try {var str = fn(); "); // $NON-NLS-1$
	if (showPrompters) {
		buffer.append ("if (str != null) { "); // $NON-NLS-1$
		buffer.append ("var result = window.external.callRunBeforeUnloadConfirmPanelWithMessage(str);"); // $NON-NLS-1$
		buffer.append ("if (!result) return false;}"); // $NON-NLS-1$
	}	
	buffer.append ("} catch (e) {}}"); // $NON-NLS-1$
	buffer.append ("try {for (var i = 0; i < win.frames.length; i++) {var result = "); // $NON-NLS-1$
	buffer.append (functionName);
	buffer.append ("(win.frames[i]); if (!result) return false;}} catch (e) {} return true;"); // $NON-NLS-1$
	buffer.append ("\n};"); // $NON-NLS-1$
	execute (buffer.toString ());

	Boolean result = (Boolean)evaluate ("return " + functionName +"(window);"); // $NON-NLS-1$ // $NON-NLS-2$
	if (result == null) return false;
	return result.booleanValue ();
}

public boolean execute(String script) {
	int frame = Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame);
	int context = Cocoa.objc_msgSend(frame, Cocoa.S_globalContext);

	byte[] bytes = null;
	try {
		bytes = (script + '\0').getBytes("UTF-8"); //$NON-NLS-1$
	} catch (UnsupportedEncodingException e) {
		bytes = (script + '\0').getBytes();
	}
	int scriptString = OS.JSStringCreateWithUTF8CString(bytes);

	try {
		bytes = (getUrl() + '\0').getBytes("UTF-8"); //$NON-NLS-1$
	} catch (UnsupportedEncodingException e) {
		bytes = (getUrl() + '\0').getBytes();
	}
	int urlString = OS.JSStringCreateWithUTF8CString(bytes);

	int result = OS.JSEvaluateScript(context, scriptString, 0, urlString, 0, null);
	OS.JSStringRelease(urlString);
	OS.JSStringRelease(scriptString);
	return result != 0;
}

public boolean forward() {
	html = null;
	return Cocoa.objc_msgSend(webView, Cocoa.S_goForward) != 0;
}

public String getBrowserType () {
	return "webkit"; //$NON-NLS-1$
}

public String getText() {
	int mainFrame = Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame);
	int dataSource = Cocoa.objc_msgSend(mainFrame, Cocoa.S_dataSource);
	if (dataSource == 0) return "";	//$NON-NLS-1$
	int representation = Cocoa.objc_msgSend(dataSource, Cocoa.S_representation);
	if (representation == 0) return "";	//$NON-NLS-1$
	int source = Cocoa.objc_msgSend(representation, Cocoa.S_documentSource);
	if (source == 0) return "";	//$NON-NLS-1$
	int length = OS.CFStringGetLength(source);
	char[] buffer = new char[length];
	CFRange range = new CFRange();
	range.length = length;
	OS.CFStringGetCharacters(source, range, buffer);
	return new String(buffer);
}

public String getUrl() {
	/* WebKit auto-navigates to about:blank at startup */
	if (url.length() == 0) return ABOUT_BLANK;

	return url;
}

int handleCallback(int nextHandler, int theEvent) {
	int eventKind = OS.GetEventKind(theEvent);
	switch (OS.GetEventClass(theEvent)) {
		case OS.kEventClassControl:
			switch (eventKind) {
				case OS.kEventControlGetClickActivation: {
					OS.SetEventParameter (theEvent, OS.kEventParamClickActivation, OS.typeClickActivationResult, 4, new int [] {OS.kActivateAndHandleClick});
					return OS.noErr;
				}
				case OS.kEventControlSetCursor: {
					return OS.noErr;
				}
				case OS.kEventControlDraw: {
					/*
					 * Bug on WebKit. The web view cannot be obscured by other views above it.
					 * This problem is specified in the apple documentation for HiWebViewCreate.
					 * The workaround is to don't draw the web view when it is not visible.
					 */
					if (!browser.isVisible ()) return OS.noErr;
					break;
				}
				case OS.kEventControlOwningWindowChanged: {
					/* Reparent the web view handler */
					int window = OS.GetControlOwner(browser.handle);
					int[] contentView = new int[1];
					OS.HIViewFindByID(OS.HIViewGetRoot(window), OS.kHIViewWindowContentID(), contentView);
					OS.HIViewAddSubview(contentView[0], webViewHandle);
					
					/* Reset the kEventWindowBoundsChanged handler */
					OS.RemoveEventHandler(windowBoundsHandler);
					int[] mask2 = new int[] {
						OS.kEventClassWindow, OS.kEventWindowBoundsChanged,
					};
					int[] outRef = new int[1];
					OS.InstallEventHandler(OS.GetWindowEventTarget(window), Callback3.getAddress(), mask2.length / 2, mask2, browser.handle, outRef);
					windowBoundsHandler = outRef[0];
					break;
				}
				case OS.kEventControlBoundsChanged:
				case OS.kEventControlVisibilityChanged: {
					/*
					 * Bug on WebKit. The web view cannot be obscured by other views above it.
					 * This problem is specified in the apple documentation for HiWebViewCreate.
					 * The workaround is to hook kEventControlVisibilityChanged on the browser
					 * and move the browser out of the screen when hidden and restore its bounds
					 * when shown.
					 */
					CGRect bounds = new CGRect();
					if (!browser.isVisible()) {
						bounds.x = bounds.y = -MIN_SIZE;
						bounds.width = bounds.height = MIN_SIZE;
						OS.HIViewSetFrame(webViewHandle, bounds);
					} else {
						OS.HIViewGetBounds(browser.handle, bounds);
						int[] contentView = new int[1];
						OS.HIViewFindByID(OS.HIViewGetRoot(OS.GetControlOwner(browser.handle)), OS.kHIViewWindowContentID(), contentView);
						OS.HIViewConvertRect(bounds, browser.handle, contentView[0]);
						/* 
						* Bug in WebKit.  For some reason, the web view will display incorrectly or
						* blank depending on its contents, if its size is set to a value smaller than
						* MIN_SIZE. It will not display properly even after the size is made larger.
						* The fix is to avoid setting sizes smaller than MIN_SIZE. 
						*/
						if (bounds.width <= MIN_SIZE) bounds.width = MIN_SIZE;
						if (bounds.height <= MIN_SIZE) bounds.height = MIN_SIZE;
						OS.HIViewSetFrame(webViewHandle, bounds);
					}
					break;
				}
			}
		case OS.kEventClassWindow:
			switch (eventKind) {
				case OS.kEventWindowBoundsChanged:
					/*
					 * Bug on WebKit. Resizing the height of a Shell containing a Browser at
					 * a fixed location causes the Browser to redraw at a wrong location.
					 * The web view is a HIView container that internally hosts
					 * a Cocoa NSView that uses a coordinates system with the origin at the
					 * bottom left corner of a window instead of the coordinates system used
					 * in Carbon that starts at the top left corner. The workaround is to
					 * reposition the web view every time the Shell of the Browser is resized.
					 * 
					 * Note the size should not be updated if the browser is hidden.
					 */
					if (browser.isVisible()) {
						CGRect oldBounds = new CGRect();
						OS.GetEventParameter (theEvent, OS.kEventParamOriginalBounds, OS.typeHIRect, null, CGRect.sizeof, null, oldBounds);
						CGRect bounds = new CGRect();
						OS.GetEventParameter (theEvent, OS.kEventParamCurrentBounds, OS.typeHIRect, null, CGRect.sizeof, null, bounds);
						if (oldBounds.height == bounds.height) break;
						OS.HIViewGetBounds(browser.handle, bounds);
						int[] contentView = new int[1];
						OS.HIViewFindByID(OS.HIViewGetRoot(OS.GetControlOwner(browser.handle)), OS.kHIViewWindowContentID(), contentView);
						OS.HIViewConvertRect(bounds, browser.handle, contentView[0]);
						/* 
						* Bug in WebKit.  For some reason, the web view will display incorrectly or
						* blank depending on its contents, if its size is set to a value smaller than
						* MIN_SIZE. It will not display properly even after the size is made larger.
						* The fix is to avoid setting sizes smaller than MIN_SIZE. 
						*/
						if (bounds.width <= MIN_SIZE) bounds.width = MIN_SIZE;
						if (bounds.height <= MIN_SIZE) bounds.height = MIN_SIZE;
						bounds.x++;
						/* Note that the bounds needs to change */
						OS.HIViewSetFrame(webViewHandle, bounds);
						bounds.x--;
						OS.HIViewSetFrame(webViewHandle, bounds);
					}
			}
		case OS.kEventClassKeyboard:
			switch (eventKind) {
				case OS.kEventRawKeyDown: {
					/*
					* Bug in WebKit. The WebView blocks the propagation of certain Carbon events
					* such as kEventRawKeyDown. On the Mac, Carbon events propagate from the
					* Focus Target Handler to the Control Target Handler, Window Target and finally
					* the Application Target Handler. It is assumed that WebView hooks its events
					* on the Window Target and does not pass kEventRawKeyDown to the next handler.
					* Since kEventRawKeyDown events never make it to the Application Target Handler,
					* the Application Target Handler never gets to emit kEventTextInputUnicodeForKeyEvent
					* used by SWT to send a SWT.KeyDown event.
					* The workaround is to hook kEventRawKeyDown on the Control Target Handler which gets
					* called before the WebView hook on the Window Target Handler. Then, forward this event
					* directly to the Application Target Handler. Note that if in certain conditions WebKit
					* does not block the kEventRawKeyDown, then multiple kEventTextInputUnicodeForKeyEvent
					* events might be generated as a result of this workaround.
					*/
					//TEMPORARY CODE
//					doit = false;
//					OS.SendEventToEventTarget(theEvent, OS.GetApplicationEventTarget());
//					if (!doit) return OS.noErr;

					int[] length = new int[1];
					int status = OS.GetEventParameter (theEvent, OS.kEventParamKeyUnicodes, OS.typeUnicodeText, null, 4, length, (char[])null);
					if (status == OS.noErr && length[0] != 0) {
						int[] modifiers = new int[1];
						OS.GetEventParameter (theEvent, OS.kEventParamKeyModifiers, OS.typeUInt32, null, 4, null, modifiers);
						char[] chars = new char[1];
						OS.GetEventParameter (theEvent, OS.kEventParamKeyUnicodes, OS.typeUnicodeText, null, 2, null, chars);
						if ((modifiers[0] & OS.cmdKey) != 0) {
							switch (chars[0]) {
								case 'v': {
									Cocoa.objc_msgSend (webView, Cocoa.S_paste);
									return OS.noErr;
								}
								case 'c': {
									Cocoa.objc_msgSend (webView, Cocoa.S_copy);
									return OS.noErr;
								}
								case 'x': {
									Cocoa.objc_msgSend (webView, Cocoa.S_cut);
									return OS.noErr;
								}
							}
						}
					}
					/*
					* Bug in Carbon.  OSX crashes if a HICocoaView is disposed during a key event,
					* presumably as a result of attempting to use it after its refcount has reached
					* 0.  The workaround is to temporarily add an extra ref to the view and its
					* ancestor while the DOM listener is handling the event, in case the
					* Browser gets disposed in a callback.
					*/
					int handle = webViewHandle, root = OS.HIViewGetSuperview (webViewHandle);
					OS.CFRetain (handle);
					OS.CFRetain (root);
					int result = OS.CallNextEventHandler (nextHandler, theEvent);
					OS.CFRelease (handle);
					OS.CFRelease (root);
					return result;
				}
			}
		case OS.kEventClassTextInput:
			switch (eventKind) {
				case OS.kEventTextInputUnicodeForKeyEvent: {
					/*
					* Note.  This event is received from the Window Target therefore after it was received
					* by the Focus Target. The SWT.KeyDown event is sent by SWT on the Focus Target. If it
					* is received here, then the SWT.KeyDown doit flag must have been left to the value
					* true.  For package visibility reasons we cannot access the doit flag directly.
					* 
					* Sequence of events when the user presses a key down
					* 
					* .Control Target - kEventRawKeyDown
					* 	.forward to ApplicationEventTarget
					* 		.Focus Target kEventTextInputUnicodeForKeyEvent - SWT emits SWT.KeyDown - 
					* 			blocks further propagation if doit false. Browser does not know directly about
					* 			the doit flag value.
					* 			.Window Target kEventTextInputUnicodeForKeyEvent - if received, Browser knows 
					* 			SWT.KeyDown is not blocked and event should be sent to WebKit
					*  Return from Control Target - kEventRawKeyDown: let the event go to WebKit if doit true 
					*  (eventNotHandledErr) or stop it (noErr).
					*/
					//TEMPORARY CODE
//					doit = true;
					break;
				}
			}
	}
	return OS.eventNotHandledErr;
}

/* Here we dispatch all WebView upcalls. */
int handleCallback(int selector, int arg0, int arg1, int arg2, int arg3) {
	int ret = 0;
	// for meaning of selector see WebKitDelegate methods in webkit.c
	switch (selector) {
		case 1: didFailProvisionalLoadWithError(arg0, arg1); break;
		case 2: didFinishLoadForFrame(arg0); break;
		case 3: didReceiveTitle(arg0, arg1); break;
		case 4: didStartProvisionalLoadForFrame(arg0); break;
		case 5: didFinishLoadingFromDataSource(arg0, arg1); break;
		case 6: didFailLoadingWithError(arg0, arg1, arg2); break;
		case 7: ret = identifierForInitialRequest(arg0, arg1); break;
		case 8: ret = willSendRequest(arg0, arg1, arg2, arg3); break;
		case 9: handleNotification(arg0); break;
		case 10: didCommitLoadForFrame(arg0); break;
		case 11: ret = createWebViewWithRequest(arg0); break;
		case 12: webViewShow(arg0); break;
		case 13: setFrame(arg0); break;
		case 14: webViewClose(); break;
		case 15: ret = contextMenuItemsForElement(arg0, arg1); break;
		case 16: setStatusBarVisible(arg0); break;
		case 17: setResizable(arg0); break;
		case 18: setToolbarsVisible(arg0); break;
		case 19: decidePolicyForMIMEType(arg0, arg1, arg2, arg3); break;
		case 20: decidePolicyForNavigationAction(arg0, arg1, arg2, arg3); break;
		case 21: decidePolicyForNewWindowAction(arg0, arg1, arg2, arg3); break;
		case 22: unableToImplementPolicyWithError(arg0, arg1); break;
		case 23: setStatusText(arg0); break;
		case 24: webViewFocus(); break;
		case 25: webViewUnfocus(); break;
		case 26: runJavaScriptAlertPanelWithMessage(arg0); break;
		case 27: ret = runJavaScriptConfirmPanelWithMessage(arg0); break;
		case 28: runOpenPanelForFileButtonWithResultListener(arg0); break;
		case 29: decideDestinationWithSuggestedFilename(arg0, arg1); break;
		case 30: mouseDidMoveOverElement(arg0, arg1); break;
		case 31: didChangeLocationWithinPageForFrame(arg0); break;
		case 32: handleEvent(arg0); break;
		case 33: windowScriptObjectAvailable(arg0); break;
		case 34: ret = callJava(arg0, arg1, arg2); break;
		case 35: didReceiveAuthenticationChallengefromDataSource(arg0, arg1, arg2); break;
		case 36: ret = runBeforeUnloadConfirmPanelWithMessage(arg0, arg1); break;
		case 37: ret = callRunBeforeUnloadConfirmPanelWithMessage(arg0, arg1); break;
		case 38: createPanelDidEnd(arg0, arg1, arg2); break;
	}
	return ret;
}

public boolean isBackEnabled() {
	return Cocoa.objc_msgSend(webView, Cocoa.S_canGoBack) != 0;
}

public boolean isForwardEnabled() {
	return Cocoa.objc_msgSend(webView, Cocoa.S_canGoForward) != 0;
}

public void refresh() {
	html = null;
	Cocoa.objc_msgSend(webView, Cocoa.S_reload, 0);
}

public boolean setText(String html, boolean trusted) {
	/*
	* If this.html is not null then the about:blank page is already being loaded,
	* so no navigate is required.  Just set the html that is to be shown.
	*/
	boolean blankLoading = this.html != null;
	this.html = html;
	untrustedText = !trusted;
	if (blankLoading) return true;

	int str = createNSString(ABOUT_BLANK);
	int inURL = Cocoa.objc_msgSend(Cocoa.C_NSURL, Cocoa.S_URLWithString, str); /* autoreleased */
	OS.CFRelease (str);
	int request = Cocoa.objc_msgSend(Cocoa.C_NSURLRequest, Cocoa.S_requestWithURL, inURL);
	int mainFrame = Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame);
	Cocoa.objc_msgSend(mainFrame, Cocoa.S_loadRequest, request);
	return true;
}

public boolean setUrl(String url, String postData, String[] headers) {
	html = null;

	if (url.indexOf('/') == 0) {
		url = PROTOCOL_FILE + url;
	} else if (url.indexOf(':') == -1) {
		url = PROTOCOL_HTTP + url;
	}

	int inURL = 0;
	int str = createNSString(url);
	if (str != 0) {
		char[] unescapedChars = new char[] {'%', '#'};
		int unescapedStr = OS.CFStringCreateWithCharacters(0, unescapedChars, unescapedChars.length);
		int escapedStr = OS.CFURLCreateStringByAddingPercentEscapes(OS.kCFAllocatorDefault, str, unescapedStr, 0, OS.kCFStringEncodingUTF8);
		if (escapedStr != 0) {
			inURL = OS.CFURLCreateWithString(OS.kCFAllocatorDefault, escapedStr, 0);
			OS.CFRelease(escapedStr);
		}
		if (unescapedStr != 0) OS.CFRelease(unescapedStr);
		OS.CFRelease(str);
	}
	if (inURL == 0) return false;

	int request = Cocoa.objc_msgSend(Cocoa.C_NSMutableURLRequest, Cocoa.S_requestWithURL, inURL);
	OS.CFRelease(inURL);

	if (postData != null) {
		int post = createNSString(POST);
		Cocoa.objc_msgSend(request, Cocoa.S_setHTTPMethod, post);
		OS.CFRelease (post);
		byte[] bytes = postData.getBytes();
		int data = Cocoa.objc_msgSend(Cocoa.C_NSData, Cocoa.S_dataWithBytes, bytes, bytes.length);
		Cocoa.objc_msgSend(request, Cocoa.S_setHTTPBody, data);
	}
	if (headers != null) {
		for (int i = 0; i < headers.length; i++) {
			String current = headers[i];
			if (current != null) {
				int index = current.indexOf(':');
				if (index != -1) {
					String key = current.substring(0, index).trim();
					String value = current.substring(index + 1).trim();
					if (key.length() > 0 && value.length() > 0) {
						if (key.equalsIgnoreCase(USER_AGENT)) {
							/*
							* Feature of WebKit.  The user-agent header value cannot be overridden
							* here.  The workaround is to temporarily set the value on the WebView
							* and then remove it after the loading of the request has begun.
							*/
							int string = createNSString(value);
							Cocoa.objc_msgSend(webView, Cocoa.S_setCustomUserAgent, string);
							OS.CFRelease (string);
						} else {
							int keyString = createNSString(key);
							int valueString = createNSString(value);
							Cocoa.objc_msgSend(request, Cocoa.S_setValueForHTTPHeaderField, valueString, keyString);
							OS.CFRelease (valueString);
							OS.CFRelease (keyString);
						}
					}
				}
			}
		}
	}

	int mainFrame = Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame);
	Cocoa.objc_msgSend(mainFrame, Cocoa.S_loadRequest, request);
	Cocoa.objc_msgSend(webView, Cocoa.S_setCustomUserAgent, 0);
	return true;
}

public void stop() {
	html = null;
	Cocoa.objc_msgSend(webView, Cocoa.S_stopLoading, 0);
}

boolean translateMnemonics() {
	return false;
}

/* WebFrameLoadDelegate */
void didChangeLocationWithinPageForFrame(int frame) {
	//id url= [[[[frame provisionalDataSource] request] URL] absoluteString];
	int dataSource = Cocoa.objc_msgSend(frame, Cocoa.S_dataSource);
	int request = Cocoa.objc_msgSend(dataSource, Cocoa.S_request);
	int url = Cocoa.objc_msgSend(request, Cocoa.S_URL);
	int s = Cocoa.objc_msgSend(url, Cocoa.S_absoluteString);
	int length = OS.CFStringGetLength(s);
	if (length == 0) return;
	char[] buffer = new char[length];
	CFRange range = new CFRange();
	range.length = length;
	OS.CFStringGetCharacters(s, range, buffer);
	String url2 = new String(buffer);
	/*
	 * If the URI indicates that the page is being rendered from memory
	 * (via setText()) then set it to about:blank to be consistent with IE.
	 */
	if (url2.equals (URI_FILEROOT)) {
		url2 = ABOUT_BLANK;
	} else {
		length = URI_FILEROOT.length ();
		if (url2.startsWith (URI_FILEROOT) && url2.charAt (length) == '#') {
			url2 = ABOUT_BLANK + url2.substring (length);
		}
	}

	final Display display = browser.getDisplay();
	boolean top = frame == Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame);
	if (top) {
		StatusTextEvent statusText = new StatusTextEvent(browser);
		statusText.display = display;
		statusText.widget = browser;
		statusText.text = url2;
		for (int i = 0; i < statusTextListeners.length; i++) {
			statusTextListeners[i].changed(statusText);
		}
	}
	LocationEvent location = new LocationEvent(browser);
	location.display = display;
	location.widget = browser;
	location.location = url2;
	location.top = top;
	for (int i = 0; i < locationListeners.length; i++) {
		locationListeners[i].changed(location);
	}
}

void didFailProvisionalLoadWithError(int error, int frame) {
	if (frame == Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame)) {
		/*
		* Feature on WebKit.  The identifier is used here as a marker for the events 
		* related to the top frame and the URL changes related to that top frame as 
		* they should appear on the location bar of a browser.  It is expected to reset
		* the identifier to 0 when the event didFinishLoadingFromDataSource related to 
		* the identifierForInitialRequest event is received.  However, WebKit fires
		* the didFinishLoadingFromDataSource event before the entire content of the
		* top frame is loaded.  It is possible to receive multiple willSendRequest 
		* events in this interval, causing the Browser widget to send unwanted
		* Location.changing events.  For this reason, the identifier is reset to 0
		* when the top frame has either finished loading (didFinishLoadForFrame
		* event) or failed (didFailProvisionalLoadWithError).
		*/
		identifier = 0;
	}

	int errorCode = Cocoa.objc_msgSend(error, Cocoa.S_code);
	if (Cocoa.NSURLErrorBadURL < errorCode) return;

	int failingURL = 0;
	int info = Cocoa.objc_msgSend(error, Cocoa.S_userInfo);
	if (info != 0) {
		int keyString = createNSString("NSErrorFailingURLKey"); //$NON-NLS-1$
		failingURL = Cocoa.objc_msgSend(info, Cocoa.S_valueForKey, keyString);
		OS.CFRelease(keyString);
	}

	if (failingURL != 0 && Cocoa.NSURLErrorServerCertificateNotYetValid <= errorCode && errorCode <= Cocoa.NSURLErrorSecureConnectionFailed) {
		/* handle invalid certificate error */
		int keyString = createNSString("NSErrorPeerCertificateChainKey"); //$NON-NLS-1$
		int certificates = Cocoa.objc_msgSend(info, Cocoa.S_objectForKey, keyString);
		OS.CFRelease(keyString);

		int[] policySearch = new int[1];
		int[] policyRef = new int[1];
		int[] trustRef = new int[1];
		boolean success = false;
		int result = OS.SecPolicySearchCreate(OS.CSSM_CERT_X_509v3, 0, 0, policySearch);
		if (result == 0 && policySearch[0] != 0) {
			result = OS.SecPolicySearchCopyNext(policySearch[0], policyRef);
			if (result == 0 && policyRef[0] != 0) {
				result = OS.SecTrustCreateWithCertificates(certificates, policyRef[0], trustRef);
				if (result == 0 && trustRef[0] != 0) {
					int panel = Cocoa.objc_msgSend(Cocoa.C_SFCertificateTrustPanel, Cocoa.S_sharedCertificateTrustPanel);
					String failingUrlString = getString(Cocoa.objc_msgSend(failingURL, Cocoa.S_absoluteString));
					String message = Compatibility.getMessage("SWT_InvalidCert_Message", new Object[] {failingUrlString}); //$NON-NLS-1$
					int nsString = createNSString(Compatibility.getMessage("SWT_Cancel")); //$NON-NLS-1$
					Cocoa.objc_msgSend(panel, Cocoa.S_setAlternateButtonTitle, nsString);
					OS.CFRelease(nsString);
					Cocoa.objc_msgSend(panel, Cocoa.S_setShowsHelp, 1);
					Cocoa.objc_msgSend(failingURL, Cocoa.S_retain);
					int window = Cocoa.objc_msgSend(webView, Cocoa.S_window);
					nsString = createNSString(message);
					Cocoa.objc_msgSend(panel, Cocoa.S_beginSheetForWindow, window, delegate, Cocoa.S_createPanelDidEnd, failingURL, trustRef[0], nsString);
					OS.CFRelease(nsString);
					success = true;
				}
			}
		}

		if (trustRef[0] != 0) OS.CFRelease(trustRef[0]);
		if (policyRef[0] != 0) OS.CFRelease(policyRef[0]);
		if (policySearch[0] != 0) OS.CFRelease(policySearch[0]);
		if (success) return;
	}

	/* handle other types of errors */
	int description = Cocoa.objc_msgSend(error, Cocoa.S_localizedDescription);
	if (description != 0) {
		String descriptionString = getString(description);
		String message = failingURL != 0 ? getString(Cocoa.objc_msgSend(failingURL, Cocoa.S_absoluteString)) + "\n\n" : ""; //$NON-NLS-1$ //$NON-NLS-2$
		message += Compatibility.getMessage ("SWT_Page_Load_Failed", new Object[] {descriptionString}); //$NON-NLS-1$
		MessageBox messageBox = new MessageBox(browser.getShell(), SWT.OK | SWT.ICON_ERROR);
		messageBox.setMessage(message);
		messageBox.open();
	}
}

void createPanelDidEnd(int sheet, int returnCode, int contextInfo) {
	Cocoa.objc_msgSend(contextInfo, Cocoa.S_autorelease);
	if (returnCode != Cocoa.NSFileHandlingPanelOKButton) return;	/* nothing more to do */

	int /*long*/ method = Cocoa.class_getClassMethod(Cocoa.C_NSURLRequest, Cocoa.S_setAllowsAnyHTTPSCertificate);
	if (method != 0) {
		int host = Cocoa.objc_msgSend(contextInfo, Cocoa.S_host);
		int urlString = Cocoa.objc_msgSend(contextInfo, Cocoa.S_absoluteString);
		Cocoa.objc_msgSend(Cocoa.C_NSURLRequest, Cocoa.S_setAllowsAnyHTTPSCertificate, 1, host);
		setUrl(getString(urlString), null, null);
	}
}

void didFinishLoadForFrame(int frame) {
	if (frame == Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame)) {
		/*
		 * If html is not null then there is html from a previous setText() call
		 * waiting to be set into the about:blank page once it has completed loading. 
		 */
		if (html != null) {
			if (getUrl().startsWith(ABOUT_BLANK)) {
				loadingText = true;
				int htmlString = createNSString(html);
				int urlString;
				if (untrustedText) {
					urlString = createNSString(ABOUT_BLANK);
				} else {
					urlString = createNSString(URI_FILEROOT);
				}
				int url = Cocoa.objc_msgSend(Cocoa.C_NSURL, Cocoa.S_URLWithString, urlString); /* autoreleased */
				int mainFrame = Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame);
				Cocoa.objc_msgSend(mainFrame, Cocoa.S_loadHTMLStringBaseURL, htmlString, url);
				OS.CFRelease(urlString);
				OS.CFRelease(htmlString);
				html = null;
			}
		}

		/*
		* The loadHTMLStringBaseURL invocation above will trigger a second didFinishLoadForFrame
		* callback when it is completed.  If text was just set into the browser then wait
		* for this second callback to come before sending the title or completed events.
		*/
		if (!loadingText) {
			/*
			* To be consistent with other platforms a title event should be fired when a
			* page has completed loading.  A page with a <title> tag will do this
			* automatically when the didReceiveTitle callback is received.  However a page
			* without a <title> tag will not do this by default, so fire the event
			* here with the page's url as the title.
			*/
			final Display display = browser.getDisplay();
			int dataSource = Cocoa.objc_msgSend(frame, Cocoa.S_dataSource);
			if (dataSource != 0) {
				int title = Cocoa.objc_msgSend(dataSource, Cocoa.S_pageTitle);
				if (title == 0) {	/* page has no title */
					final TitleEvent newEvent = new TitleEvent(browser);
					newEvent.display = display;
					newEvent.widget = browser;
					newEvent.title = getUrl();
					for (int i = 0; i < titleListeners.length; i++) {
						titleListeners[i].changed(newEvent);
					}
					if (browser.isDisposed()) return;
				}
			}

			ProgressEvent progress = new ProgressEvent(browser);
			progress.display = display;
			progress.widget = browser;
			progress.current = MAX_PROGRESS;
			progress.total = MAX_PROGRESS;
			for (int i = 0; i < progressListeners.length; i++) {
				progressListeners[i].completed(progress);
			}
		}
		loadingText = false;
		if (browser.isDisposed()) return;

		/*
		* Feature on WebKit.  The identifier is used here as a marker for the events 
		* related to the top frame and the URL changes related to that top frame as 
		* they should appear on the location bar of a browser.  It is expected to reset
		* the identifier to 0 when the event didFinishLoadingFromDataSource related to 
		* the identifierForInitialRequest event is received.  Howeever, WebKit fires
		* the didFinishLoadingFromDataSource event before the entire content of the
		* top frame is loaded.  It is possible to receive multiple willSendRequest 
		* events in this interval, causing the Browser widget to send unwanted
		* Location.changing events.  For this reason, the identifier is reset to 0
		* when the top frame has either finished loading (didFinishLoadForFrame
		* event) or failed (didFailProvisionalLoadWithError).
		*/
		identifier = 0;
	}
}

void hookDOMFocusListeners(int frame) {
	/*
	* These listeners only need to be hooked for OSX 10.4 (Tiger).  The WebKit on
	* OSX < 10.4 does not send these DOM events, and tab traversals that exit
	* WebKit are handled as of OSX 10.5 as a result of using HICocoaViewCreate,
	* which makes these listeners unnecessary.
	*/
	if (!(0x1040 <= OS.VERSION && OS.VERSION < 0x1050)) return;

	int document = Cocoa.objc_msgSend(frame, Cocoa.S_DOMDocument);
	if (document == 0) return;

	int ptr = createNSString(DOMEVENT_FOCUSIN);
	Cocoa.objc_msgSend(document, Cocoa.S_addEventListener, ptr, delegate, 0);
	OS.CFRelease(ptr);

	ptr = createNSString(DOMEVENT_FOCUSOUT);
	Cocoa.objc_msgSend(document, Cocoa.S_addEventListener, ptr, delegate, 0);
	OS.CFRelease(ptr);
}
	
void hookDOMKeyListeners(int frame) {
	/*
	* WebKit's DOM listener api became functional in OSX 10.4, so if an earlier
	* version than this is detected then do not hook the DOM listeners.
	*/
	if (OS.VERSION < 0x1040) return;

	int document = Cocoa.objc_msgSend(frame, Cocoa.S_DOMDocument);
	if (document == 0) return;

	int ptr = createNSString(DOMEVENT_KEYDOWN);
	Cocoa.objc_msgSend(document, Cocoa.S_addEventListener, ptr, delegate, 0);
	OS.CFRelease(ptr);

	ptr = createNSString(DOMEVENT_KEYUP);
	Cocoa.objc_msgSend(document, Cocoa.S_addEventListener, ptr, delegate, 0);
	OS.CFRelease(ptr);
}

void hookDOMMouseListeners(int frame) {
	/*
	* WebKit's DOM listener api became functional in OSX 10.4, so if an earlier
	* version than this is detected then do not hook the DOM listeners.
	*/
	if (OS.VERSION < 0x1040) return;

	int document = Cocoa.objc_msgSend(frame, Cocoa.S_DOMDocument);
	if (document == 0) return;

	int ptr = createNSString(DOMEVENT_MOUSEDOWN);
	Cocoa.objc_msgSend(document, Cocoa.S_addEventListener, ptr, delegate, 0);
	OS.CFRelease(ptr);

	ptr = createNSString(DOMEVENT_MOUSEUP);
	Cocoa.objc_msgSend(document, Cocoa.S_addEventListener, ptr, delegate, 0);
	OS.CFRelease(ptr);

	ptr = createNSString(DOMEVENT_MOUSEMOVE);
	Cocoa.objc_msgSend(document, Cocoa.S_addEventListener, ptr, delegate, 0);
	OS.CFRelease(ptr);

	ptr = createNSString(DOMEVENT_MOUSEWHEEL);
	Cocoa.objc_msgSend(document, Cocoa.S_addEventListener, ptr, delegate, 0);
	OS.CFRelease(ptr);
}

void didReceiveTitle(int title, int frame) {
	if (frame == Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame)) {
		int length = OS.CFStringGetLength(title);
		char[] buffer = new char[length];
		CFRange range = new CFRange();
		range.length = length;
		OS.CFStringGetCharacters(title, range, buffer);
		String newTitle = new String(buffer);
		TitleEvent newEvent = new TitleEvent(browser);
		newEvent.display = browser.getDisplay();
		newEvent.widget = browser;
		newEvent.title = newTitle;
		for (int i = 0; i < titleListeners.length; i++) {
			titleListeners[i].changed(newEvent);
		}
	}
}

void didStartProvisionalLoadForFrame(int frame) {
	/* 
	* This code is intentionally commented.  WebFrameLoadDelegate:didStartProvisionalLoadForFrame is
	* called before WebResourceLoadDelegate:willSendRequest and
	* WebFrameLoadDelegate:didCommitLoadForFrame.  The resource count is reset when didCommitLoadForFrame
	* is received for the top frame.
	*/
//	int webView = WebKit.HIWebViewGetWebView(webViewHandle);
//	if (frame == WebKit.objc_msgSend(webView, WebKit.S_mainFrame)) {
//		/* reset resource status variables */
//		resourceCount= 0;
//	}
}

void didCommitLoadForFrame(int frame) {
	//id url= [[[[frame provisionalDataSource] request] URL] absoluteString];
	int dataSource = Cocoa.objc_msgSend(frame, Cocoa.S_dataSource);
	int request = Cocoa.objc_msgSend(dataSource, Cocoa.S_request);
	int url = Cocoa.objc_msgSend(request, Cocoa.S_URL);
	int s = Cocoa.objc_msgSend(url, Cocoa.S_absoluteString);	
	int length = OS.CFStringGetLength(s);
	if (length == 0) return;
	char[] buffer = new char[length];
	CFRange range = new CFRange();
	range.length = length;
	OS.CFStringGetCharacters(s, range, buffer);
	String url2 = new String(buffer);
	/*
	 * If the URI indicates that the page is being rendered from memory
	 * (via setText()) then set it to about:blank to be consistent with IE.
	 */
	if (url2.equals (URI_FILEROOT)) {
		url2 = ABOUT_BLANK;
	} else {
		length = URI_FILEROOT.length ();
		if (url2.startsWith (URI_FILEROOT) && url2.charAt (length) == '#') {
			url2 = ABOUT_BLANK + url2.substring (length);
		}
	}

	final Display display = browser.getDisplay();
	boolean top = frame == Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame);
	if (top) {
		/* reset resource status variables */
		resourceCount = 0;		
		this.url = url2;

		/*
		* Each invocation of setText() causes didCommitLoadForFrame to be invoked twice,
		* once for the initial navigate to about:blank, and once for the auto-navigate
		* to about:blank that WebKit does when loadHTMLStringBaseURL is invoked.  If
		* this is the first didCommitLoadForFrame callback received for a setText()
		* invocation then do not send any events or re-install registered BrowserFunctions. 
		*/
		if (url2.startsWith(ABOUT_BLANK) && html != null) return;

		Enumeration elements = functions.elements ();
		while (elements.hasMoreElements ()) {
			BrowserFunction function = (BrowserFunction)elements.nextElement ();
			execute (function.functionString);
		}

		final ProgressEvent progress = new ProgressEvent(browser);
		progress.display = display;
		progress.widget = browser;
		progress.current = 1;
		progress.total = MAX_PROGRESS;
		for (int i = 0; i < progressListeners.length; i++) {
			progressListeners[i].changed(progress);
		}
		if (browser.isDisposed()) return;
		
		StatusTextEvent statusText = new StatusTextEvent(browser);
		statusText.display = display;
		statusText.widget = browser;
		statusText.text = url2;
		for (int i = 0; i < statusTextListeners.length; i++) {
			statusTextListeners[i].changed(statusText);
		}
		if (browser.isDisposed()) return;

		hookDOMKeyListeners(frame);
	}

	hookDOMFocusListeners(frame);
	hookDOMMouseListeners(frame);

	LocationEvent location = new LocationEvent(browser);
	location.display = display;
	location.widget = browser;
	location.location = url2;
	location.top = top;
	for (int i = 0; i < locationListeners.length; i++) {
		locationListeners[i].changed(location);
	}
}

void windowScriptObjectAvailable (int windowScriptObject) {
	int str = createNSString("external"); //$NON-NLS-1$
	if (str != 0) {
		Cocoa.objc_msgSend (windowScriptObject, Cocoa.S_setValue, delegate, str);
		OS.CFRelease (str);
	}
}

/* WebResourceLoadDelegate */

void didFinishLoadingFromDataSource(int identifier, int dataSource) {
	/*
	* Feature on WebKit.  The identifier is used here as a marker for the events 
	* related to the top frame and the URL changes related to that top frame as 
	* they should appear on the location bar of a browser.  It is expected to reset
	* the identifier to 0 when the event didFinishLoadingFromDataSource related to 
	* the identifierForInitialRequest event is received.  Howeever, WebKit fires
	* the didFinishLoadingFromDataSource event before the entire content of the
	* top frame is loaded.  It is possible to receive multiple willSendRequest 
	* events in this interval, causing the Browser widget to send unwanted
	* Location.changing events.  For this reason, the identifier is reset to 0
	* when the top frame has either finished loading (didFinishLoadForFrame
	* event) or failed (didFailProvisionalLoadWithError).
	*/
	// this code is intentionally commented
	//if (this.identifier == identifier) this.identifier = 0;
}

void didFailLoadingWithError(int identifier, int error, int dataSource) {
	/*
	* Feature on WebKit.  The identifier is used here as a marker for the events 
	* related to the top frame and the URL changes related to that top frame as 
	* they should appear on the location bar of a browser.  It is expected to reset
	* the identifier to 0 when the event didFinishLoadingFromDataSource related to 
	* the identifierForInitialRequest event is received.  Howeever, WebKit fires
	* the didFinishLoadingFromDataSource event before the entire content of the
	* top frame is loaded.  It is possible to receive multiple willSendRequest 
	* events in this interval, causing the Browser widget to send unwanted
	* Location.changing events.  For this reason, the identifier is reset to 0
	* when the top frame has either finished loading (didFinishLoadForFrame
	* event) or failed (didFailProvisionalLoadWithError).
	*/
	// this code is intentionally commented
	//if (this.identifier == identifier) this.identifier = 0;
}

void didReceiveAuthenticationChallengefromDataSource (int identifier, int challenge, int dataSource) {
	/*
	 * Do not invoke the listeners if this challenge has been failed too many
	 * times because a listener is likely giving incorrect credentials repeatedly
	 * and will do so indefinitely.
	 */
	int count = Cocoa.objc_msgSend (challenge, Cocoa.S_previousFailureCount);
	if (count < 3) {
		for (int i = 0; i < authenticationListeners.length; i++) {
			AuthenticationEvent event = new AuthenticationEvent (browser);
			event.location = lastNavigateURL;
			authenticationListeners[i].authenticate (event);
			if (!event.doit) {
				int challengeSender = Cocoa.objc_msgSend (challenge, Cocoa.S_sender);
				Cocoa.objc_msgSend (challengeSender, Cocoa.S_cancelAuthenticationChallenge, challenge);
				return;
			}
			if (event.user != null && event.password != null) {
				int challengeSender = Cocoa.objc_msgSend (challenge, Cocoa.S_sender);
				int user = createNSString(event.user);
				int password = createNSString(event.password);
				int credential = Cocoa.objc_msgSend (Cocoa.C_NSURLCredential, Cocoa.S_credentialWithUser, user, password, Cocoa.NSURLCredentialPersistenceForSession);
				Cocoa.objc_msgSend (challengeSender, Cocoa.S_useCredential, credential, challenge);
				OS.CFRelease (password);
				OS.CFRelease (user);
				return;
			}
		}
	}

	/* no listener handled the challenge, so try to invoke the native panel */
	int cls = Cocoa.C_WebPanelAuthenticationHandler;
	if (cls != 0) {
		int method = Cocoa.class_getClassMethod (cls, Cocoa.S_sharedHandler);
		if (method != 0) {
			int handler = Cocoa.objc_msgSend (cls, Cocoa.S_sharedHandler);
			if (handler != 0) {
				int window = Cocoa.objc_msgSend (webView, Cocoa.S_window);
				Cocoa.objc_msgSend (handler, Cocoa.S_startAuthentication, challenge, window);
				return;
			}
		}
	}

	/* the native panel was not available, so show a custom dialog */
	String[] userReturn = new String[1], passwordReturn = new String[1];
	int proposedCredential = Cocoa.objc_msgSend (challenge, Cocoa.S_proposedCredential);
	if (proposedCredential != 0) {
		int user = Cocoa.objc_msgSend (proposedCredential, Cocoa.S_user);
		userReturn[0] = getString (user);
		boolean hasPassword = Cocoa.objc_msgSend (proposedCredential, Cocoa.S_hasPassword) != 0;
		if (hasPassword) {
			int password = Cocoa.objc_msgSend (proposedCredential, Cocoa.S_password);
			passwordReturn[0] = getString (password);
		}
	}

	int space = Cocoa.objc_msgSend (challenge, Cocoa.S_protectionSpace);
	int host = Cocoa.objc_msgSend (space, Cocoa.S_host);
	String hostString = getString (host) + ':';
	int port = Cocoa.objc_msgSend (space, Cocoa.S_port);
	hostString += port;
	int realm = Cocoa.objc_msgSend (space, Cocoa.S_realm);
	String realmString = getString (realm);
	boolean result = showAuthenticationDialog (userReturn, passwordReturn, hostString, realmString);
	int challengeSender = Cocoa.objc_msgSend (challenge, Cocoa.S_sender);
	if (!result) {
		Cocoa.objc_msgSend (challengeSender, Cocoa.S_cancelAuthenticationChallenge, challenge);
		return;
	}

	int user = createNSString(userReturn[0]);
	int password = createNSString(passwordReturn[0]);
	int credential = Cocoa.objc_msgSend (Cocoa.C_NSURLCredential, Cocoa.S_credentialWithUser, user, password, Cocoa.NSURLCredentialPersistenceForSession);
	Cocoa.objc_msgSend (challengeSender, Cocoa.S_useCredential, credential, challenge);
	OS.CFRelease (password);
	OS.CFRelease (user);
}

boolean showAuthenticationDialog (final String[] user, final String[] password, String host, String realm) {
	final Shell shell = new Shell (browser.getShell ());
	shell.setLayout (new GridLayout ());
	String title = SWT.getMessage ("SWT_Authentication_Required"); //$NON-NLS-1$
	shell.setText (title);
	Label label = new Label (shell, SWT.WRAP);
	label.setText (Compatibility.getMessage ("SWT_Enter_Username_and_Password", new String[] {realm, host})); //$NON-NLS-1$

	GridData data = new GridData ();
	Monitor monitor = browser.getMonitor ();
	int maxWidth = monitor.getBounds ().width * 2 / 3;
	int width = label.computeSize (SWT.DEFAULT, SWT.DEFAULT).x;
	data.widthHint = Math.min (width, maxWidth);
	data.horizontalAlignment = GridData.FILL;
	data.grabExcessHorizontalSpace = true;
	label.setLayoutData (data);

	Label userLabel = new Label (shell, SWT.NONE);
	userLabel.setText (SWT.getMessage ("SWT_Username")); //$NON-NLS-1$

	final Text userText = new Text (shell, SWT.BORDER);
	if (user[0] != null) userText.setText (user[0]);
	data = new GridData ();
	data.horizontalAlignment = GridData.FILL;
	data.grabExcessHorizontalSpace = true;
	userText.setLayoutData (data);

	Label passwordLabel = new Label (shell, SWT.NONE);
	passwordLabel.setText (SWT.getMessage ("SWT_Password")); //$NON-NLS-1$

	final Text passwordText = new Text (shell, SWT.PASSWORD | SWT.BORDER);
	if (password[0] != null) passwordText.setText (password[0]);
	data = new GridData ();
	data.horizontalAlignment = GridData.FILL;
	data.grabExcessHorizontalSpace = true;
	passwordText.setLayoutData (data);

	final boolean[] result = new boolean[1];
	final Button[] buttons = new Button[2];
	Listener listener = new Listener() {
		public void handleEvent(Event event) {
			user[0] = userText.getText();
			password[0] = passwordText.getText();
			result[0] = event.widget == buttons[1];
			shell.close();
		}	
	};

	Composite composite = new Composite (shell, SWT.NONE);
	data = new GridData ();
	data.horizontalAlignment = GridData.END;
	composite.setLayoutData (data);
	composite.setLayout (new GridLayout (2, true));
	buttons[0] = new Button (composite, SWT.PUSH);
	buttons[0].setText (SWT.getMessage("SWT_Cancel")); //$NON-NLS-1$
	buttons[0].setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
	buttons[0].addListener (SWT.Selection, listener);
	buttons[1] = new Button (composite, SWT.PUSH);
	buttons[1].setText (SWT.getMessage("SWT_OK")); //$NON-NLS-1$
	buttons[1].setLayoutData (new GridData (GridData.FILL_HORIZONTAL));
	buttons[1].addListener (SWT.Selection, listener);

	shell.setDefaultButton (buttons[1]);
	shell.pack ();
	shell.open ();
	Display display = browser.getDisplay ();
	while (!shell.isDisposed ()) {
		if (!display.readAndDispatch ()) display.sleep ();
	}

	return result[0];
}

int identifierForInitialRequest(int request, int dataSource) {
	final Display display = browser.getDisplay();
	final ProgressEvent progress = new ProgressEvent(browser);
	progress.display = display;
	progress.widget = browser;
	progress.current = resourceCount;
	progress.total = Math.max(resourceCount, MAX_PROGRESS);
	for (int i = 0; i < progressListeners.length; i++) {
		progressListeners[i].changed(progress);
	}
	if (browser.isDisposed()) return 0;

	/*
	* Note.  numberWithInt uses autorelease.  The resulting object
	* does not need to be released.
	* identifier = [NSNumber numberWithInt: resourceCount++]
	*/	
	int identifier = Cocoa.objc_msgSend(Cocoa.C_NSNumber, Cocoa.S_numberWithInt, resourceCount++);
		
	if (this.identifier == 0) {
		int frame = Cocoa.objc_msgSend(dataSource, Cocoa.S_webFrame);
		if (frame == Cocoa.objc_msgSend(webView, Cocoa.S_mainFrame)) this.identifier = identifier;
	}
	return identifier;
}

int willSendRequest(int identifier, int request, int redirectResponse, int dataSource) {
	int url = Cocoa.objc_msgSend (request, Cocoa.S_URL);
	boolean isFileURL = Cocoa.objc_msgSend (url, Cocoa.S_isFileURL) != 0;
	if (isFileURL) {
		int newRequest = Cocoa.objc_msgSend (request, Cocoa.S_mutableCopy);
		Cocoa.objc_msgSend (newRequest, Cocoa.S_autorelease);
		Cocoa.objc_msgSend (newRequest, Cocoa.S_setCachePolicy, Cocoa.NSURLRequestReloadIgnoringLocalCacheData);
		return newRequest;
	}
	return request;
}

/* handleNotification */

void handleNotification(int notification) {	
}

/* UIDelegate */
int createWebViewWithRequest(int request) {
	WindowEvent newEvent = new WindowEvent(browser);
	newEvent.display = browser.getDisplay();
	newEvent.widget = browser;
	newEvent.required = true;
	if (openWindowListeners != null) {
		for (int i = 0; i < openWindowListeners.length; i++) {
			openWindowListeners[i].open(newEvent);
		}
	}

	int webView = 0;