Esempio n. 1
0
static void aio_complete_handler(void *context, AIOStatus status)
{
    Callback *cb = (Callback *)context;
    assert(cb);
    cb->exec(status);
    delete cb;
}
Esempio n. 2
0
/**
 * Socket associated with client connection has indicated it has data ready
 * to read. We want to determine which client connection and receive the data
 * from it.
 */
void Server::handleServerConnection(int sckt)
{
    //determine connection
    ServerConnection* connection = mConnections->getServerConnection(sckt);
    if (0 != connection)
    {
        Callback* callback = getCallback();
        try
        {
            //receive data
            std::vector<char> result = connection->performReceive();

            if (0 != callback)
            {
                callback->receiveComplete(connection->getIdentifier(), &(result[0]),
                        result.size());
            }

        } catch (std::runtime_error)
        {
            if (0 != callback)
            {
                callback->disconnected(connection->getIdentifier());
            }
            //error retrieving data from client, connection is bad, need to remove it
            mConnections->removeServerConnection(sckt);
        }
    }
}
void ThreadPoolNormal::ExecuteTask() {
  while(1) { 
    queue_lock_.lock(); 

    while(tasks_.empty() && flagstop_ == false) {        
      queue_empty_.wait(&queue_lock_);     
    }

    /* Either pool was stopped or task was added */

    if(flagstop_ == true) {               //Stop the Pool
      break; 
    } 
    else {                               // Pop from the queue
        Callback<void>* task = tasks_.front();  
        bool task_type = task->once();
        tasks_.pop();
        queue_lock_.unlock();

        (*task)();    //Execute the task

        if(task_type == false) { // Delete the task if of type CallbackMany
          delete task;  
        }
    }
  }  
  queue_lock_.unlock();
}
Esempio n. 4
0
static void tim_handler(int num) {
	IRQFunction irqfunc;
	TIM_TypeDef *tim = timers[num];
	uint16_t sr = tim->SR;
	Callback *callback = NULL;
	
	if (sr & TIM_SR_UIF) {
		callback = overflowcallbacks[num-1];
		tim->SR &= ~TIM_SR_UIF;
	} else if (sr & TIM_SR_CC1IF) {
		callback = callbacks[num-1][0];
		tim->SR &= ~TIM_SR_CC1IF;
	} else if (sr & TIM_SR_CC2IF) {
		callback = callbacks[num-1][1];
		tim->SR &= ~TIM_SR_CC2IF;
	} else if (sr & TIM_SR_CC3IF) {
		callback = callbacks[num-1][2];
		tim->SR &= ~TIM_SR_CC3IF;
	} else if (sr & TIM_SR_CC4IF) {
		callback = callbacks[num-1][3];
		tim->SR &= ~TIM_SR_CC4IF;
	}
	
	if (callback != NULL)
		callback->call();
}
Esempio n. 5
0
static void run_exti_callback(int irq) {
	Callback *callback = exti_callbacks[irq];
	if (callback)
		callback->call();
	
	EXTI->PR = (1 << irq);
}
Esempio n. 6
0
File: engine.c Progetto: fizx/sit
void
_unregister_handler(Callback *cb, void *vnode) {
	QueryNode *node = vnode;
	unregister_data *data = cb->user_data;
	
	if(data->success) {
    return;
	}
	
	// handle the first case
	while (node->callback && node->callback->id == data->query_id) {
		Callback *old = node->callback;
		node->callback = old->next;
		if(old->free) {
			old->free(old);
		}
    data->success = true;
    return;
	}
	
	Callback *prev = node->callback;
	Callback *qc = node->callback;
	while(qc) {
		if(qc->id == data->query_id) {
			prev->next = qc->next;
			if(qc->free) {
				qc->free(qc);
			}
			data->success = true;
      return;
		}
		prev = qc;
		qc = qc->next;
	}
}
Esempio n. 7
0
FB::variant ibrowserAPI::uninstallPackage(const std::string& fileName, const boost::optional<FB::JSObjectPtr>& pcb, F_ADD)
{
    if(fileName.empty())
        return false;
    
    THREAD(&ibrowserAPI::uninstallPackage,fileName,pcb);
    
    int ret=0;
    Callback *cb = new Callback();
    cb->set("pcb",*pcb);
    cb->set("scb",*scb);
    cb->set("ecb",*ecb);
    
    while (INSTPROXY_E_OP_IN_PROGRESS == (ret = instproxy_uninstall(instproxy_client, fileName.c_str(), NULL, &ibrowserAPI::installCallback, (void*)cb)))
    {
        log("uninstallPackage %s sleep...",fileName.c_str());
        sleep(1);
    }
    
    if(INSTPROXY_E_SUCCESS != ret)
    {
        ERRO("instproxy_uninstall");
    }
    
    return true;
    
}
Esempio n. 8
0
void ibrowserAPI::ideviceEventCallback(const idevice_event_t *event, void *user_data)
{
    Callback *cb = (Callback *)user_data;
    FB::JSObjectPtr callback=cb->get("callback");
    if(callback && callback->isValid())
        callback->InvokeAsync("", FB::variant_list_of( event->event ));
}
Esempio n. 9
0
File: engine.c Progetto: fizx/sit
bool
engine_unregister(Engine *engine, long query_id) {
  Callback *cb = engine->catchall_callbacks;
  if(cb && cb->id == query_id) {
    engine->catchall_callbacks = cb->next;
    if(cb->free) {
      cb->free(cb);
    }
    return true;
  }
  Callback *prev = cb;
  while(cb) {
    if(cb->id == query_id) {
      prev->next = cb->next;
      if(cb->free) {
        cb->free(cb);
      }
      return true;
    }
    prev = cb;
    cb = cb->next;
  }
  
  unregister_data data = {
    query_id,
    false
  };
	Callback unregister;
	unregister.user_data = &data;
	unregister.handler = _unregister_handler;
	engine_each_node(engine, &unregister);
  return data.success;
}
bool CppBoundClass::invoke(NPIdentifier ident,
                           const NPVariant* arguments,
                           size_t argumentCount,
                           NPVariant* result) {
    MethodList::const_iterator end = m_methods.end();
    MethodList::const_iterator method = m_methods.find(ident);
    Callback* callback;
    if (method == end) {
        if (!m_fallbackCallback.get()) {
            VOID_TO_NPVARIANT(*result);
            return false;
        }
        callback = m_fallbackCallback.get();
    } else
        callback = (*method).second;

    // Build a CppArgumentList argument vector from the NPVariants coming in.
    CppArgumentList cppArguments(argumentCount);
    for (size_t i = 0; i < argumentCount; i++)
        cppArguments[i].set(arguments[i]);

    CppVariant cppResult;
    callback->run(cppArguments, &cppResult);

    cppResult.copyToNPVariant(result);
    return true;
}
Esempio n. 11
0
File: CopyOp.cpp Progetto: 3dcl/osg
Callback* CopyOp::operator() (const Callback* nc) const
{
    if (nc && _flags&DEEP_COPY_CALLBACKS)
    {
        // deep copy the full chain of callback
        Callback* first = osg::clone(nc, *this);
        if (!first) return 0;

        first->setNestedCallback(0);
        nc = nc->getNestedCallback();
        while (nc)
        {
            Callback* ucb = osg::clone(nc, *this);
            if (ucb)
            {
                ucb->setNestedCallback(0);
                first->addNestedCallback(ucb);
            }
            nc = nc->getNestedCallback();
        }
        return first;
    }
    else
        return const_cast<Callback*>(nc);
}
Esempio n. 12
0
bool Nuria::RestfulHttpNode::invokeMatchLater (Callback callback, const QVariantList &arguments, HttpClient *client) {
	Callback invoker (this, &RestfulHttpNode::invokeMatchNow);
	invoker.bind (callback, arguments);
	
	SlotInfo slotInfo (invoker);
	client->setSlotInfo (slotInfo);
	return true;
}
Esempio n. 13
0
void CallbackHandler::ExecuteQueuedCallbacks() {
	Callback* cb = FetchFirstCallback();
	if (!cb) return;

//	cb->isExecuting = true;
	cb->Execute();
	delete cb;
}
Esempio n. 14
0
void Freenect::depth_cb(freenect_device *dev, void *depth, uint32_t timestamp) {
	Callback * cb = (Callback * )freenect_get_user(dev);
	if (cb) {
		cb->depth.array().data.ptr = (char *)depth;
		cb->depth.dirty();
		cb->onDepth(cb->depth, timestamp); 
	}
}
Esempio n. 15
0
void Freenect::video_cb(freenect_device *dev, void *video, uint32_t timestamp) {
	Callback * cb = (Callback * )freenect_get_user(dev);
	if (cb) {
		cb->video.array().data.ptr = (char *)video;
		cb->video.dirty();
		cb->onVideo(cb->video, timestamp);
	}
}
Esempio n. 16
0
void FastCGITransport::onSendEndImpl() {
  Callback* callback = m_callback;
  std::function<void()> fn = [callback]() mutable {
      if (callback) {
        callback->onComplete();
      }
    };
  m_connection->getEventBase()->runInEventBaseThread(fn);
}
Esempio n. 17
0
FB::variant ibrowserAPI::setIdeviceEventCallback(const FB::JSObjectPtr& callback,F_ADD)
{
    Callback *cb = new Callback();
    cb->set("callback",callback);
    
    if(IDEVICE_E_SUCCESS != idevice_event_subscribe(&ibrowserAPI::ideviceEventCallback, (void *)cb))
        ERRO("idevice_event_subscribe");
    
    return true;
}
ThreadPoolFast::~ThreadPoolFast() {
  m_dispatch_.lock();
  while (! dispatch_queue_.empty()) {
    Callback<void>* task = dispatch_queue_.front();
    dispatch_queue_.pop();
    if (task && task->once()) {
      delete task;
    }
  }
  m_dispatch_.unlock();
}
Esempio n. 19
0
File: engine.c Progetto: fizx/sit
void 
callback_recurse(Engine *engine, dict *term_index, dict *query_nodes, void *doc, bool positive) {
	assert(doc);
  if(positive) {
    QueryNode *n = dictFetchValue(query_nodes, &SENTINEL);
    if (n) {
      DEBUG("recursing SENTINEL");
      callback_recurse(engine, term_index, n->children, doc, false);
    }
  }
	if(dictSize(term_index) > dictSize(query_nodes) || !positive){
		dictIterator *iterator = dictGetIterator(query_nodes);
		dictEntry *next;
	
    while ((next = dictNext(iterator))) {
      if (positive == !!dictFetchValue(term_index, dictGetKey(next))) {
		  	QueryNode *node = dictGetVal(next);
  			Callback *cb = node->callback;
        assert(node->term->owns_string);
        DEBUG("perc'd %.*s:%.*s", node->term->field.len, node->term->field.val, node->term->text.len, node->term->text.val);
  			while(cb) {
  			  DEBUG("running callback %d", cb->id);
  				cb->handler(cb, doc);
  				cb = cb->next;
  			}
  			if(node->children) {
  				callback_recurse(engine, term_index, node->children, doc, positive);
  			}
  		}
		}
    dictReleaseIterator(iterator);
	} else {
		dictIterator *iterator = dictGetIterator(term_index);
		dictEntry *next;
		QueryNode *node;

    while ((next = dictNext(iterator))) {
      if(positive == !!(node = dictFetchValue(query_nodes, dictGetKey(next)))) {
  			Callback *cb = node->callback;
  			DEBUG("perc'd %.*s:%.*s", node->term->field.len, node->term->field.val, node->term->text.len, node->term->text.val);
  			while(cb) {
  			  DEBUG("running callback %d", cb->id);
  				cb->handler(cb, doc);
  				cb = cb->next;
  			}
  			if(node->children){
  				callback_recurse(engine, term_index, node->children, doc,positive);
  			}
  		}
		}
		dictReleaseIterator(iterator);
	}
}
ThreadPoolNormal::~ThreadPoolNormal() { 
  // Clear tasks 
  queue_lock_.lock();
  while(!tasks_.empty()) {
    Callback<void>* task = tasks_.front();
    tasks_.pop();  
    if(task && task->once()) {
      delete task;
    }
  }
  queue_lock_.unlock(); 
}
Esempio n. 21
0
File: engine.c Progetto: fizx/sit
void
engine_percolate(Engine *engine, DocBuf *buffer, long doc_id) {  
  DEBUG("starting percolation");
  
  Callback *cb = engine->catchall_callbacks;
	while(cb) {
		cb->handler(cb, &doc_id);
		cb = cb->next;
	}
	
	callback_recurse(engine, buffer->term_index, engine->queries, &doc_id, true);
}
	int PhysWorld3D::OnAABBOverlap(const NewtonMaterial* const material, const NewtonBody* const body0, const NewtonBody* const body1, int threadIndex)
	{
		RigidBody3D* bodyA = static_cast<RigidBody3D*>(NewtonBodyGetUserData(body0));
		RigidBody3D* bodyB = static_cast<RigidBody3D*>(NewtonBodyGetUserData(body1));
		assert(bodyA && bodyB);

		Callback* callbackData = static_cast<Callback*>(NewtonMaterialGetMaterialPairUserData(material));
		assert(callbackData);
		assert(callbackData->aabbOverlapCallback);

		return callbackData->aabbOverlapCallback(*bodyA, *bodyB);
	}
