Browse Source

clean up AsyncTask

dmuratshin 8 years ago
parent
commit
bd5888e3db

+ 5 - 0
examples/Demo/src/TestHttp.h

@@ -33,6 +33,7 @@ public:
         task = HttpRequestTask::create();
         task->setUrl("http://oxygine.org/emscripten/MPHello.js.gz");
         task->setFileName("somefile.abc");
+        addRef();//protect self from auto delete, will be released from TestHttp::loaded
         task->addEventListener(HttpRequestTask::COMPLETE, CLOSURE(this, &TestHttp::loaded));
         task->addEventListener(HttpRequestTask::PROGRESS, CLOSURE(this, &TestHttp::progress));
         task->run();
@@ -53,6 +54,7 @@ public:
         for (int i = 0; i < 256; ++i)
             postBody.push_back(i);
         task->setPostData(postBody);
+        addRef();//protect self from auto delete, will be released from TestHttp::onPostLoaded
         task->addEventListener(HttpRequestTask::COMPLETE, CLOSURE(this, &TestHttp::onPostLoaded));
         task->run();
 
@@ -100,6 +102,7 @@ public:
         {
             OX_ASSERT(res[i] == i);
         }
+        releaseRef();
     }
 
     void dateTimeLoaded(Event* event)
@@ -122,5 +125,7 @@ public:
         {
             notify("file loaded");
         }
+
+        releaseRef();
     }
 };

+ 4 - 1
examples/Demo/src/example.cpp

@@ -86,7 +86,10 @@ public:
         addButton("polygon", "Polygon");
         addButton("inputtext", "Input Text");
         addButton("openbrowser", "Open Browser");
-        addButton("http", "Http requests");
+
+        if (HttpRequestTask::create())
+            addButton("http", "Http requests");
+
         addButton("tweenpp", "Post Processing Tweens");
 
         _color = Color::Red;

+ 22 - 50
oxygine/src/oxygine/AsyncTask.cpp

@@ -3,12 +3,7 @@
 #include <typeinfo>
 namespace oxygine
 {
-    const int successID = sysEventID('s', 'c', 'm');
-    //const int customID = sysEventID('s', 'c', 'm');
-    const int runID = sysEventID('r', 'u', 'n');
-    const int errorID = sysEventID('s', 'e', 'r');
-
-    AsyncTask::AsyncTask() : _status(status_not_started), _mainThreadSync(false), _uiThreadSync(false)
+    AsyncTask::AsyncTask() : _status(status_not_started), _mainThreadSync(true), _uiThreadSync(false)
     {
 
     }
@@ -18,6 +13,16 @@ namespace oxygine
 
     }
 
+    void AsyncTask::sync(const std::function< void()>& f)
+    {
+        addRef();
+        core::getMainThreadDispatcher().postCallback([ = ]()
+        {
+            f();
+            releaseRef();
+        });
+    }
+
     void AsyncTask::run()
     {
         _prerun();
@@ -25,40 +30,16 @@ namespace oxygine
 
         OX_ASSERT(_status == status_not_started);
         _status = status_inprogress;
-        if (!syncEvent(runID))
-            _run();
-    }
-
-    void AsyncTask::threadCB(const ThreadDispatcher::message& msg)
-    {
-        ((AsyncTask*)msg.cbData)->_threadCB(msg);
-    }
 
