Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 1406 lines (1130 sloc) 42.115 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 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
/*
* CPApplication.j
* AppKit
*
* Created by Francisco Tolmasky.
* Copyright 2008, 280 North, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

@import <Foundation/CPBundle.j>

@import "CPCompatibility.j"
@import "CPEvent.j"
@import "CPMenu.j"
@import "CPResponder.j"
@import "CPDocumentController.j"
@import "CPThemeBlend.j"
@import "CPCibLoading.j"
@import "CPPlatform.j"


var CPMainCibFile = @"CPMainCibFile",
    CPMainCibFileHumanFriendly = @"Main cib file base name",
    CPEventModifierFlags = 0;

CPApp = nil;

CPApplicationWillFinishLaunchingNotification = @"CPApplicationWillFinishLaunchingNotification";
CPApplicationDidFinishLaunchingNotification = @"CPApplicationDidFinishLaunchingNotification";
CPApplicationWillTerminateNotification = @"CPApplicationWillTerminateNotification";
CPApplicationWillBecomeActiveNotification = @"CPApplicationWillBecomeActiveNotification";
CPApplicationDidBecomeActiveNotification = @"CPApplicationDidBecomeActiveNotification";
CPApplicationWillResignActiveNotification = @"CPApplicationWillResignActiveNotification";
CPApplicationDidResignActiveNotification = @"CPApplicationDidResignActiveNotification";

CPTerminateNow = YES;
CPTerminateCancel = NO;
CPTerminateLater = -1; // not currently supported

CPRunStoppedResponse = -1000;
CPRunAbortedResponse = -1001;
CPRunContinuesResponse = -1002;

/*!
@ingroup appkit
@class CPApplication

CPApplication is THE way to start up the Cappuccino framework for your application to use.
Every GUI application has exactly one instance of CPApplication (or of a custom subclass of
CPApplication). Your program's main() function can create that instance by calling the
\c CPApplicationMain function. A simple example looks like this:

<pre>
function main(args, namedArgs)
{
CPApplicationMain(args, namedArgs);
}
</pre>

@delegate -(void)applicationDidFinishLaunching:(CPNotification)aNotification;
Sent from the notification center after the app initializes, but before
receiving events.
@param aNotification contains information about the event

@delegate -(void)applicationWillFinishLaunching:(CPNotification)aNotification;
Sent from the notification center before the app is initialized.
@param aNotification contains information about the event
*/
@implementation CPApplication : CPResponder
{
    CPArray _eventListeners;

    CPEvent _currentEvent;

    CPArray _windows;
    CPWindow _keyWindow;
    CPWindow _mainWindow;
    CPWindow _previousKeyWindow;
    CPWindow _previousMainWindow;

    CPDocumentController _documentController;

    CPModalSession _currentSession;

    //
    id _delegate;
    BOOL _finishedLaunching;
    BOOL _isActive;

    CPDictionary _namedArgs;
    CPArray _args;
    CPString _fullArgsString;

    CPImage _applicationIconImage;

    CPPanel _aboutPanel;

    CPThemeBlend _themeBlend @accessors(property=themeBlend);
}

/*!
Returns the singleton instance of the running application. If it
doesn't exist, it will be created, and then returned.
@return the application singleton
*/
+ (CPApplication)sharedApplication
{
    if (!CPApp)
        CPApp = [[CPApplication alloc] init];

    return CPApp;
}

/*!
Initializes the Document based application with basic menu functions.
Functions are \c New, \c Open, \c Undo, \c Redo, \c Save, \c Cut, \c Copy, \c Paste.
@return the initialized application
*/
- (id)init
{
    self = [super init];

    CPApp = self;

    if (self)
    {
        _eventListeners = [];

        _windows = [];

        [_windows addObject:nil];
    }

    return self;
}

// Configuring Applications

/*!
Sets the delegate for this application. The delegate will receive various notifications
caused by user interactions during the application's run. The delegate can choose to
react to these events.
@param aDelegate the delegate object
*/
- (void)setDelegate:(id)aDelegate
{
    if (_delegate == aDelegate)
        return;

    var defaultCenter = [CPNotificationCenter defaultCenter],
        delegateNotifications =
        [
            CPApplicationWillFinishLaunchingNotification, @selector(applicationWillFinishLaunching:),
            CPApplicationDidFinishLaunchingNotification, @selector(applicationDidFinishLaunching:),
            CPApplicationWillBecomeActiveNotification, @selector(applicationWillBecomeActive:),
            CPApplicationDidBecomeActiveNotification, @selector(applicationDidBecomeActive:),
            CPApplicationWillResignActiveNotification, @selector(applicationWillResignActive:),
            CPApplicationDidResignActiveNotification, @selector(applicationDidResignActive:),
            CPApplicationWillTerminateNotification, @selector(applicationWillTerminate:)
        ],
        count = [delegateNotifications count];

    if (_delegate)
    {
        var index = 0;

        for (; index < count; index += 2)
        {
            var notificationName = delegateNotifications[index],
                selector = delegateNotifications[index + 1];

            if ([_delegate respondsToSelector:selector])
                [defaultCenter removeObserver:_delegate name:notificationName object:self];
        }
    }

    _delegate = aDelegate;

    var index = 0;

    for (; index < count; index += 2)
    {
        var notificationName = delegateNotifications[index],
            selector = delegateNotifications[index + 1];

        if ([_delegate respondsToSelector:selector])
            [defaultCenter addObserver:_delegate selector:selector name:notificationName object:self];
    }
}