Esempio n. 23
0
bool Nuria::RestfulHttpNode::invokeMatchNow (Callback callback, const QVariantList &arguments, HttpClient *client) {
	int resultType = callback.returnType ();
	QVariant result = callback.invoke (arguments);
	
	if ((resultType == QMetaType::QVariant && !result.isValid ()) ||
	    (resultType != QMetaType::Void && resultType != 0 &&
	     resultType != result.userType ())) {
	        return false;
	}
	
	// Send response
	return writeResponse (result, client);
}
Esempio n. 24
0
void AsyncTimeoutSet::timeoutExpired() noexcept {
  // If destroy() is called inside timeoutExpired(), delay actual destruction
  // until timeoutExpired() returns
  DestructorGuard dg(this);

  // timeoutExpired() can only be invoked directly from the event base loop.
  // It should never be invoked recursively.
  //
  // Set inTimeoutExpired_ to true, so that we won't bother rescheduling the
  // main AsyncTimeout inside timeoutExpired().  We'll always make sure this
  // is up-to-date before we return.  This simply prevents us from
  // unnecessarily modifying the main timeout heap multiple times before we
  // return.
  assert(!inTimeoutExpired_);
  inTimeoutExpired_ = true;
  SCOPE_EXIT { inTimeoutExpired_ = false; };

  // Get the current time.
  // For now we only compute the current time at the start of the loop.
  // If a callback takes a very long time to execute its timeoutExpired()
  // method, this value could potentially get stale.
  //
  // However, this should be rare, and it doesn't seem worth the overhead of
  // recomputing the current time each time around the loop.  If the value does
  // go stale, we won't invoke as many callbacks as we could.  They will have
  // to wait until the next call to timeoutExpired().  However, we could also
  // end up rescheduling the next timeoutExpired() call a bit late if now gets
  // stale.  If we find that this becomes a problem in practice we could be
  // more smart about when we recompute the current time.
  auto now = timeoutClock_.millisecondsSinceEpoch();

  while (head_ != nullptr) {
    milliseconds delta = head_->getTimeRemaining(now);
    if (delta > milliseconds(0)) {
      if (delta < atMostEveryN_) {
        delta = atMostEveryN_;
      }
      this->folly::AsyncTimeout::scheduleTimeout(delta.count());
      break;
    }

    // Remember the callback to invoke, since calling cancelTimeout()
    // on it will modify head_.
    Callback* cb = head_;
    head_->cancelTimeout();
    auto old_ctx =
      folly::RequestContext::setContext(cb->context_);
    cb->timeoutExpired();
    folly::RequestContext::setContext(old_ctx);
  }
}
Esempio n. 25
0
/*************************************************************
* @brief Removes a callback from the list of callbacks for a particular type of incoming message.
*
* @param callback	The function that was previously registered.  If NULL removes all callbacks for this type of message.
* @param pType		The type of message to unregister from (currently one of "call", "response" or "notify").
*
* @returns 0 if successful, otherwise an error code to indicate what went wrong.
*************************************************************/
void Connection::UnregisterCallback(IncomingCallback callback, char const* pType)
{
	ClearError() ;

	if (pType == NULL)
	{
		SetError(Error::kInvalidArgument) ;
		return ;
	}

	// See if we have a list of callbacks for this type
	CallbackList* pList = GetCallbackList(pType) ;

	if (pList == NULL)
	{
		SetError(Error::kCallbackNotFound) ;
		return ;
	}

	if (callback == NULL)
	{
		// Caller asked to delete all callbacks for this type
		delete pList ;
		m_CallbackMap[pType] = NULL ;

		return ;
	}

	// Walk the list of callbacks, deleting any objects that
	// match the callback function
	CallbackListIter iter = pList->begin() ;

	bool found = false ;

	while (iter != pList->end())
	{
		Callback* pCallback = *iter ;
		iter++ ;

		// See if this function matches the one we were passed
		// In which case, delete it.
		if (pCallback->getFunction() == callback)
		{
			delete pCallback ;
			found = true ;
		}
	}

	if (!found)
		SetError(Error::kCallbackNotFound) ;
}
Esempio n. 26
0
void ibrowserAPI::installCallback(const char *operation, plist_t status, void *user_data) {
    char *xml_doc=NULL;
    uint32_t xml_length;
    
    Callback *cb = (Callback *)user_data;
    
    FB::JSObjectPtr pcb = cb->get("pcb");
    FB::JSObjectPtr scb = cb->get("scb");
    FB::JSObjectPtr ecb = cb->get("ecb");
    
    if(pcb)
    {
        plist_to_xml(status, &xml_doc, &xml_length);
        pcb->InvokeAsync("", FB::variant_list_of(xml_doc));
        free(xml_doc);
    }
    
    plist_dict_iter it = NULL;
	char* key = NULL;
    char*   s = NULL;
	plist_t subnode = NULL;
	plist_dict_new_iter(status, &it);
	plist_dict_next_item(status, it, &key, &subnode);
	while (subnode)
	{
		if(strcmp(key, "Error") == 0)
        {
            plist_get_string_val(subnode, &s);
            if(ecb)
                ecb->InvokeAsync("", FB::variant_list_of(s));
            
        }else if(strcmp(key, "Status") == 0){
            plist_get_string_val(subnode, &s);
            if(strcmp(s, "Complete") == 0){
                if(scb)
                    scb->InvokeAsync("", FB::variant_list_of(NULL));
            }
        }
		plist_dict_next_item(status, it, &key, &subnode);
        
	}

    if(key)
        free(key);
    if(s)
        free(s);
	free(it);
    return;
}
Esempio n. 27
0
ServerRequest::ServerRequest( ServerFile *file,
                              const QByteArray &request,
                              const QVariant &parameters,
                              const Callback &callback ) :
	mFile( file ),
	mOpeningFile( NULL ),
	mRequest( request ),
	mParameters( parameters ),
	mMessageId( 0 ),
	mPackedRequest() {
	if ( callback.getFailureSlot() ) {
		connect( this,
		         SIGNAL( requestFailure( QString, int ) ),
		         callback.getTarget(),
		         callback.getFailureSlot() );
	}
Esempio n. 28
0
void FastCGITransport::sendImpl(const void *data, int size, int code,
                                bool chunked) {
  IOBufQueue queue;
  if (!m_headersSent) {
    sendResponseHeaders(queue, code);
  }
  queue.append(IOBuf::copyBuffer(data, size));
  folly::MoveWrapper<std::unique_ptr<IOBuf>> chain_wrapper(queue.move());
  Callback* callback = m_callback;
  auto fn = [callback, chain_wrapper]() mutable {
    if (callback) {
      callback->onStdOut(std::move(*chain_wrapper));
    }
  };
  m_connection->getEventBase()->runInEventBaseThread(fn);
}
Esempio n. 29
0
void button_connect_callback( GtkButton* button, const Callback& callback ){
#if 1
	g_signal_connect_swapped( G_OBJECT( button ), "clicked", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() );
#else
	g_signal_connect_closure( G_OBJECT( button ), "clicked", create_cclosure( G_CALLBACK( clicked_closure_callback ), callback ), FALSE );
#endif
}
Esempio n. 30
0
LPTSTR CEventListener::GenerateListenerId(void) const
{
	const std::type_info& target_type = m_callback.target_type();

	TCHAR hash_code_str[16] = TEXT("");
	_stprintf_s(hash_code_str, TEXT("%u"), target_type.hash_code());
	const size_t hash_code_len = _tcslen(hash_code_str);

	LPCSTR wrap_begin = "_Callable_pmf<";
	LPCSTR type_name_a = target_type.name();
	LPCSTR copy_begin = strstr(type_name_a, wrap_begin);

	if (NULL == copy_begin) {
		LPTSTR listener_id = new TCHAR[hash_code_len + 1];
		_tcscpy_s(listener_id, hash_code_len + 1, hash_code_str);
		return listener_id;
	}

	copy_begin += strlen(wrap_begin);
	LPCSTR copy_end = strstr(copy_begin, ",class");
	if (NULL == copy_end) {
		copy_end = copy_begin + strlen(copy_begin);
	}

	const size_t type_name_len = copy_end - copy_begin;
	const size_t buf_words = type_name_len + hash_code_len + 1;
	LPTSTR listener_id = new TCHAR[buf_words];
	memset(listener_id, 0, buf_words * sizeof(TCHAR));
	
	for (size_t i = 0; copy_begin + i < copy_end; ++i) {
		listener_id[i] = static_cast<TCHAR>(copy_begin[i]);
	}
	_tcscpy_s(listener_id + type_name_len, buf_words - type_name_len, hash_code_str);
	return listener_id;
}