1 /* 2 * Copyright 2001-2015 Haiku, inc. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Axel Dörfler, axeld@pinc-software.de 7 * Jerome Duval 8 * Erik Jaesler, erik@cgsoftware.com 9 */ 10 11 12 #include <Application.h> 13 14 #include <new> 15 #include <pthread.h> 16 #include <stdio.h> 17 #include <stdlib.h> 18 #include <string.h> 19 #include <strings.h> 20 #include <unistd.h> 21 22 #include <Alert.h> 23 #include <AppFileInfo.h> 24 #include <Cursor.h> 25 #include <Debug.h> 26 #include <Entry.h> 27 #include <File.h> 28 #include <Locker.h> 29 #include <MessageRunner.h> 30 #include <ObjectList.h> 31 #include <Path.h> 32 #include <PropertyInfo.h> 33 #include <RegistrarDefs.h> 34 #include <Resources.h> 35 #include <Roster.h> 36 #include <Window.h> 37 38 #include <AppMisc.h> 39 #include <AppServerLink.h> 40 #include <AutoLocker.h> 41 #include <BitmapPrivate.h> 42 #include <DraggerPrivate.h> 43 #include <LooperList.h> 44 #include <MenuWindow.h> 45 #include <PicturePrivate.h> 46 #include <PortLink.h> 47 #include <RosterPrivate.h> 48 #include <ServerMemoryAllocator.h> 49 #include <ServerProtocol.h> 50 51 52 using namespace BPrivate; 53 54 55 BApplication* be_app = NULL; 56 BMessenger be_app_messenger; 57 58 pthread_once_t sAppResourcesInitOnce = PTHREAD_ONCE_INIT; 59 BResources* BApplication::sAppResources = NULL; 60 61 62 enum { 63 kWindowByIndex, 64 kWindowByName, 65 kLooperByIndex, 66 kLooperByID, 67 kLooperByName, 68 kApplication 69 }; 70 71 72 static property_info sPropertyInfo[] = { 73 { 74 "Window", 75 {}, 76 {B_INDEX_SPECIFIER, B_REVERSE_INDEX_SPECIFIER}, 77 NULL, kWindowByIndex, 78 {}, 79 {}, 80 {} 81 }, 82 { 83 "Window", 84 {}, 85 {B_NAME_SPECIFIER}, 86 NULL, kWindowByName, 87 {}, 88 {}, 89 {} 90 }, 91 { 92 "Looper", 93 {}, 94 {B_INDEX_SPECIFIER, B_REVERSE_INDEX_SPECIFIER}, 95 NULL, kLooperByIndex, 96 {}, 97 {}, 98 {} 99 }, 100 { 101 "Looper", 102 {}, 103 {B_ID_SPECIFIER}, 104 NULL, kLooperByID, 105 {}, 106 {}, 107 {} 108 }, 109 { 110 "Looper", 111 {}, 112 {B_NAME_SPECIFIER}, 113 NULL, kLooperByName, 114 {}, 115 {}, 116 {} 117 }, 118 { 119 "Name", 120 {B_GET_PROPERTY}, 121 {B_DIRECT_SPECIFIER}, 122 NULL, kApplication, 123 {B_STRING_TYPE}, 124 {}, 125 {} 126 }, 127 { 128 "Window", 129 {B_COUNT_PROPERTIES}, 130 {B_DIRECT_SPECIFIER}, 131 NULL, kApplication, 132 {B_INT32_TYPE}, 133 {}, 134 {} 135 }, 136 { 137 "Loopers", 138 {B_GET_PROPERTY}, 139 {B_DIRECT_SPECIFIER}, 140 NULL, kApplication, 141 {B_MESSENGER_TYPE}, 142 {}, 143 {} 144 }, 145 { 146 "Windows", 147 {B_GET_PROPERTY}, 148 {B_DIRECT_SPECIFIER}, 149 NULL, kApplication, 150 {B_MESSENGER_TYPE}, 151 {}, 152 {} 153 }, 154 { 155 "Looper", 156 {B_COUNT_PROPERTIES}, 157 {B_DIRECT_SPECIFIER}, 158 NULL, kApplication, 159 {B_INT32_TYPE}, 160 {}, 161 {} 162 }, 163 {} 164 }; 165 166 167 // argc/argv 168 extern const int __libc_argc; 169 extern const char* const *__libc_argv; 170 171 172 // debugging 173 //#define DBG(x) x 174 #define DBG(x) 175 #define OUT printf 176 177 178 // #pragma mark - static helper functions 179 180 181 /*! 182 \brief Checks whether the supplied string is a valid application signature. 183 184 An error message is printed, if the string is no valid app signature. 185 186 \param signature The string to be checked. 187 188 \return A status code. 189 \retval B_OK \a signature is a valid app signature. 190 \retval B_BAD_VALUE \a signature is \c NULL or no valid app signature. 191 */ 192 static status_t 193 check_app_signature(const char* signature) 194 { 195 bool isValid = false; 196 BMimeType type(signature); 197 198 if (type.IsValid() && !type.IsSupertypeOnly() 199 && BMimeType("application").Contains(&type)) { 200 isValid = true; 201 } 202 203 if (!isValid) { 204 printf("bad signature (%s), must begin with \"application/\" and " 205 "can't conflict with existing registered mime types inside " 206 "the \"application\" media type.\n", signature); 207 } 208 209 return (isValid ? B_OK : B_BAD_VALUE); 210 } 211 212 213 // Returns the looper name for a given signature. 214 // Normally this is "AppLooperPort", but in case of the registrar it gets a 215 // special name. 216 static const char* 217 looper_name_for(const char* signature) 218 { 219 if (signature != NULL && !strcasecmp(signature, kRegistrarSignature)) 220 return BPrivate::get_roster_port_name(); 221 222 return "AppLooperPort"; 223 } 224 225 226 #ifndef RUN_WITHOUT_REGISTRAR 227 // Fills the passed BMessage with B_ARGV_RECEIVED infos. 228 static void 229 fill_argv_message(BMessage &message) 230 { 231 message.what = B_ARGV_RECEIVED; 232 233 int32 argc = __libc_argc; 234 const char* const *argv = __libc_argv; 235 236 // add argc 237 message.AddInt32("argc", argc); 238 239 // add argv 240 for (int32 i = 0; i < argc; i++) { 241 if (argv[i] != NULL) 242 message.AddString("argv", argv[i]); 243 } 244 245 // add current working directory 246 char cwd[B_PATH_NAME_LENGTH]; 247 if (getcwd(cwd, B_PATH_NAME_LENGTH)) 248 message.AddString("cwd", cwd); 249 } 250 #endif 251 252 253 // #pragma mark - BApplication 254 255 256 BApplication::BApplication(const char* signature) 257 : 258 BLooper(looper_name_for(signature)) 259 { 260 _InitData(signature, true, NULL); 261 } 262 263 264 BApplication::BApplication(const char* signature, status_t* _error) 265 : 266 BLooper(looper_name_for(signature)) 267 { 268 _InitData(signature, true, _error); 269 } 270 271 272 BApplication::BApplication(const char* signature, bool initGUI, 273 status_t* _error) 274 : 275 BLooper(looper_name_for(signature)) 276 { 277 _InitData(signature, initGUI, _error); 278 } 279 280 281 BApplication::BApplication(BMessage* data) 282 // Note: BeOS calls the private BLooper(int32, port_id, const char*) 283 // constructor here, test if it's needed 284 : 285 BLooper(looper_name_for(NULL)) 286 { 287 const char* signature = NULL; 288 data->FindString("mime_sig", &signature); 289 290 _InitData(signature, true, NULL); 291 292 bigtime_t pulseRate; 293 if (data->FindInt64("_pulse", &pulseRate) == B_OK) 294 SetPulseRate(pulseRate); 295 } 296 297 298 BApplication::BApplication(uint32 signature) 299 { 300 } 301 302 303 BApplication::BApplication(const BApplication &rhs) 304 { 305 } 306 307 308 BApplication::~BApplication() 309 { 310 Lock(); 311 312 // tell all loopers(usually windows) to quit. Also, wait for them. 313 _QuitAllWindows(true); 314 315 // unregister from the roster 316 BRoster::Private().RemoveApp(Team()); 317 318 #ifndef RUN_WITHOUT_APP_SERVER 319 // tell app_server we're quitting... 320 if (be_app) { 321 // be_app can be NULL here if the application fails to initialize 322 // correctly. For example, if it's already running and it's set to 323 // exclusive launch. 324 BPrivate::AppServerLink link; 325 link.StartMessage(B_QUIT_REQUESTED); 326 link.Flush(); 327 } 328 delete_port(fServerLink->SenderPort()); 329 delete_port(fServerLink->ReceiverPort()); 330 delete fServerLink; 331 #endif // RUN_WITHOUT_APP_SERVER 332 333 delete fServerAllocator; 334 335 // uninitialize be_app, the be_app_messenger is invalidated automatically 336 be_app = NULL; 337 } 338 339 340 BApplication& 341 BApplication::operator=(const BApplication &rhs) 342 { 343 return *this; 344 } 345 346 347 void 348 BApplication::_InitData(const char* signature, bool initGUI, status_t* _error) 349 { 350 DBG(OUT("BApplication::InitData(`%s', %p)\n", signature, _error)); 351 // check whether there exists already an application 352 if (be_app) 353 debugger("2 BApplication objects were created. Only one is allowed."); 354 355 fServerLink = new BPrivate::PortLink(-1, -1); 356 fServerAllocator = NULL; 357 fInitialWorkspace = 0; 358 //fDraggedMessage = NULL; 359 fReadyToRunCalled = false; 360 361 // initially, there is no pulse 362 fPulseRunner = NULL; 363 fPulseRate = 0; 364 365 // check signature 366 fInitError = check_app_signature(signature); 367 fAppName = signature; 368 369 #ifndef RUN_WITHOUT_REGISTRAR 370 bool isRegistrar = signature 371 && strcasecmp(signature, kRegistrarSignature) == 0; 372 // get team and thread 373 team_id team = Team(); 374 thread_id thread = BPrivate::main_thread_for(team); 375 #endif 376 377 // get app executable ref 378 entry_ref ref; 379 if (fInitError == B_OK) { 380 fInitError = BPrivate::get_app_ref(&ref); 381 if (fInitError != B_OK) { 382 DBG(OUT("BApplication::InitData(): Failed to get app ref: %s\n", 383 strerror(fInitError))); 384 } 385 } 386 387 // get the BAppFileInfo and extract the information we need 388 uint32 appFlags = B_REG_DEFAULT_APP_FLAGS; 389 if (fInitError == B_OK) { 390 BAppFileInfo fileInfo; 391 BFile file(&ref, B_READ_ONLY); 392 fInitError = fileInfo.SetTo(&file); 393 if (fInitError == B_OK) { 394 fileInfo.GetAppFlags(&appFlags); 395 char appFileSignature[B_MIME_TYPE_LENGTH]; 396 // compare the file signature and the supplied signature 397 if (fileInfo.GetSignature(appFileSignature) == B_OK 398 && strcasecmp(appFileSignature, signature) != 0) { 399 printf("Signature in rsrc doesn't match constructor arg. (%s, %s)\n", 400 signature, appFileSignature); 401 } 402 } else { 403 DBG(OUT("BApplication::InitData(): Failed to get info from: " 404 "BAppFileInfo: %s\n", strerror(fInitError))); 405 } 406 } 407 408 #ifndef RUN_WITHOUT_REGISTRAR 409 // check whether be_roster is valid 410 if (fInitError == B_OK && !isRegistrar 411 && !BRoster::Private().IsMessengerValid(false)) { 412 printf("FATAL: be_roster is not valid. Is the registrar running?\n"); 413 fInitError = B_NO_INIT; 414 } 415 416 // check whether or not we are pre-registered 417 bool preRegistered = false; 418 app_info appInfo; 419 if (fInitError == B_OK && !isRegistrar) { 420 if (BRoster::Private().IsAppRegistered(&ref, team, 0, &preRegistered, 421 &appInfo) != B_OK) { 422 preRegistered = false; 423 } 424 } 425 if (preRegistered) { 426 // we are pre-registered => the app info has been filled in 427 // Check whether we need to replace the looper port with a port 428 // created by the roster. 429 if (appInfo.port >= 0 && appInfo.port != fMsgPort) { 430 delete_port(fMsgPort); 431 fMsgPort = appInfo.port; 432 } else 433 appInfo.port = fMsgPort; 434 // check the signature and correct it, if necessary, also the case 435 if (strcmp(appInfo.signature, fAppName)) 436 BRoster::Private().SetSignature(team, fAppName); 437 // complete the registration 438 fInitError = BRoster::Private().CompleteRegistration(team, thread, 439 appInfo.port); 440 } else if (fInitError == B_OK) { 441 // not pre-registered -- try to register the application 442 team_id otherTeam = -1; 443 // the registrar must not register 444 if (!isRegistrar) { 445 fInitError = BRoster::Private().AddApplication(signature, &ref, 446 appFlags, team, thread, fMsgPort, true, NULL, &otherTeam); 447 if (fInitError != B_OK) { 448 DBG(OUT("BApplication::InitData(): Failed to add app: %s\n", 449 strerror(fInitError))); 450 } 451 } 452 if (fInitError == B_ALREADY_RUNNING) { 453 // An instance is already running and we asked for 454 // single/exclusive launch. Send our argv to the running app. 455 // Do that only, if the app is NOT B_ARGV_ONLY. 456 if (otherTeam >= 0) { 457 BMessenger otherApp(NULL, otherTeam); 458 app_info otherAppInfo; 459 if (__libc_argc > 1 460 && be_roster->GetRunningAppInfo(otherTeam, &otherAppInfo) 461 == B_OK 462 && (otherAppInfo.flags & B_ARGV_ONLY) != 0) { 463 // create an B_ARGV_RECEIVED message 464 BMessage argvMessage(B_ARGV_RECEIVED); 465 fill_argv_message(argvMessage); 466 467 // replace the first argv string with the path of the 468 // other application 469 BPath path; 470 if (path.SetTo(&otherAppInfo.ref) == B_OK) 471 argvMessage.ReplaceString("argv", 0, path.Path()); 472 473 // send the message 474 otherApp.SendMessage(&argvMessage); 475 } else 476 otherApp.SendMessage(B_SILENT_RELAUNCH); 477 } 478 } else if (fInitError == B_OK) { 479 // the registrations was successful 480 // Create a B_ARGV_RECEIVED message and send it to ourselves. 481 // Do that even, if we are B_ARGV_ONLY. 482 // TODO: When BLooper::AddMessage() is done, use that instead of 483 // PostMessage(). 484 485 DBG(OUT("info: BApplication successfully registered.\n")); 486 487 if (__libc_argc > 1) { 488 BMessage argvMessage(B_ARGV_RECEIVED); 489 fill_argv_message(argvMessage); 490 PostMessage(&argvMessage, this); 491 } 492 // send a B_READY_TO_RUN message as well 493 PostMessage(B_READY_TO_RUN, this); 494 } else if (fInitError > B_ERRORS_END) { 495 // Registrar internal errors shouldn't fall into the user's hands. 496 fInitError = B_ERROR; 497 } 498 } 499 #else 500 // We need to have ReadyToRun called even when we're not using the registrar 501 PostMessage(B_READY_TO_RUN, this); 502 #endif // ifndef RUN_WITHOUT_REGISTRAR 503 504 if (fInitError == B_OK) { 505 // TODO: Not completely sure about the order, but this should be close. 506 507 // init be_app and be_app_messenger 508 be_app = this; 509 be_app_messenger = BMessenger(NULL, this); 510 511 // set the BHandler's name 512 SetName(ref.name); 513 514 // create meta MIME 515 BPath path; 516 if (path.SetTo(&ref) == B_OK) 517 create_app_meta_mime(path.Path(), false, true, false); 518 519 #ifndef RUN_WITHOUT_APP_SERVER 520 // app server connection and IK initialization 521 if (initGUI) 522 fInitError = _InitGUIContext(); 523 #endif // RUN_WITHOUT_APP_SERVER 524 } 525 526 // Return the error or exit, if there was an error and no error variable 527 // has been supplied. 528 if (_error) { 529 *_error = fInitError; 530 } else if (fInitError != B_OK) { 531 DBG(OUT("BApplication::InitData() failed: %s\n", strerror(fInitError))); 532 exit(0); 533 } 534 DBG(OUT("BApplication::InitData() done\n")); 535 } 536 537 538 BArchivable* 539 BApplication::Instantiate(BMessage* data) 540 { 541 if (validate_instantiation(data, "BApplication")) 542 return new BApplication(data); 543 544 return NULL; 545 } 546 547 548 status_t 549 BApplication::Archive(BMessage* data, bool deep) const 550 { 551 status_t status = BLooper::Archive(data, deep); 552 if (status < B_OK) 553 return status; 554 555 app_info info; 556 status = GetAppInfo(&info); 557 if (status < B_OK) 558 return status; 559 560 status = data->AddString("mime_sig", info.signature); 561 if (status < B_OK) 562 return status; 563 564 return data->AddInt64("_pulse", fPulseRate); 565 } 566 567 568 status_t 569 BApplication::InitCheck() const 570 { 571 return fInitError; 572 } 573 574 575 thread_id 576 BApplication::Run() 577 { 578 if (fInitError != B_OK) 579 return fInitError; 580 581 AssertLocked(); 582 583 if (fRunCalled) 584 debugger("BApplication::Run was already called. Can only be called once."); 585 586 fThread = find_thread(NULL); 587 fRunCalled = true; 588 589 task_looper(); 590 591 delete fPulseRunner; 592 return fThread; 593 } 594 595 596 void 597 BApplication::Quit() 598 { 599 bool unlock = false; 600 if (!IsLocked()) { 601 const char* name = Name(); 602 if (name == NULL) 603 name = "no-name"; 604 605 printf("ERROR - you must Lock the application object before calling " 606 "Quit(), team=%" B_PRId32 ", looper=%s\n", Team(), name); 607 unlock = true; 608 if (!Lock()) 609 return; 610 } 611 // Delete the object, if not running only. 612 if (!fRunCalled) { 613 delete this; 614 } else if (find_thread(NULL) != fThread) { 615 // ToDo: why shouldn't we set fTerminating to true directly in this case? 616 // We are not the looper thread. 617 // We push a _QUIT_ into the queue. 618 // TODO: When BLooper::AddMessage() is done, use that instead of 619 // PostMessage()??? This would overtake messages that are still at 620 // the port. 621 // NOTE: We must not unlock here -- otherwise we had to re-lock, which 622 // may not work. This is bad, since, if the port is full, it 623 // won't get emptier, as the looper thread needs to lock the object 624 // before dispatching messages. 625 while (PostMessage(_QUIT_, this) == B_WOULD_BLOCK) 626 snooze(10000); 627 } else { 628 // We are the looper thread. 629 // Just set fTerminating to true which makes us fall through the 630 // message dispatching loop and return from Run(). 631 fTerminating = true; 632 } 633 634 // If we had to lock the object, unlock now. 635 if (unlock) 636 Unlock(); 637 } 638 639 640 bool 641 BApplication::QuitRequested() 642 { 643 return _QuitAllWindows(false); 644 } 645 646 647 void 648 BApplication::Pulse() 649 { 650 // supposed to be implemented by subclasses 651 } 652 653 654 void 655 BApplication::ReadyToRun() 656 { 657 // supposed to be implemented by subclasses 658 } 659 660 661 void 662 BApplication::MessageReceived(BMessage* message) 663 { 664 switch (message->what) { 665 case B_COUNT_PROPERTIES: 666 case B_GET_PROPERTY: 667 case B_SET_PROPERTY: 668 { 669 int32 index; 670 BMessage specifier; 671 int32 what; 672 const char* property = NULL; 673 if (message->GetCurrentSpecifier(&index, &specifier, &what, 674 &property) < B_OK 675 || !ScriptReceived(message, index, &specifier, what, 676 property)) { 677 BLooper::MessageReceived(message); 678 } 679 break; 680 } 681 682 case B_SILENT_RELAUNCH: 683 // Sent to a B_SINGLE_LAUNCH application when it's launched again 684 // (see _InitData()) 685 be_roster->ActivateApp(Team()); 686 break; 687 688 case kMsgAppServerRestarted: 689 _ReconnectToServer(); 690 break; 691 692 case kMsgDeleteServerMemoryArea: 693 { 694 int32 serverArea; 695 if (message->FindInt32("server area", &serverArea) == B_OK) { 696 // The link is not used, but we currently borrow its lock 697 BPrivate::AppServerLink link; 698 fServerAllocator->RemoveArea(serverArea); 699 } 700 break; 701 } 702 703 default: 704 BLooper::MessageReceived(message); 705 } 706 } 707 708 709 void 710 BApplication::ArgvReceived(int32 argc, char** argv) 711 { 712 // supposed to be implemented by subclasses 713 } 714 715 716 void 717 BApplication::AppActivated(bool active) 718 { 719 // supposed to be implemented by subclasses 720 } 721 722 723 void 724 BApplication::RefsReceived(BMessage* message) 725 { 726 // supposed to be implemented by subclasses 727 } 728 729 730 void 731 BApplication::AboutRequested() 732 { 733 // supposed to be implemented by subclasses 734 } 735 736 737 BHandler* 738 BApplication::ResolveSpecifier(BMessage* message, int32 index, 739 BMessage* specifier, int32 what, const char* property) 740 { 741 BPropertyInfo propInfo(sPropertyInfo); 742 status_t err = B_OK; 743 uint32 data; 744 745 if (propInfo.FindMatch(message, 0, specifier, what, property, &data) >= 0) { 746 switch (data) { 747 case kWindowByIndex: 748 { 749 int32 index; 750 err = specifier->FindInt32("index", &index); 751 if (err != B_OK) 752 break; 753 754 if (what == B_REVERSE_INDEX_SPECIFIER) 755 index = CountWindows() - index; 756 757 BWindow* window = WindowAt(index); 758 if (window != NULL) { 759 message->PopSpecifier(); 760 BMessenger(window).SendMessage(message); 761 } else 762 err = B_BAD_INDEX; 763 break; 764 } 765 766 case kWindowByName: 767 { 768 const char* name; 769 err = specifier->FindString("name", &name); 770 if (err != B_OK) 771 break; 772 773 for (int32 i = 0;; i++) { 774 BWindow* window = WindowAt(i); 775 if (window == NULL) { 776 err = B_NAME_NOT_FOUND; 777 break; 778 } 779 if (window->Title() != NULL && !strcmp(window->Title(), 780 name)) { 781 message->PopSpecifier(); 782 BMessenger(window).SendMessage(message); 783 break; 784 } 785 } 786 break; 787 } 788 789 case kLooperByIndex: 790 { 791 int32 index; 792 err = specifier->FindInt32("index", &index); 793 if (err != B_OK) 794 break; 795 796 if (what == B_REVERSE_INDEX_SPECIFIER) 797 index = CountLoopers() - index; 798 799 BLooper* looper = LooperAt(index); 800 if (looper != NULL) { 801 message->PopSpecifier(); 802 BMessenger(looper).SendMessage(message); 803 } else 804 err = B_BAD_INDEX; 805 806 break; 807 } 808 809 case kLooperByID: 810 // TODO: implement getting looper by ID! 811 break; 812 813 case kLooperByName: 814 { 815 const char* name; 816 err = specifier->FindString("name", &name); 817 if (err != B_OK) 818 break; 819 820 for (int32 i = 0;; i++) { 821 BLooper* looper = LooperAt(i); 822 if (looper == NULL) { 823 err = B_NAME_NOT_FOUND; 824 break; 825 } 826 if (looper->Name() != NULL 827 && strcmp(looper->Name(), name) == 0) { 828 message->PopSpecifier(); 829 BMessenger(looper).SendMessage(message); 830 break; 831 } 832 } 833 break; 834 } 835 836 case kApplication: 837 return this; 838 } 839 } else { 840 return BLooper::ResolveSpecifier(message, index, specifier, what, 841 property); 842 } 843 844 if (err != B_OK) { 845 BMessage reply(B_MESSAGE_NOT_UNDERSTOOD); 846 reply.AddInt32("error", err); 847 reply.AddString("message", strerror(err)); 848 message->SendReply(&reply); 849 } 850 851 return NULL; 852 853 } 854 855 856 void 857 BApplication::ShowCursor() 858 { 859 BPrivate::AppServerLink link; 860 link.StartMessage(AS_SHOW_CURSOR); 861 link.Flush(); 862 } 863 864 865 void 866 BApplication::HideCursor() 867 { 868 BPrivate::AppServerLink link; 869 link.StartMessage(AS_HIDE_CURSOR); 870 link.Flush(); 871 } 872 873 874 void 875 BApplication::ObscureCursor() 876 { 877 BPrivate::AppServerLink link; 878 link.StartMessage(AS_OBSCURE_CURSOR); 879 link.Flush(); 880 } 881 882 883 bool 884 BApplication::IsCursorHidden() const 885 { 886 BPrivate::AppServerLink link; 887 int32 status = B_ERROR; 888 link.StartMessage(AS_QUERY_CURSOR_HIDDEN); 889 link.FlushWithReply(status); 890 891 return status == B_OK; 892 } 893 894 895 void 896 BApplication::SetCursor(const void* cursorData) 897 { 898 BCursor cursor(cursorData); 899 SetCursor(&cursor, true); 900 // forces the cursor to be sync'ed 901 } 902 903 904 void 905 BApplication::SetCursor(const BCursor* cursor, bool sync) 906 { 907 BPrivate::AppServerLink link; 908 link.StartMessage(AS_SET_CURSOR); 909 link.Attach<bool>(sync); 910 link.Attach<int32>(cursor->fServerToken); 911 912 if (sync) { 913 int32 code; 914 link.FlushWithReply(code); 915 } else 916 link.Flush(); 917 } 918 919 920 int32 921 BApplication::CountWindows() const 922 { 923 return _CountWindows(false); 924 // we're ignoring menu windows 925 } 926 927 928 BWindow* 929 BApplication::WindowAt(int32 index) const 930 { 931 return _WindowAt(index, false); 932 // we're ignoring menu windows 933 } 934 935 936 int32 937 BApplication::CountLoopers() const 938 { 939 AutoLocker<BLooperList> ListLock(gLooperList); 940 if (ListLock.IsLocked()) 941 return gLooperList.CountLoopers(); 942 943 // Some bad, non-specific thing has happened 944 return B_ERROR; 945 } 946 947 948 BLooper* 949 BApplication::LooperAt(int32 index) const 950 { 951 BLooper* looper = NULL; 952 AutoLocker<BLooperList> listLock(gLooperList); 953 if (listLock.IsLocked()) 954 looper = gLooperList.LooperAt(index); 955 956 return looper; 957 } 958 959 960 bool 961 BApplication::IsLaunching() const 962 { 963 return !fReadyToRunCalled; 964 } 965 966 967 const char* 968 BApplication::Signature() const 969 { 970 return fAppName; 971 } 972 973 974 status_t 975 BApplication::GetAppInfo(app_info* info) const 976 { 977 if (be_app == NULL || be_roster == NULL) 978 return B_NO_INIT; 979 return be_roster->GetRunningAppInfo(be_app->Team(), info); 980 } 981 982 983 BResources* 984 BApplication::AppResources() 985 { 986 if (sAppResources == NULL) 987 pthread_once(&sAppResourcesInitOnce, &_InitAppResources); 988 989 return sAppResources; 990 } 991 992 993 void 994 BApplication::DispatchMessage(BMessage* message, BHandler* handler) 995 { 996 if (handler != this) { 997 // it's not ours to dispatch 998 BLooper::DispatchMessage(message, handler); 999 return; 1000 } 1001 1002 switch (message->what) { 1003 case B_ARGV_RECEIVED: 1004 _ArgvReceived(message); 1005 break; 1006 1007 case B_REFS_RECEIVED: 1008 { 1009 // this adds the refs that are part of this message to the recent 1010 // lists, but only folders and documents are handled here 1011 entry_ref ref; 1012 int32 i = 0; 1013 while (message->FindRef("refs", i++, &ref) == B_OK) { 1014 BEntry entry(&ref, true); 1015 if (entry.InitCheck() != B_OK) 1016 continue; 1017 1018 if (entry.IsDirectory()) 1019 BRoster().AddToRecentFolders(&ref); 1020 else { 1021 // filter out applications, we only want to have documents 1022 // in the recent files list 1023 BNode node(&entry); 1024 BNodeInfo info(&node); 1025 1026 char mimeType[B_MIME_TYPE_LENGTH]; 1027 if (info.GetType(mimeType) != B_OK 1028 || strcasecmp(mimeType, B_APP_MIME_TYPE)) 1029 BRoster().AddToRecentDocuments(&ref); 1030 } 1031 } 1032 1033 RefsReceived(message); 1034 break; 1035 } 1036 1037 case B_READY_TO_RUN: 1038 if (!fReadyToRunCalled) { 1039 ReadyToRun(); 1040 fReadyToRunCalled = true; 1041 } 1042 break; 1043 1044 case B_ABOUT_REQUESTED: 1045 AboutRequested(); 1046 break; 1047 1048 case B_PULSE: 1049 Pulse(); 1050 break; 1051 1052 case B_APP_ACTIVATED: 1053 { 1054 bool active; 1055 if (message->FindBool("active", &active) == B_OK) 1056 AppActivated(active); 1057 break; 1058 } 1059 1060 case _SHOW_DRAG_HANDLES_: 1061 { 1062 bool show; 1063 if (message->FindBool("show", &show) != B_OK) 1064 break; 1065 1066 BDragger::Private::UpdateShowAllDraggers(show); 1067 break; 1068 } 1069 1070 // TODO: Handle these as well 1071 case _DISPOSE_DRAG_: 1072 case _PING_: 1073 puts("not yet handled message:"); 1074 DBG(message->PrintToStream()); 1075 break; 1076 1077 default: 1078 BLooper::DispatchMessage(message, handler); 1079 break; 1080 } 1081 } 1082 1083 1084 void 1085 BApplication::SetPulseRate(bigtime_t rate) 1086 { 1087 if (rate < 0) 1088 rate = 0; 1089 1090 // BeBook states that we have only 100,000 microseconds granularity 1091 rate -= rate % 100000; 1092 1093 if (!Lock()) 1094 return; 1095 1096 if (rate != 0) { 1097 // reset existing pulse runner, or create new one 1098 if (fPulseRunner == NULL) { 1099 BMessage pulse(B_PULSE); 1100 fPulseRunner = new BMessageRunner(be_app_messenger, &pulse, rate); 1101 } else 1102 fPulseRunner->SetInterval(rate); 1103 } else { 1104 // turn off pulse messages 1105 delete fPulseRunner; 1106 fPulseRunner = NULL; 1107 } 1108 1109 fPulseRate = rate; 1110 Unlock(); 1111 } 1112 1113 1114 status_t 1115 BApplication::GetSupportedSuites(BMessage* data) 1116 { 1117 if (data == NULL) 1118 return B_BAD_VALUE; 1119 1120 status_t status = data->AddString("suites", "suite/vnd.Be-application"); 1121 if (status == B_OK) { 1122 BPropertyInfo propertyInfo(sPropertyInfo); 1123 status = data->AddFlat("messages", &propertyInfo); 1124 if (status == B_OK) 1125 status = BLooper::GetSupportedSuites(data); 1126 } 1127 1128 return status; 1129 } 1130 1131 1132 status_t 1133 BApplication::Perform(perform_code d, void* arg) 1134 { 1135 return BLooper::Perform(d, arg); 1136 } 1137 1138 1139 void BApplication::_ReservedApplication1() {} 1140 void BApplication::_ReservedApplication2() {} 1141 void BApplication::_ReservedApplication3() {} 1142 void BApplication::_ReservedApplication4() {} 1143 void BApplication::_ReservedApplication5() {} 1144 void BApplication::_ReservedApplication6() {} 1145 void BApplication::_ReservedApplication7() {} 1146 void BApplication::_ReservedApplication8() {} 1147 1148 1149 bool 1150 BApplication::ScriptReceived(BMessage* message, int32 index, 1151 BMessage* specifier, int32 what, const char* property) 1152 { 1153 BMessage reply(B_REPLY); 1154 status_t err = B_BAD_SCRIPT_SYNTAX; 1155 1156 switch (message->what) { 1157 case B_GET_PROPERTY: 1158 if (strcmp("Loopers", property) == 0) { 1159 int32 count = CountLoopers(); 1160 err = B_OK; 1161 for (int32 i=0; err == B_OK && i<count; i++) { 1162 BMessenger messenger(LooperAt(i)); 1163 err = reply.AddMessenger("result", messenger); 1164 } 1165 } else if (strcmp("Windows", property) == 0) { 1166 int32 count = CountWindows(); 1167 err = B_OK; 1168 for (int32 i=0; err == B_OK && i<count; i++) { 1169 BMessenger messenger(WindowAt(i)); 1170 err = reply.AddMessenger("result", messenger); 1171 } 1172 } else if (strcmp("Window", property) == 0) { 1173 switch (what) { 1174 case B_INDEX_SPECIFIER: 1175 case B_REVERSE_INDEX_SPECIFIER: 1176 { 1177 int32 index = -1; 1178 err = specifier->FindInt32("index", &index); 1179 if (err != B_OK) 1180 break; 1181 1182 if (what == B_REVERSE_INDEX_SPECIFIER) 1183 index = CountWindows() - index; 1184 1185 err = B_BAD_INDEX; 1186 BWindow* window = WindowAt(index); 1187 if (window == NULL) 1188 break; 1189 1190 BMessenger messenger(window); 1191 err = reply.AddMessenger("result", messenger); 1192 break; 1193 } 1194 1195 case B_NAME_SPECIFIER: 1196 { 1197 const char* name; 1198 err = specifier->FindString("name", &name); 1199 if (err != B_OK) 1200 break; 1201 err = B_NAME_NOT_FOUND; 1202 for (int32 i = 0; i < CountWindows(); i++) { 1203 BWindow* window = WindowAt(i); 1204 if (window && window->Name() != NULL 1205 && !strcmp(window->Name(), name)) { 1206 BMessenger messenger(window); 1207 err = reply.AddMessenger("result", messenger); 1208 break; 1209 } 1210 } 1211 break; 1212 } 1213 } 1214 } else if (strcmp("Looper", property) == 0) { 1215 switch (what) { 1216 case B_INDEX_SPECIFIER: 1217 case B_REVERSE_INDEX_SPECIFIER: 1218 { 1219 int32 index = -1; 1220 err = specifier->FindInt32("index", &index); 1221 if (err != B_OK) 1222 break; 1223 1224 if (what == B_REVERSE_INDEX_SPECIFIER) 1225 index = CountLoopers() - index; 1226 1227 err = B_BAD_INDEX; 1228 BLooper* looper = LooperAt(index); 1229 if (looper == NULL) 1230 break; 1231 1232 BMessenger messenger(looper); 1233 err = reply.AddMessenger("result", messenger); 1234 break; 1235 } 1236 1237 case B_NAME_SPECIFIER: 1238 { 1239 const char* name; 1240 err = specifier->FindString("name", &name); 1241 if (err != B_OK) 1242 break; 1243 err = B_NAME_NOT_FOUND; 1244 for (int32 i = 0; i < CountLoopers(); i++) { 1245 BLooper* looper = LooperAt(i); 1246 if (looper != NULL && looper->Name() 1247 && strcmp(looper->Name(), name) == 0) { 1248 BMessenger messenger(looper); 1249 err = reply.AddMessenger("result", messenger); 1250 break; 1251 } 1252 } 1253 break; 1254 } 1255 1256 case B_ID_SPECIFIER: 1257 { 1258 // TODO 1259 debug_printf("Looper's ID specifier used but not implemented.\n"); 1260 break; 1261 } 1262 } 1263 } else if (strcmp("Name", property) == 0) 1264 err = reply.AddString("result", Name()); 1265 1266 break; 1267 1268 case B_COUNT_PROPERTIES: 1269 if (strcmp("Looper", property) == 0) 1270 err = reply.AddInt32("result", CountLoopers()); 1271 else if (strcmp("Window", property) == 0) 1272 err = reply.AddInt32("result", CountWindows()); 1273 1274 break; 1275 } 1276 if (err == B_BAD_SCRIPT_SYNTAX) 1277 return false; 1278 1279 if (err < B_OK) { 1280 reply.what = B_MESSAGE_NOT_UNDERSTOOD; 1281 reply.AddString("message", strerror(err)); 1282 } 1283 reply.AddInt32("error", err); 1284 message->SendReply(&reply); 1285 1286 return true; 1287 } 1288 1289 1290 void 1291 BApplication::BeginRectTracking(BRect rect, bool trackWhole) 1292 { 1293 BPrivate::AppServerLink link; 1294 link.StartMessage(AS_BEGIN_RECT_TRACKING); 1295 link.Attach<BRect>(rect); 1296 link.Attach<int32>(trackWhole); 1297 link.Flush(); 1298 } 1299 1300 1301 void 1302 BApplication::EndRectTracking() 1303 { 1304 BPrivate::AppServerLink link; 1305 link.StartMessage(AS_END_RECT_TRACKING); 1306 link.Flush(); 1307 } 1308 1309 1310 status_t 1311 BApplication::_SetupServerAllocator() 1312 { 1313 fServerAllocator = new (std::nothrow) BPrivate::ServerMemoryAllocator(); 1314 if (fServerAllocator == NULL) 1315 return B_NO_MEMORY; 1316 1317 return fServerAllocator->InitCheck(); 1318 } 1319 1320 1321 status_t 1322 BApplication::_InitGUIContext() 1323 { 1324 // An app_server connection is necessary for a lot of stuff, so get that first. 1325 status_t error = _ConnectToServer(); 1326 if (error != B_OK) 1327 return error; 1328 1329 // Initialize the IK after we have set be_app because of a construction 1330 // of a AppServerLink (which depends on be_app) nested inside the call 1331 // to get_menu_info. 1332 error = _init_interface_kit_(); 1333 if (error != B_OK) 1334 return error; 1335 1336 // create global system cursors 1337 B_CURSOR_SYSTEM_DEFAULT = new BCursor(B_HAND_CURSOR); 1338 B_CURSOR_I_BEAM = new BCursor(B_I_BEAM_CURSOR); 1339 1340 // TODO: would be nice to get the workspace at launch time from the registrar 1341 fInitialWorkspace = current_workspace(); 1342 1343 return B_OK; 1344 } 1345 1346 1347 status_t 1348 BApplication::_ConnectToServer() 1349 { 1350 status_t status 1351 = create_desktop_connection(fServerLink, "a<app_server", 100); 1352 if (status != B_OK) 1353 return status; 1354 1355 // AS_CREATE_APP: 1356 // 1357 // Attach data: 1358 // 1) port_id - receiver port of a regular app 1359 // 2) port_id - looper port for this BApplication 1360 // 3) team_id - team identification field 1361 // 4) int32 - handler ID token of the app 1362 // 5) char* - signature of the regular app 1363 1364 fServerLink->StartMessage(AS_CREATE_APP); 1365 fServerLink->Attach<port_id>(fServerLink->ReceiverPort()); 1366 fServerLink->Attach<port_id>(_get_looper_port_(this)); 1367 fServerLink->Attach<team_id>(Team()); 1368 fServerLink->Attach<int32>(_get_object_token_(this)); 1369 fServerLink->AttachString(fAppName); 1370 1371 area_id sharedReadOnlyArea; 1372 team_id serverTeam; 1373 port_id serverPort; 1374 1375 int32 code; 1376 if (fServerLink->FlushWithReply(code) == B_OK 1377 && code == B_OK) { 1378 // We don't need to contact the main app_server anymore 1379 // directly; we now talk to our server alter ego only. 1380 fServerLink->Read<port_id>(&serverPort); 1381 fServerLink->Read<area_id>(&sharedReadOnlyArea); 1382 fServerLink->Read<team_id>(&serverTeam); 1383 } else { 1384 fServerLink->SetSenderPort(-1); 1385 debugger("BApplication: couldn't obtain new app_server comm port"); 1386 return B_ERROR; 1387 } 1388 fServerLink->SetTargetTeam(serverTeam); 1389 fServerLink->SetSenderPort(serverPort); 1390 1391 status = _SetupServerAllocator(); 1392 if (status != B_OK) 1393 return status; 1394 1395 area_id area; 1396 uint8* base; 1397 status = fServerAllocator->AddArea(sharedReadOnlyArea, area, base, true); 1398 if (status < B_OK) 1399 return status; 1400 1401 fServerReadOnlyMemory = base; 1402 1403 return B_OK; 1404 } 1405 1406 1407 void 1408 BApplication::_ReconnectToServer() 1409 { 1410 delete_port(fServerLink->SenderPort()); 1411 delete_port(fServerLink->ReceiverPort()); 1412 invalidate_server_port(); 1413 1414 if (_ConnectToServer() != B_OK) 1415 debugger("Can't reconnect to app server!"); 1416 1417 AutoLocker<BLooperList> listLock(gLooperList); 1418 if (!listLock.IsLocked()) 1419 return; 1420 1421 uint32 count = gLooperList.CountLoopers(); 1422 for (uint32 i = 0; i < count ; i++) { 1423 BWindow* window = dynamic_cast<BWindow*>(gLooperList.LooperAt(i)); 1424 if (window == NULL) 1425 continue; 1426 BMessenger windowMessenger(window); 1427 windowMessenger.SendMessage(kMsgAppServerRestarted); 1428 } 1429 1430 reconnect_bitmaps_to_app_server(); 1431 reconnect_pictures_to_app_server(); 1432 } 1433 1434 1435 #if 0 1436 void 1437 BApplication::send_drag(BMessage* message, int32 vs_token, BPoint offset, 1438 BRect dragRect, BHandler* replyTo) 1439 { 1440 // TODO: implement 1441 } 1442 1443 1444 void 1445 BApplication::send_drag(BMessage* message, int32 vs_token, BPoint offset, 1446 int32 bitmapToken, drawing_mode dragMode, BHandler* replyTo) 1447 { 1448 // TODO: implement 1449 } 1450 1451 1452 void 1453 BApplication::write_drag(_BSession_* session, BMessage* message) 1454 { 1455 // TODO: implement 1456 } 1457 #endif 1458 1459 1460 bool 1461 BApplication::_WindowQuitLoop(bool quitFilePanels, bool force) 1462 { 1463 int32 index = 0; 1464 while (true) { 1465 BWindow* window = WindowAt(index); 1466 if (window == NULL) 1467 break; 1468 1469 // NOTE: the window pointer might be stale, in case the looper 1470 // was already quit by quitting an earlier looper... but fortunately, 1471 // we can still call Lock() on the invalid pointer, and it 1472 // will return false... 1473 if (!window->Lock()) 1474 continue; 1475 1476 // don't quit file panels if we haven't been asked for it 1477 if (!quitFilePanels && window->IsFilePanel()) { 1478 window->Unlock(); 1479 index++; 1480 continue; 1481 } 1482 1483 if (!force && !window->QuitRequested() 1484 && !(quitFilePanels && window->IsFilePanel())) { 1485 // the window does not want to quit, so we don't either 1486 window->Unlock(); 1487 return false; 1488 } 1489 1490 // Re-lock, just to make sure that the user hasn't done nasty 1491 // things in QuitRequested(). Quit() unlocks fully, thus 1492 // double-locking is harmless. 1493 if (window->Lock()) 1494 window->Quit(); 1495 1496 index = 0; 1497 // we need to continue at the start of the list again - it 1498 // might have changed 1499 } 1500 1501 return true; 1502 } 1503 1504 1505 bool 1506 BApplication::_QuitAllWindows(bool force) 1507 { 1508 AssertLocked(); 1509 1510 // We need to unlock here because BWindow::QuitRequested() must be 1511 // allowed to lock the application - which would cause a deadlock 1512 Unlock(); 1513 1514 bool quit = _WindowQuitLoop(false, force); 1515 if (quit) 1516 quit = _WindowQuitLoop(true, force); 1517 1518 Lock(); 1519 1520 return quit; 1521 } 1522 1523 1524 void 1525 BApplication::_ArgvReceived(BMessage* message) 1526 { 1527 ASSERT(message != NULL); 1528 1529 // build the argv vector 1530 status_t error = B_OK; 1531 int32 argc = 0; 1532 char** argv = NULL; 1533 if (message->FindInt32("argc", &argc) == B_OK && argc > 0) { 1534 // allocate a NULL terminated array 1535 argv = new(std::nothrow) char*[argc + 1]; 1536 if (argv == NULL) 1537 return; 1538 1539 // copy the arguments 1540 for (int32 i = 0; error == B_OK && i < argc; i++) { 1541 const char* arg = NULL; 1542 error = message->FindString("argv", i, &arg); 1543 if (error == B_OK && arg) { 1544 argv[i] = strdup(arg); 1545 if (argv[i] == NULL) 1546 error = B_NO_MEMORY; 1547 } else 1548 argc = i; 1549 } 1550 1551 argv[argc] = NULL; 1552 } 1553 1554 // call the hook 1555 if (error == B_OK && argc > 0) 1556 ArgvReceived(argc, argv); 1557 1558 if (error != B_OK) { 1559 printf("Error parsing B_ARGV_RECEIVED message. Message:\n"); 1560 message->PrintToStream(); 1561 } 1562 1563 // cleanup 1564 if (argv) { 1565 for (int32 i = 0; i < argc; i++) 1566 free(argv[i]); 1567 delete[] argv; 1568 } 1569 } 1570 1571 1572 uint32 1573 BApplication::InitialWorkspace() 1574 { 1575 return fInitialWorkspace; 1576 } 1577 1578 1579 int32 1580 BApplication::_CountWindows(bool includeMenus) const 1581 { 1582 uint32 count = 0; 1583 for (int32 i = 0; i < gLooperList.CountLoopers(); i++) { 1584 BWindow* window = dynamic_cast<BWindow*>(gLooperList.LooperAt(i)); 1585 if (window != NULL && !window->fOffscreen && (includeMenus 1586 || dynamic_cast<BMenuWindow*>(window) == NULL)) { 1587 count++; 1588 } 1589 } 1590 1591 return count; 1592 } 1593 1594 1595 BWindow* 1596 BApplication::_WindowAt(uint32 index, bool includeMenus) const 1597 { 1598 AutoLocker<BLooperList> listLock(gLooperList); 1599 if (!listLock.IsLocked()) 1600 return NULL; 1601 1602 uint32 count = gLooperList.CountLoopers(); 1603 for (uint32 i = 0; i < count && index < count; i++) { 1604 BWindow* window = dynamic_cast<BWindow*>(gLooperList.LooperAt(i)); 1605 if (window == NULL || (window != NULL && window->fOffscreen) 1606 || (!includeMenus && dynamic_cast<BMenuWindow*>(window) != NULL)) { 1607 index++; 1608 continue; 1609 } 1610 1611 if (i == index) 1612 return window; 1613 } 1614 1615 return NULL; 1616 } 1617 1618 1619 /*static*/ void 1620 BApplication::_InitAppResources() 1621 { 1622 entry_ref ref; 1623 bool found = false; 1624 1625 // App is already running. Get its entry ref with 1626 // GetAppInfo() 1627 app_info appInfo; 1628 if (be_app && be_app->GetAppInfo(&appInfo) == B_OK) { 1629 ref = appInfo.ref; 1630 found = true; 1631 } else { 1632 // Run() hasn't been called yet 1633 found = BPrivate::get_app_ref(&ref) == B_OK; 1634 } 1635 1636 if (!found) 1637 return; 1638 1639 BFile file(&ref, B_READ_ONLY); 1640 if (file.InitCheck() != B_OK) 1641 return; 1642 1643 BResources* resources = new (std::nothrow) BResources(&file, false); 1644 if (resources == NULL || resources->InitCheck() != B_OK) { 1645 delete resources; 1646 return; 1647 } 1648 1649 sAppResources = resources; 1650 } 1651