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