/*!
Returns the application's delegate. The app can only have one delegate at a time.
*/
- (id)delegate
{
    return _delegate;
}

/*!
This method is called by \c -run before the event loop begins.
When it successfully completes, it posts the notification
CPApplicationDidFinishLaunchingNotification. If you override
\c -finishLaunching, the subclass method should invoke the superclass method.
*/
- (void)finishLaunching
{
    // At this point we clear the window.status to eliminate Safari's "Cancelled" error message
    // The message shouldn't be displayed, because only an XHR is cancelled, but it is a usability issue.
    // We do it here so that applications can change it in willFinish or didFinishLaunching
#if PLATFORM(DOM)
    window.status = " ";
#endif

    // We also want to set the default cursor on the body, so that buttons and things don't have an iBeam
    [[CPCursor arrowCursor] set];

    var bundle = [CPBundle mainBundle],
        delegateClassName = [bundle objectForInfoDictionaryKey:@"CPApplicationDelegateClass"];

    if (delegateClassName)
    {
        var delegateClass = objj_getClass(delegateClassName);

        if (delegateClass)
            [self setDelegate:[[delegateClass alloc] init]];
    }

    var defaultCenter = [CPNotificationCenter defaultCenter];

    [defaultCenter
        postNotificationName:CPApplicationWillFinishLaunchingNotification
        object:self];

    var types = [bundle objectForInfoDictionaryKey:@"CPBundleDocumentTypes"];

    if ([types count] > 0)
        _documentController = [CPDocumentController sharedDocumentController];

    var needsUntitled = !!_documentController,
        URLStrings = window.cpOpeningURLStrings && window.cpOpeningURLStrings(),
        index = 0,
        count = [URLStrings count];

    for (; index < count; ++index)
        needsUntitled = ![self _openURL:[CPURL URLWithString:URLStrings[index]]] && needsUntitled;

    if (needsUntitled && [_delegate respondsToSelector:@selector(applicationShouldOpenUntitledFile:)])
        needsUntitled = [_delegate applicationShouldOpenUntitledFile:self];

    if (needsUntitled)
        [_documentController newDocument:self];

    [_documentController _updateRecentDocumentsMenu];

    [defaultCenter
        postNotificationName:CPApplicationDidFinishLaunchingNotification
        object:self];

    [[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];

    _finishedLaunching = YES;
}

- (void)terminate:(id)aSender
{
    [[CPNotificationCenter defaultCenter]
        postNotificationName:CPApplicationWillTerminateNotification
                      object:self];

    if (![CPPlatform isBrowser])
    {
        [[CPDocumentController sharedDocumentController] closeAllDocumentsWithDelegate:self
                                                                  didCloseAllSelector:@selector(_documentController:didCloseAll:context:)
                                                                          contextInfo:nil];
    }
    else
    {
        [[[self keyWindow] platformWindow] _propagateCurrentDOMEvent:YES];
    }
}

/*!
Sets the applications icon image. This image is used in the default "About" window.
By default this value is pulled from the CPApplicationIcon key in your info.plist file.

@param anImage - The image to set.
*/
- (void)setApplicationIconImage:(CPImage)anImage
{
    _applicationIconImage = anImage;
}

/*!
Returns the application icon image. By default this is pulled from the CPApplicationIcon key of info.plist.
@return CPImage - Your application icon image.
*/
- (CPImage)applicationIconImage
{
    if (_applicationIconImage)
        return _applicationIconImage;

    var imagePath = [[CPBundle mainBundle] objectForInfoDictionaryKey:@"CPApplicationIcon"];
    if (imagePath)
        _applicationIconImage = [[CPImage alloc] initWithContentsOfFile:imagePath];

    return _applicationIconImage;
}

/*!
Opens the standard about panel with no options.
*/
- (void)orderFrontStandardAboutPanel:(id)sender
{
    [self orderFrontStandardAboutPanelWithOptions:nil];
}

/*!
Opens the standard about panel. This method takes a single argument \c options.
Options is a dictionary that can contain any of the following keys:
<pre>
ApplicationName - The name of your application.
ApplicationIcon - Application icon image.
Version - The full version of your application
ApplicationVersion - The shorter version number of your application.
Copyright - Human readable copyright information.
</pre>

If you choose not the include any of the above keys, they will default
to the following respective keys in your info.plist file.

<pre>
CPBundleName
CPApplicationIcon (through a call to -applicationIconImage, see documentation for that method for more details)
CPBundleVersion
CPBundleShortVersionString
CPHumanReadableCopyright
</pre>

@param options - A dictionary with the aboe listed keys. You can pass nil to default to your plist values.
*/
- (void)orderFrontStandardAboutPanelWithOptions:(CPDictionary)options
{
    if (!_aboutPanel)
    {
        var mainInfo = [[CPBundle mainBundle] infoDictionary],
            applicationTitle = [options objectForKey:"ApplicationName"] || [mainInfo objectForKey:@"CPBundleName"],
            applicationIcon = [options objectForKey:@"ApplicationIcon"] || [self applicationIconImage],
            version = [options objectForKey:@"Version"] || [mainInfo objectForKey:@"CPBundleVersion"],
            applicationVersion = [options objectForKey:@"ApplicationVersion"] || [mainInfo objectForKey:@"CPBundleShortVersionString"],
            copyright = [options objectForKey:@"Copyright"] || [mainInfo objectForKey:@"CPHumanReadableCopyright"];

        var aboutPanelPath = [[CPBundle bundleForClass:[CPWindowController class]] pathForResource:@"AboutPanel.cib"],
            aboutPanelController = [CPWindowController alloc],
            aboutPanelController = [aboutPanelController initWithWindowCibPath:aboutPanelPath owner:aboutPanelController],
            aboutPanel = [aboutPanelController window],
            contentView = [aboutPanel contentView],
            imageView = [contentView viewWithTag:1],
            applicationLabel = [contentView viewWithTag:2],
            versionLabel = [contentView viewWithTag:3],
            copyrightLabel = [contentView viewWithTag:4],
            standardPath = [[CPBundle bundleForClass:[self class]] pathForResource:@"standardApplicationIcon.png"];

        // FIXME move this into the CIB eventually
        [applicationLabel setFont:[CPFont boldSystemFontOfSize:[CPFont systemFontSize] + 2]];
        [applicationLabel setAlignment:CPCenterTextAlignment];
        [versionLabel setAlignment:CPCenterTextAlignment];
        [copyrightLabel setAlignment:CPCenterTextAlignment];

        [imageView setImage:applicationIcon || [[CPImage alloc] initWithContentsOfFile:standardPath
                                                                                  size:CGSizeMake(256, 256)]];

        [applicationLabel setStringValue:applicationTitle || ""];

        if (applicationVersion && version)
            [versionLabel setStringValue:@"Version " + applicationVersion + " (" + version + ")"];
        else if (applicationVersion || version)
            [versionLabel setStringValue:@"Version " + (applicationVersion || version)];
        else
            [versionLabel setStringValue:@""];

        [copyrightLabel setStringValue:copyright || ""];
        [aboutPanel center];

        _aboutPanel = aboutPanel;
    }

    [_aboutPanel orderFront:self];
}


- (void)_documentController:(NSDocumentController *)docController didCloseAll:(BOOL)didCloseAll context:(Object)info
{
    // callback method for terminate:
    if (didCloseAll)
    {
        if ([_delegate respondsToSelector:@selector(applicationShouldTerminate:)])
            [self replyToApplicationShouldTerminate:[_delegate applicationShouldTerminate:self]];
        else
            [self replyToApplicationShouldTerminate:YES];
    }
}

- (void)replyToApplicationShouldTerminate:(BOOL)terminate
{
    if (terminate == CPTerminateNow)
    {
        [[CPNotificationCenter defaultCenter] postNotificationName:CPApplicationWillTerminateNotification object:self];
        [CPPlatform terminateApplication];
    }
}

- (void)activateIgnoringOtherApps:(BOOL)shouldIgnoreOtherApps
{
    [self _willBecomeActive];

    [CPPlatform activateIgnoringOtherApps:shouldIgnoreOtherApps];
    _isActive = YES;

    [self _willResignActive];
}

- (void)deactivate
{
    [self _willResignActive];

    [CPPlatform deactivate];
    _isActive = NO;

    [self _didResignActive];
}

- (void)isActive
{
    return _isActive;
}

- (void)hideOtherApplications:(id)aSender
{
    [CPPlatform hideOtherApplications:self];
}

/*!
Calls \c -finishLaunching method which results in starting
the main event loop.
*/
- (void)run
{
    [self finishLaunching];
}

// Managing the Event Loop
/*!
Starts a modal event loop for \c aWindow
@param aWindow the window to start the event loop for
*/
- (void)runModalForWindow:(CPWindow)aWindow
{
    [self runModalSession:[self beginModalSessionForWindow:aWindow]];
}

/*!
Stops the event loop started by \c -runModalForWindow: and
sets the code that \c -runModalForWindow: will return.
@param aCode the return code for the modal event
*/
- (void)stopModalWithCode:(int)aCode
{
    if (!_currentSession)
    {
        return;
        // raise exception;
    }

    _currentSession._state = aCode;
    _currentSession = _currentSession._previous;

// if (aCode == CPRunAbortedResponse)
        [self _removeRunModalLoop];
}

/* @ignore */
- (void)_removeRunModalLoop
{
    var count = _eventListeners.length;

    while (count--)
        if (_eventListeners[count]._callback === _CPRunModalLoop)
        {
            _eventListeners.splice(count, 1);

            return;
        }
}

/*!
Stops the modal event loop
*/
- (void)stopModal
{
    [self stopModalWithCode:CPRunStoppedResponse]
}

/*!
Aborts the event loop started by \c -runModalForWindow:
*/
- (void)abortModal
{
    [self stopModalWithCode:CPRunAbortedResponse];
}

/*!
Sets up a modal session with \c theWindow.
@param aWindow the window to set up the modal session for
*/
- (CPModalSession)beginModalSessionForWindow:(CPWindow)aWindow
{
    return _CPModalSessionMake(aWindow, 0);
}

/*!
Runs a modal session
@param CPModalSession the session to run
*/
- (void)runModalSession:(CPModalSession)aModalSession
{
    aModalSession._previous = _currentSession;
    _currentSession = aModalSession;

    var theWindow = aModalSession._window;

    [theWindow center];
    [theWindow makeKeyWindow];
    [theWindow orderFront:self];

// [theWindow._bridge _obscureWindowsBelowModalWindow];

    [CPApp setCallback:_CPRunModalLoop forNextEventMatchingMask:CPAnyEventMask untilDate:nil inMode:0 dequeue:NO];
}

/*!
Returns the window for the current modal session. If there is no
modal session, it returns \c nil.
*/
- (CPWindow)modalWindow
{
    if (!_currentSession)
        return nil;

    return _currentSession._window;
}

/* @ignore */
- (BOOL)_handleKeyEquivalent:(CPEvent)anEvent
{
    return [[self keyWindow] performKeyEquivalent:anEvent] ||
            [[self mainMenu] performKeyEquivalent:anEvent];
}

/*!
Dispatches events to other objects.
@param anEvent the event to dispatch
*/
- (void)sendEvent:(CPEvent)anEvent
{
    _currentEvent = anEvent;
    CPEventModifierFlags = [anEvent modifierFlags];

#if PLATFORM(DOM)
    var willPropagate = [[[anEvent window] platformWindow] _willPropagateCurrentDOMEvent];

    // temporarily pretend we won't propagate the event. we'll restore the saved value later
    // we do this outside the if so that changes user code might make in _handleKeyEquiv. are preserved
    [[[anEvent window] platformWindow] _propagateCurrentDOMEvent:NO];
#endif

    // Check if this is a candidate for key equivalent...
    if ([anEvent _couldBeKeyEquivalent] && [self _handleKeyEquivalent:anEvent])
    {
#if PLATFORM(DOM)
        var characters = [anEvent characters],
            modifierFlags = [anEvent modifierFlags];

        // Unconditionally propagate on these keys to solve browser copy paste bugs
        if ((characters == "c" || characters == "x" || characters == "v") && (modifierFlags & CPPlatformActionKeyMask))
            [[[anEvent window] platformWindow] _propagateCurrentDOMEvent:YES];
#endif

        return;
    }

#if PLATFORM(DOM)
    // if we make it this far, then restore the original willPropagate value
    [[[anEvent window] platformWindow] _propagateCurrentDOMEvent:willPropagate];
#endif

    if (_eventListeners.length)
    {
        if (_eventListeners[_eventListeners.length - 1]._mask & (1 << [anEvent type]))
            _eventListeners.pop()._callback(anEvent);

        return;
    }

    [[anEvent window] sendEvent:anEvent];
}

/*!
If the delegate responds to the given selector it will call the method on the delegate,
otherwise the method will be passed to CPResponder.
*/
- (void)doCommandBySelector:(SEL)aSelector
{
    if ([_delegate respondsToSelector:aSelector])
        [_delegate performSelector:aSelector];
    else
        [super doCommandBySelector:aSelector];
}

/*!
Returns the key window.
*/
- (CPWindow)keyWindow
{
    return _keyWindow;
}

/*!
Returns the main window.
*/
- (CPWindow)mainWindow
{
    return _mainWindow;
}

/*!
Returns the CPWindow object corresponding to \c aWindowNumber.
*/
- (CPWindow)windowWithWindowNumber:(int)aWindowNumber
{
    return _windows[aWindowNumber];
}

/*!
Returns an array of the application's CPWindows
*/
- (CPArray)windows
{
    return _windows;
}

/*!
Returns an array of visible CPWindow objects, ordered by their front to back order on the screen.
*/
- (CPArray)orderedWindows
{
#if PLATFORM(DOM)
    return CPWindowObjectList();
#else
    return [];
#endif
}

- (void)hide:(id)aSender
{
    [CPPlatform hide:self];
}

// Accessing the Main Menu
/*!
Returns the application's main menu
*/
- (CPMenu)mainMenu
{
    return [self menu];
}

/*!
Sets the main menu for the application
@param aMenu the menu to set for the application
*/
- (void)setMainMenu:(CPMenu)aMenu
{
    [self setMenu:aMenu];
}

- (void)setMenu:(CPMenu)aMenu
{
    if ([aMenu _menuName] === "CPMainMenu")
    {
        if ([self menu] === aMenu)
            return;

        [super setMenu:aMenu];

        if ([CPPlatform supportsNativeMainMenu])
            window.cpSetMainMenu([self menu]);
    }
    else
        [aMenu _setMenuName:@"CPMainMenu"];
}

/*!
Opens the shared color panel.
@param aSender
*/
- (void)orderFrontColorPanel:(id)aSender
{
    [[CPColorPanel sharedColorPanel] orderFront:self];
}

// Posting Actions
/*!
Tries to perform the action with an argument. Performs
the action on itself (if it responds to it), then
tries to perform the action on the delegate.
@param anAction the action to perform.
@param anObject the argument for the action
method
@return \c YES if the action was performed
*/
- (BOOL)tryToPerform:(SEL)anAction with:(id)anObject
{
    if (!anAction)
        return NO;

    if ([super tryToPerform:anAction with:anObject])
        return YES;

    if ([_delegate respondsToSelector:anAction])
    {
        [_delegate performSelector:anAction withObject:anObject];

        return YES;
    }

    return NO;
}

/*!
Sends an action to a target.
@param anAction the action to send
@param aTarget the target for the action
@param aSender the action sender
@return \c YES
*/
- (BOOL)sendAction:(SEL)anAction to:(id)aTarget from:(id)aSender
{
    var target = [self targetForAction:anAction to:aTarget from:aSender];

    if (!target)
        return NO;

    [target performSelector:anAction withObject:aSender];

    return YES;
}

/*!
Finds a target for the specified action. If the
action is \c nil, returns \c nil.
If the target is not \c nil, \c aTarget is
returned. Otherwise, it calls \c -targetForAction:
to search for a target.
@param anAction the action to find a target for
@param aTarget if not \c nil, this will be returned
@aSender not used
@return a target for the action
*/
- (id)targetForAction:(SEL)anAction to:(id)aTarget from:(id)aSender
{
    if (!anAction)
        return nil;

    if (aTarget)
        return aTarget;

    return [self targetForAction:anAction];
}

/*!
Finds an action-target for a specified window.
It finds a matching target in the following order:
<ol>
<li>the window's first responder</li>
<li>all the next responders after first responder</li>
<li>the window</li>
<li>the window's delegate</li>
<li>the window's controller</li>
<li>the window's associated document</li>
</ol>
@param aWindow the window to search for a target
@param anAction the action to find a responder to
@return the object that responds to the action, or \c nil
if no matching target was found
@ignore
*/
- (id)_targetForWindow:(CPWindow)aWindow action:(SEL)anAction
{
    var responder = [aWindow firstResponder],
        checkWindow = YES;

    while (responder)
    {
        if ([responder respondsToSelector:anAction])
            return responder;

        if (responder == aWindow)
            checkWindow = NO;

        responder = [responder nextResponder];
    }

    if (checkWindow && [aWindow respondsToSelector:anAction])
        return aWindow;

    var delegate = [aWindow delegate];

    if ([delegate respondsToSelector:anAction])
        return delegate;

    var windowController = [aWindow windowController];

    if ([windowController respondsToSelector:anAction])
        return windowController;

    var theDocument = [windowController document];
    if (theDocument !== delegate && [theDocument respondsToSelector:anAction])
        return theDocument;

    return nil;
}

/*!
Looks for a target that can handle the specified action.
Checks for a target in the following order:
<ol>
<li>a responder from the key window</li>
<li>a responder from the main window</li>
<li>the CPApplication instance</li>
<li>the application delegate</li>
<li>the document controller</li>
</ol>
@param anAction the action to handle
@return a target that can respond, or \c nil
if no match could be found
*/
- (id)targetForAction:(SEL)anAction
{
    if (!anAction)
        return nil;

    var target = [self _targetForWindow:[self keyWindow] action:anAction];

    if (target)
        return target;

    target = [self _targetForWindow:[self mainWindow] action:anAction];

    if (target)
        return target;

    if ([self respondsToSelector:anAction])
        return self;

    if ([_delegate respondsToSelector:anAction])
        return _delegate;

    if ([_documentController respondsToSelector:anAction])
        return _documentController;

    return nil;
}

/*!
Fires a callback function when an event matching a given mask occurs.
@param aCallback - A js function to be fired.
@prarm aMask - An event mask for the next event.
@param anExpiration - The date for which this callback expires (not implemented).
@param inMode (not implemented).
@param shouldDequeue (not implemented).
*/
- (void)setCallback:(Function)aCallback forNextEventMatchingMask:(unsigned int)aMask untilDate:(CPDate)anExpiration inMode:(CPString)aMode dequeue:(BOOL)shouldDequeue
{
    _eventListeners.push(_CPEventListenerMake(aMask, aCallback));
}

/*!
Assigns a target and action for the next event matching a given event mask.
The callback method called will be passed the CPEvent when it fires.

@param aTarget - The target object for the callback.
@param aSelector - The selector which should be called on the target object.
@param aMask - The mask for a given event which should trigger the callback.
@param anExpiration - The date for which the callback expires (not implemented).
@param aMode (not implemented).
@param shouldDequeue (not implemented).
*/
- (void)setTarget:(id)aTarget selector:(SEL)aSelector forNextEventMatchingMask:(unsigned int)aMask untilDate:(CPDate)anExpiration inMode:(CPString)aMode dequeue:(BOOL)shouldDequeue
{
    _eventListeners.push(_CPEventListenerMake(aMask, function (anEvent) { objj_msgSend(aTarget, aSelector, anEvent); }));
}

/*!
Returns the last event recieved by your application.
*/
- (CPEvent)currentEvent
{
    return _currentEvent;
}

// Managing Sheets

/*!
Displays a window as a sheet.
@param aSheet the window to display as a sheet
@param aWindow the window that will hold the sheet as a child
@param aModalDelegate
@param aDidEndSelector
@param aContextInfo
*/
- (void)beginSheet:(CPWindow)aSheet modalForWindow:(CPWindow)aWindow modalDelegate:(id)aModalDelegate didEndSelector:(SEL)aDidEndSelector contextInfo:(id)aContextInfo
{
    if ([aWindow isSheet])
    {
        [CPException raise:CPInternalInconsistencyException reason:@"The target window of beginSheet: cannot be a sheet"];
        return;
    }

    [aSheet._windowView _enableSheet:YES];

    // -dw- if a sheet is already visible, we skip this since it serves no purpose and causes
    // orderOut: to be called on the sheet, which is not what we want.
    if (![aWindow isVisible])
    {
        [aWindow orderFront:self];
        [aSheet setPlatformWindow:[aWindow platformWindow]];
    }
    [aWindow _attachSheet:aSheet modalDelegate:aModalDelegate didEndSelector:aDidEndSelector contextInfo:aContextInfo];
}

/*!
Ends a sheet modal.
The following are predefined return codes:

<pre>
CPRunStoppedResponse
CPRunAbortedResponse
CPRunContinuesResponse
</pre>

@param sheet - The window object (sheet) to dismiss.
@param returnCode - The return code to send to the delegate. You can use one of the return codes above or a custom value that you define.
*/
- (void)endSheet:(CPWindow)sheet returnCode:(int)returnCode
{
    var count = [_windows count];

    while (--count >= 0)
    {
        var aWindow = [_windows objectAtIndex:count],
            context = aWindow._sheetContext;

        if (context != nil && context["sheet"] === sheet)
        {
            context["returnCode"] = returnCode;
            [aWindow _endSheet];
            return;
        }
    }
}

/*!
Ends a sheet and sends the return code "0".
@param sheet - The CPWindow object (sheet) that should be dismissed.
*/
- (void)endSheet:(CPWindow)sheet
{
    // FIX ME: this is wrong: by Cocoa this should be: CPRunStoppedResponse.
   [self endSheet:sheet returnCode:0];
}

/*!
Returns and array of slash seperated arugments to your application.
These values are pulled from your window location hash.

For exampled if your application loaded:
<pre>
index.html#280north/cappuccino/issues
</pre>
The follow array would be returned:
<pre>
["280north", "cappuccino", "issues"]
</pre>

@return CPArray - The array of arguments.
*/
- (CPArray)arguments
{
    if (_fullArgsString !== window.location.hash)
        [self _reloadArguments];

    return _args;
}

/*!
Sets the arguments of your application.
That is, set the slash seperated values of an array as the window location hash.

For example if you pass an array:
<pre>
["280north", "cappuccino", "issues"]
</pre>

The new window location would be
<pre>
index.html#280north/cappuccino/issues
</pre>

@param args - An array of arguments.
*/
- (void)setArguments:(CPArray)args
{
    if (!args || args.length == 0)
    {
        _args = [];
        window.location.hash = @"#";

        return;
    }

    if (![args isKindOfClass:CPArray])
        args = [CPArray arrayWithObject:args];

    _args = args;

    var toEncode = [_args copy];
    for (var i = 0, count = toEncode.length; i < count; i++)
        toEncode[i] = encodeURIComponent(toEncode[i]);

    var hash = [toEncode componentsJoinedByString:@"/"];

    window.location.hash = @"#" + hash;
}

- (void)_reloadArguments
{
    _fullArgsString = window.location.hash;

    if (_fullArgsString.length)
    {
        var args = _fullArgsString.substring(1).split("/");

        for (var i = 0, count = args.length; i < count; i++)
            args[i] = decodeURIComponent(args[i]);

        _args = args;
    }
    else
        _args = [];
}

/*!
Returns a dictionary of the window location named arguments.
For example if your location was:
<pre>
index.html?owner=280north&repo=cappuccino&type=issues
</pre>

a CPDictionary with the keys:
<pre>
owner, repo, type
</pre>
and respective values:
<pre>
280north, cappuccino, issues
</pre>
Will be returned.
*/
- (CPDictionary)namedArguments
{
    return _namedArgs;
}

- (BOOL)_openURL:(CPURL)aURL
{
    if (_delegate && [_delegate respondsToSelector:@selector(application:openFile:)])
    {
        CPLog.warn("application:openFile: is deprecated, use application:openURL: instead.");
        return [_delegate application:self openFile:[aURL absoluteString]];
    }

    if (_delegate && [_delegate respondsToSelector:@selector(application:openURL:)])
        return [_delegate application:self openURL:aURL];

    return !![_documentController openDocumentWithContentsOfURL:aURL display:YES error:NULL];
}

- (void)_willBecomeActive
{
    [[CPNotificationCenter defaultCenter] postNotificationName:CPApplicationWillBecomeActiveNotification
                                                        object:self
                                                      userInfo:nil];
}

- (void)_didBecomeActive
{
    if (![self keyWindow] && _previousKeyWindow &&
        [[self windows] indexOfObjectIdenticalTo:_previousKeyWindow] !== CPNotFound)
        [_previousKeyWindow makeKeyWindow];

    if (![self mainWindow] && _previousMainWindow &&
        [[self windows] indexOfObjectIdenticalTo:_previousMainWindow] !== CPNotFound)
        [_previousMainWindow makeMainWindow];

    if ([self keyWindow])
        [[self keyWindow] orderFront:self];
    else if ([self mainWindow])
        [[self mainWindow] makeKeyAndOrderFront:self];
    else
        [[self mainMenu]._menuWindow makeKeyWindow]; //FIXME this may not actually work

    _previousKeyWindow = nil;
    _previousMainWindow = nil;

    [[CPNotificationCenter defaultCenter] postNotificationName:CPApplicationDidBecomeActiveNotification
                                                        object:self
                                                      userInfo:nil];
}

- (void)_willResignActive
{
    [[CPNotificationCenter defaultCenter] postNotificationName:CPApplicationWillResignActiveNotification
                                                        object:self
                                                      userInfo:nil];
}

- (void)_didResignActive
{
    if (self._activeMenu)
        [self._activeMenu cancelTracking];

    if ([self keyWindow])
    {
        _previousKeyWindow = [self keyWindow];
        [_previousKeyWindow resignKeyWindow];
    }

    if ([self mainWindow])
    {
        _previousMainWindow = [self mainWindow];
        [_previousMainWindow resignMainWindow];
    }

    [[CPNotificationCenter defaultCenter] postNotificationName:CPApplicationDidResignActiveNotification
                                                        object:self
                                                      userInfo:nil];
}

+ (CPString)defaultThemeName
{
    return ([[CPBundle mainBundle] objectForInfoDictionaryKey:"CPDefaultTheme"] || @"Aristo");
}

@end

var _CPModalSessionMake = function(aWindow, aStopCode)
{
    return { _window:aWindow, _state:CPRunContinuesResponse , _previous:nil };
};

var _CPEventListenerMake = function(anEventMask, aCallback)
{
    return { _mask:anEventMask, _callback:aCallback };
};

// Make this a global for use in CPPlatformWindow+DOM.j.
_CPRunModalLoop = function(anEvent)
{
    [CPApp setCallback:_CPRunModalLoop forNextEventMatchingMask:CPAnyEventMask untilDate:nil inMode:0 dequeue:NO];

    var theWindow = [anEvent window],
        modalSession = CPApp._currentSession;

    // The special case for popovers here is not clear. In Cocoa the popover window does not respond YES to worksWhenModal,
    // yet it works when there is a modal window. Maybe it starts its own modal session, but interaction with the original
    // modal window seems to continue working as well. Regardless of correctness, this solution beats popovers not working
    // at all from sheets.
    if (theWindow == modalSession._window ||
        [theWindow worksWhenModal] ||
        [theWindow attachedSheet] == modalSession._window || // -dw- allow modal parent of sheet to be repositioned
        ([theWindow isKindOfClass:_CPAttachedWindow] && [[theWindow targetView] window] === modalSession._window))
        [theWindow sendEvent:anEvent];
};

/*!
Starts the GUI and Cappuccino frameworks. This function should be
called from the \c main() function of your program.
@class CPApplication
@return void
*/

function CPApplicationMain(args, namedArgs)
{

#if PLATFORM(DOM)
    // hook to allow recorder, etc to manipulate things before starting AppKit
    if (window.parent !== window && typeof window.parent._childAppIsStarting === "function")
        window.parent._childAppIsStarting(window);
#endif

    var mainBundle = [CPBundle mainBundle],
        principalClass = [mainBundle principalClass];

    if (!principalClass)
        principalClass = [CPApplication class];

    [principalClass sharedApplication];

    if ([args containsObject:"debug"])
        CPLogRegister(CPLogPopup);

    CPApp._args = args;
    CPApp._namedArgs = namedArgs;

    [_CPAppBootstrapper performActions];
}

var _CPAppBootstrapperActions = nil;

@implementation _CPAppBootstrapper : CPObject
{
}

+ (CPArray)actions
{
    return [@selector(bootstrapPlatform), @selector(loadDefaultTheme), @selector(loadMainCibFile)];
}

+ (void)performActions
{
    if (!_CPAppBootstrapperActions)
        _CPAppBootstrapperActions = [self actions];

    while (_CPAppBootstrapperActions.length)
    {
        var action = _CPAppBootstrapperActions.shift();

        if (objj_msgSend(self, action))
            return;
    }

    [CPApp run];
}

+ (BOOL)bootstrapPlatform
{
    return [CPPlatform bootstrap];
}

+ (BOOL)loadDefaultTheme
{
    var defaultThemeName = [CPApplication defaultThemeName],
        themeURL = nil;

    if (defaultThemeName === @"Aristo")
        themeURL = [[CPBundle bundleForClass:[CPApplication class]] pathForResource:defaultThemeName + @".blend"];
    else
        themeURL = [[CPBundle mainBundle] pathForResource:defaultThemeName + @".blend"];

    var blend = [[CPThemeBlend alloc] initWithContentsOfURL:themeURL];
    [blend loadWithDelegate:self];

    return YES;
}

+ (void)blendDidFinishLoading:(CPThemeBlend)aThemeBlend
{
    [[CPApplication sharedApplication] setThemeBlend:aThemeBlend];
    [CPTheme setDefaultTheme:[CPTheme themeNamed:[CPApplication defaultThemeName]]];

    [self performActions];
}

+ (BOOL)loadMainCibFile
{
    var mainBundle = [CPBundle mainBundle],
        mainCibFile = [mainBundle objectForInfoDictionaryKey:CPMainCibFile] || [mainBundle objectForInfoDictionaryKey:CPMainCibFileHumanFriendly];

    if (mainCibFile)
    {
        [mainBundle loadCibFile:mainCibFile
            externalNameTable:[CPDictionary dictionaryWithObject:CPApp forKey:CPCibOwner]
                 loadDelegate:self];

        return YES;
    }
    else
        [self loadCiblessBrowserMainMenu];

    return NO;
}

+ (void)loadCiblessBrowserMainMenu
{
    var mainMenu = [[CPMenu alloc] initWithTitle:@"MainMenu"];

    // FIXME: We should implement autoenabling.
    [mainMenu setAutoenablesItems:NO];

    var bundle = [CPBundle bundleForClass:[CPApplication class]],
        newMenuItem = [[CPMenuItem alloc] initWithTitle:@"New" action:@selector(newDocument:) keyEquivalent:@"n"];

    [newMenuItem setImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/New.png"] size:CGSizeMake(16.0, 16.0)]];
    [newMenuItem setAlternateImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/NewHighlighted.png"] size:CGSizeMake(16.0, 16.0)]];

    [mainMenu addItem:newMenuItem];

    var openMenuItem = [[CPMenuItem alloc] initWithTitle:@"Open" action:@selector(openDocument:) keyEquivalent:@"o"];

    [openMenuItem setImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/Open.png"] size:CGSizeMake(16.0, 16.0)]];
    [openMenuItem setAlternateImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/OpenHighlighted.png"] size:CGSizeMake(16.0, 16.0)]];

    [mainMenu addItem:openMenuItem];

    var saveMenu = [[CPMenu alloc] initWithTitle:@"Save"],
        saveMenuItem = [[CPMenuItem alloc] initWithTitle:@"Save" action:@selector(saveDocument:) keyEquivalent:nil];

    [saveMenuItem setImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/Save.png"] size:CGSizeMake(16.0, 16.0)]];
    [saveMenuItem setAlternateImage:[[CPImage alloc] initWithContentsOfFile:[bundle pathForResource:@"CPApplication/SaveHighlighted.png"] size:CGSizeMake(16.0, 16.0)]];

    [saveMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Save" action:@selector(saveDocument:) keyEquivalent:@"s"]];
    [saveMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Save As" action:@selector(saveDocumentAs:) keyEquivalent:nil]];

    [saveMenuItem setSubmenu:saveMenu];

    [mainMenu addItem:saveMenuItem];

    var editMenuItem = [[CPMenuItem alloc] initWithTitle:@"Edit" action:nil keyEquivalent:nil],
        editMenu = [[CPMenu alloc] initWithTitle:@"Edit"],

        undoMenuItem = [[CPMenuItem alloc] initWithTitle:@"Undo" action:@selector(undo:) keyEquivalent:CPUndoKeyEquivalent],
        redoMenuItem = [[CPMenuItem alloc] initWithTitle:@"Redo" action:@selector(redo:) keyEquivalent:CPRedoKeyEquivalent];

    [undoMenuItem setKeyEquivalentModifierMask:CPUndoKeyEquivalentModifierMask];
    [redoMenuItem setKeyEquivalentModifierMask:CPRedoKeyEquivalentModifierMask];

    [editMenu addItem:undoMenuItem];
    [editMenu addItem:redoMenuItem];

    [editMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Cut" action:@selector(cut:) keyEquivalent:@"x"]];
    [editMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Copy" action:@selector(copy:) keyEquivalent:@"c"]];
    [editMenu addItem:[[CPMenuItem alloc] initWithTitle:@"Paste" action:@selector(paste:) keyEquivalent:@"v"]];

    [editMenuItem setSubmenu:editMenu];
    [editMenuItem setHidden:YES];

    [mainMenu addItem:editMenuItem];

    [mainMenu addItem:[CPMenuItem separatorItem]];

    [CPApp setMainMenu:mainMenu];
}

+ (void)cibDidFinishLoading:(CPCib)aCib
{
    [self performActions];
}

+ (void)cibDidFailToLoad:(CPCib)aCib
{
    throw new Error("Could not load main cib file (Did you forget to nib2cib it?).");
}

+ (void)reset
{
    _CPAppBootstrapperActions = nil;
}

@end


@implementation CPEvent (CPApplicationModifierFlags)

/*!
Returns the currently pressed modifier flags.
*/
+ (unsigned)modifierFlags
{
    return CPEventModifierFlags;
}

@end
Something went wrong with that request. Please try again.