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