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