-    void AsyncTask::_threadCB(const ThreadDispatcher::message& msg)
-    {
-        switch (msg.msgid)
+        sync([ = ]()
         {
-            case successID:
-                _complete();
-                break;
-            case errorID:
-                _error();
-                break;
-            case runID:
-                _run();
-                break;
-            case customID:
-                _custom(msg);
-                break;
-            default:
-                break;
-        }
-        if (msg.msgid != customID)
-            releaseRef();
+            _run();
+        });
     }
 
     void AsyncTask::_complete()
     {
+        OX_ASSERT(core::isMainThread());
         log::messageln("AsyncTask::_complete %d - %s", getObjectID(), typeid(*this).name());
 
         _status = status_completed;
@@ -78,6 +59,7 @@ namespace oxygine
 
     void AsyncTask::_error()
     {
+        OX_ASSERT(core::isMainThread());
         log::messageln("AsyncTask::_error %d - %s", getObjectID(), typeid(*this).name());
 
         _status = status_failed;
@@ -89,29 +71,19 @@ namespace oxygine
         dispatchEvent(&ev);
     }
 
-
-    bool AsyncTask::syncEvent(int msgid, void* arg1, void* arg2)
-    {
-        if (_mainThreadSync)
-        {
-            if (msgid != customID)
-                addRef();
-            core::getMainThreadDispatcher().postCallback(msgid, arg1, arg2, AsyncTask::threadCB, this);
-            return true;
-        }
-
-        return false;
-    }
-
     void AsyncTask::onComplete()
     {
-        if (!syncEvent(successID, 0, 0))
+        sync([ = ]()
+        {
             _complete();
+        });
     }
 
     void AsyncTask::onError()
     {
-        if (!syncEvent(errorID, 0, 0))
+        sync([ = ]()
+        {
             _error();
+        });
     }
 }

+ 3 - 4
oxygine/src/oxygine/AsyncTask.h

@@ -50,6 +50,9 @@ namespace oxygine
         void onError();
         void onComplete();
 
+
+        void sync(const std::function< void()>& f);
+
         status _status;
 
         friend class AsyncTaskManager;
@@ -66,14 +69,10 @@ namespace oxygine
         virtual void _finalize(bool error) {}
         virtual void _dispatchComplete();
 
-        enum { customID = sysEventID('s', 'c', 's') };
-        bool syncEvent(int msgid, void* arg1 = 0, void* arg2 = 0);
-
     private:
 
         void _complete();
         void _error();
-        void _custom(const ThreadDispatcher::message& m) { _onCustom(m); }
 
 
         static void threadCB(const ThreadDispatcher::message&);

+ 2 - 2
oxygine/src/oxygine/HttpRequestTask.cpp

@@ -112,10 +112,10 @@ namespace oxygine
 
     void HttpRequestTask::progress(int loaded, int total)
     {
-        if (!syncEvent(customID, (void*)(size_t)loaded, (void*)(size_t)total))
+        sync([ = ]()
         {
             dispatchProgress(loaded, total);
-        }
+        });
     }
 
     void HttpRequestTask::_onError()

+ 1 - 0
oxygine/src/oxygine/HttpRequestTask.h

@@ -53,6 +53,7 @@ namespace oxygine
         void setUrl(const std::string& url);
         void setFileName(const std::string& name);
         void setCacheEnabled(bool enabled);
+        /**by default only response code == 200 is succeded, other codes are dispatching Event::ERROR*/
         void setSuccessOnAnyResponseCode(bool en) { _successOnAnyResponceCode = en; }
 
     protected:

+ 25 - 64
oxygine/src/oxygine/core/curl/HttpRequestCurlTask.cpp

@@ -17,62 +17,9 @@ namespace oxygine
         return new HttpRequestTaskCURL;
     }
 
-    const unsigned int ID_DONE = sysEventID('C', 'D', 'N');
-    const unsigned int ID_PROGRESS = sysEventID('C', 'P', 'R');
+    const unsigned int ID_FINISH = 3423;
 
