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