1 // TestApp.cpp 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 #include <Autolock.h> 8 9 #include <TestApp.h> 10 11 // TestHandler 12 13 // MessageReceived 14 void 15 BTestHandler::MessageReceived(BMessage *message) 16 { 17 // clone and push it 18 BMessage *clone = new BMessage(*message); 19 fQueue.Lock(); 20 fQueue.AddMessage(clone); 21 fQueue.Unlock(); 22 } 23 24 // Queue 25 BMessageQueue & 26 BTestHandler::Queue() 27 { 28 return fQueue; 29 } 30 31 32 // TestApp 33 34 static status_t sInitError; 35 36 // constructor 37 BTestApp::BTestApp(const char *signature) 38 : BApplication(signature, &sInitError), 39 fAppThread(B_ERROR), 40 fHandlers() 41 { 42 if (sInitError != B_OK) { 43 fprintf(stderr, "BTestApp::BTestApp(): Failed to create BApplication: " 44 "%s\n", strerror(sInitError)); 45 exit(1); 46 } 47 48 CreateTestHandler(); 49 Unlock(); 50 } 51 52 // destructor 53 BTestApp::~BTestApp() 54 { 55 int32 count = fHandlers.CountItems(); 56 for (int32 i = count - 1; i >= 0; i--) 57 DeleteTestHandler(TestHandlerAt(i)); 58 } 59 60 // Init 61 status_t 62 BTestApp::Init() 63 { 64 status_t error = B_OK; 65 fAppThread = spawn_thread(&_AppThreadStart, "query app", 66 B_NORMAL_PRIORITY, this); 67 if (fAppThread < 0) 68 error = fAppThread; 69 else { 70 error = resume_thread(fAppThread); 71 if (error != B_OK) 72 kill_thread(fAppThread); 73 } 74 if (error != B_OK) 75 fAppThread = B_ERROR; 76 return error; 77 } 78 79 // Terminate 80 void 81 BTestApp::Terminate() 82 { 83 PostMessage(B_QUIT_REQUESTED, this); 84 int32 result; 85 wait_for_thread(fAppThread, &result); 86 } 87 88 // ReadyToRun 89 void 90 BTestApp::ReadyToRun() 91 { 92 } 93 94 // CreateTestHandler 95 BTestHandler * 96 BTestApp::CreateTestHandler() 97 { 98 BTestHandler *handler = new BTestHandler; 99 Lock(); 100 AddHandler(handler); 101 fHandlers.AddItem(handler); 102 Unlock(); 103 return handler; 104 } 105 106 // DeleteTestHandler 107 bool 108 BTestApp::DeleteTestHandler(BTestHandler *handler) 109 { 110 bool result = false; 111 Lock(); 112 result = fHandlers.RemoveItem(handler); 113 if (result) 114 RemoveHandler(handler); 115 Unlock(); 116 if (result) 117 delete handler; 118 return result; 119 } 120 121 // Handler 122 BTestHandler & 123 BTestApp::Handler() 124 { 125 // The returned handler must never passed to DeleteTestHandler() by the 126 // caller! 127 return *TestHandlerAt(0); 128 } 129 130 // TestHandlerAt 131 BTestHandler * 132 BTestApp::TestHandlerAt(int32 index) 133 { 134 BAutolock _lock(this); 135 return (BTestHandler*)fHandlers.ItemAt(index); 136 } 137 138 // _AppThreadStart 139 int32 140 BTestApp::_AppThreadStart(void *data) 141 { 142 if (BTestApp *app = (BTestApp*)data) { 143 app->Lock(); 144 app->Run(); 145 } 146 return 0; 147 } 148 149