-    void mainThreadFunc(const ThreadDispatcher::message& msg)
-    {
-        switch (msg.msgid)
-        {
-            case ID_DONE:
-            {
-                CURL* easy = (CURL*)msg.arg1;
-
-                HttpRequestTaskCURL* task = 0;
-                curl_easy_getinfo(easy, CURLINFO_PRIVATE, &task);
-
-                bool ok = (size_t)msg.arg2 == CURLE_OK;
-                if (ok)
-                {
-                    int response = 0;
-                    curl_easy_getinfo(easy, CURLINFO_RESPONSE_CODE, &response);
-                    task->_responseCode = response;
-                    //ok = response == 200;
-                }
-
-#if 0
-                const Uint8* data = SDL_GetKeyboardState(0);
-                static bool fail = false;
-
-                if (data[SDL_SCANCODE_N])
-                    fail = true;
-                if (data[SDL_SCANCODE_M])
-                    fail = false;
-
-                if (fail)
-                    ok = false;
-#endif
-
-                if (ok)
-                {
-                    task->onComplete();
-                }
-                else
-                    task->onError();
-
-                task->releaseRef();
-            } break;
-
-            case ID_PROGRESS:
-            {
-                HttpRequestTaskCURL* task = (HttpRequestTaskCURL*)msg.cbData;
-                task->dispatchProgress((int)(size_t)msg.arg2, (int)(size_t)msg.arg1);
-            } break;
-        }
-
-    }
-
-    void* thread(void*)
+    void* curlThread(void*)
     {
         while (true)
         {
@@ -85,7 +32,7 @@ namespace oxygine
                 ThreadDispatcher::peekMessage tmsg;
                 if (_messages.peek(tmsg, true))
                 {
-                    if (tmsg.msgid == 1)
+                    if (tmsg.msgid == ID_FINISH)
                         return 0;
                     curl_multi_add_handle(multi_handle, (CURL*)tmsg.arg1);
                 }
@@ -133,7 +80,25 @@ namespace oxygine
                         {
 #ifdef OX_HAS_CPP11 //msg broken in VS2010
                             curl_multi_remove_handle(multi_handle, msg->easy_handle);
-                            core::getMainThreadDispatcher().postCallback(ID_DONE, msg->easy_handle, (void*)msg->data.result, mainThreadFunc, 0);
+
+
+                            HttpRequestTaskCURL* task = 0;
+                            curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &task);
+
+                            bool ok = msg->data.result == CURLE_OK;
+                            if (ok)
+                            {
+                                int response = 0;
+                                curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &response);
+                                task->_responseCode = response;
+                            }
+
+                            if (ok)
+                                task->onComplete();
+                            else
+                                task->onError();
+
+                            task->releaseRef();
 #endif
                         }
                     }
@@ -151,12 +116,12 @@ namespace oxygine
             return;
         setCustomRequests(createCurl);
         multi_handle = curl_multi_init();
-        pthread_create(&_thread, 0, thread, 0);
+        pthread_create(&_thread, 0, curlThread, 0);
     }
 
     void HttpRequestTask::release()
     {
-        _messages.post(1, 0, 0);
+        _messages.post(ID_FINISH, 0, 0);
         pthread_join(_thread, 0);
 
         if (multi_handle)
@@ -171,7 +136,7 @@ namespace oxygine
 
     size_t HttpRequestTaskCURL::_cbXRefInfoFunction(curl_off_t dltotal, curl_off_t dlnow)
     {
-        core::getMainThreadDispatcher().postCallback(ID_PROGRESS, (void*)dltotal, (void*)dlnow, mainThreadFunc, this);
+        progress((int)dlnow, (int)dltotal);
 
         return 0;
     }
@@ -197,13 +162,9 @@ namespace oxygine
 
         size_t size = n * l;
         if (!_fname.empty())
-        {
             file::write(_handle, d, (unsigned int)size);
-        }
         else
-        {
             _response.insert(_response.end(), d, d + size);
-        }
 
         return size;
     }

+ 1 - 1
oxygine/src/oxygine/core/curl/HttpRequestCurlTask.h

@@ -20,7 +20,7 @@ namespace oxygine
     protected:
         void _setFileName(const std::string& name) {}
 
-        friend void* thread(void*);
+        friend void* curlThread(void*);
         friend void mainThreadFunc(const ThreadDispatcher::message& msg);
 
         static size_t cbWriteFunction(char* d, size_t n, size_t l, void* p);