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