Esempio n. 1
0
//  ---------------------------------------------------------------------------
CUI_RESULTTYPE CUIWidgetManager::SetFocusWidget(CUIBase* widget)
{
	if (!m_bInitted) {
		CUI_ERR("WidgetManager was never Initialized!\n");
		return CUIR_ILT_WIDGETMANAGER_ERROR;
	}

	// send a lost focus message
	CUIMessage* lost_focus_message;
	LT_MEM_TRACK_ALLOC(lost_focus_message = new CUIMessage(CUIM_LOST_FOCUS, m_pFocusWidget, m_pFocusWidget, (uint32)m_pFocusWidget, 0),LT_MEM_TYPE_UI);

	EnqueueMessage(lost_focus_message);
	delete lost_focus_message;

	// change the focus
	m_pFocusWidget = widget;
	
	// send a got focus message
	CUIMessage* got_focus_message;
	LT_MEM_TRACK_ALLOC(got_focus_message =	new CUIMessage(CUIM_GOT_FOCUS, widget, widget, (uint32)widget, 0),LT_MEM_TYPE_UI);

	EnqueueMessage(got_focus_message);
	delete got_focus_message;


	return CUIR_OK;
}
Esempio n. 2
0
static void Messaging_HandleMessage(PP_Instance instance,struct PP_Var message)
{
    if ( message.type != PP_VARTYPE_DICTIONARY ) // Special case for jspipe input handling
    {
        PostMessage("Got unexpected message type: %d\n", message.type);
        return;
    }
    struct PP_Var pipe_var = CStrToVar("pipe");
    struct PP_Var pipe_name = g_ppb_var_dictionary->Get(message, pipe_var);
    g_ppb_var->Release(pipe_var);
    if ( pipe_name.type == PP_VARTYPE_STRING ) // Special case for jspipe input handling
    {
        char file_name[PATH_MAX];
        snprintf(file_name, PATH_MAX, "/dev/%s", VarToCStr(pipe_name));
        int fd = open(file_name, O_RDONLY);
        g_ppb_var->Release(pipe_name);
        if ( fd < 0 )
        {
            PostMessage("Warning: opening %s failed.", file_name);
            goto done;
        }
        //if ( ioctl(fd, NACL_IOC_HANDLEMESSAGE, &message) != 0 )
        //    PostMessage("Error: ioctl on %s failed: %s", file_name, strerror(errno));
        close(fd);
        goto done;
    }
    g_ppb_var->AddRef(message);
    if ( !EnqueueMessage(message) )
    {
        g_ppb_var->Release(message);
        PostMessage("Warning: dropped message because the queue was full.");
    }
done:
    g_ppb_var->Release(pipe_name);
}
Esempio n. 3
0
static void Messaging_HandleMessage(PP_Instance instance,
                                    struct PP_Var message) {
  g_ppb_var->AddRef(message);
  if (!EnqueueMessage(message)) {
    g_ppb_var->Release(message);
    pp_post_message("error", "dropped message because the queue was full.");
  }
}
Esempio n. 4
0
  /// Handler for messages coming in from the browser via postMessage().  The
  /// @a var_message can contain be any pp:Var type; for example int, string
  /// Array or Dictinary. Please see the pp:Var documentation for more details.
  /// @param[in] var_message The message posted by the browser.
  virtual void HandleMessage(const pp::Var& var_message) 
  {
      EnqueueMessage(var_message);
      // std::cout << "HandleMessage... " << std::endl;
      int point_size(0);
      // printf( "handler thread id '%p'\n", pthread_self());                    
 
  }
Esempio n. 5
0
void CSessionThread::SendEOJ()
{
	struct packet_s pkt;

	ClearBuffer(pkt);
	pkt.header.type = htons(PKT_EOJ);
	EnqueueMessage(pkt);
}
Esempio n. 6
0
void
CannaLooper::SendInputStopped()
{
	BMessage* msg = new BMessage(B_INPUT_METHOD_EVENT);
	msg->AddInt32("be:opcode", B_INPUT_METHOD_STOPPED);
	EnqueueMessage(msg);

	SERIAL_PRINT(("CannaLooper: B_INPUT_METHOD_STOPPED has been sent\n"));
}
Esempio n. 7
0
void
CannaLooper::SendInputStarted()
{
	BMessage* msg = new BMessage(B_INPUT_METHOD_EVENT);
	msg->AddInt32("be:opcode", B_INPUT_METHOD_STARTED);
	msg->AddMessenger("be:reply_to", BMessenger(NULL, this));
	EnqueueMessage(msg);

	SERIAL_PRINT(("CannaLooper: B_INPUT_METHOD_STARTED has been sent\n"));
}
Esempio n. 8
0
void WorkerThread::EnqueueWorkerThreadTerminateRequest(void)
{
    m_interruptRequested = INT_STOP | INT_TERMINATE;

    WORKER_THREAD_REQUEST message;
    memset(&message, 0, sizeof(message));

    message.request = REQUEST_TERMINATE;
    EnqueueMessage(message);
}
Esempio n. 9
0
static void Messaging_HandleMessage(PP_Instance instance,
                                    struct PP_Var message) {
  char buffer[1024];
  VarToCStr(message, &buffer[0], 1024);
  if (!EnqueueMessage(strdup(buffer))) {
    struct PP_Var var;
    var = PrintfToVar(
        "Warning: dropped message \"%s\" because the queue was full.", message);
    ppb_messaging_interface->PostMessage(g_instance, var);
  }
}
Esempio n. 10
0
status_t VBoxMouse::_ServiceThread()
{
    Log(("VBoxMouse::%s()\n", __FUNCTION__));

    fDriverFD = open(VBOXGUEST_DEVICE_NAME, O_RDWR);
    if (fDriverFD < 0)
        return ENXIO;

    /* The thread waits for incoming messages from the host. */
    while (!fExiting)
    {
        uint32_t cx, cy, fFeatures;
        int rc;

        fd_set readSet, writeSet, errorSet;
        FD_ZERO(&readSet);
        FD_ZERO(&writeSet);
        FD_ZERO(&errorSet);
        FD_SET(fDriverFD, &readSet);
        if (fDriverFD < 0)
            break;
        rc = select(fDriverFD + 1, &readSet, &writeSet, &errorSet, NULL);
        if (rc < 0)
        {
            if (errno == EINTR || errno == EAGAIN)
                continue;
            break;
        }

        rc = VbglR3GetMouseStatus(&fFeatures, &cx, &cy);
        if (   RT_SUCCESS(rc)
            && (fFeatures & VMMDEV_MOUSE_HOST_WANTS_ABSOLUTE))
        {
            float x = cx * 1.0 / 65535;
            float y = cy * 1.0 / 65535;

            _debugPrintf("VBoxMouse: at %d,%d %f,%f\n", cx, cy, x, y);

            /* Send absolute movement */
            bigtime_t now = system_time();
            BMessage *event = new BMessage(B_MOUSE_MOVED);
            event->AddInt64("when", now);
            event->AddFloat("x", x);
            event->AddFloat("y", y);
            event->AddFloat("be:tablet_x", x);
            event->AddFloat("be:tablet_y", y);
            //event->PrintToStream();
            EnqueueMessage(event);

            //LogRelFlow(("processed host event rc = %d\n", rc));
        }
    }
    return 0;
}
Esempio n. 11
0
void
CannaLooper::_HandleKeyDown(BMessage* msg)
{
	uint32 modifier;
	int32 key;
	msg->FindInt32("modifiers", (int32*)&modifier);
	msg->FindInt32("key", &key);

	if ((modifier & B_COMMAND_KEY) != 0) {
		EnqueueMessage(DetachCurrentMessage());
		return;
	}

	char character;
	msg->FindInt8("byte", (int8*)&character);

	// The if clause below is to avoid processing key input which char code
	// is 0x80 or more.
	// if mikakutei string exists, dispose current message.
	// Otherwise, send it to application as usual B_KEY_DOWN message.
	if ((character & 0x80) != 0) {
		if (fCanna->MikakuteiLength() != 0)
			delete DetachCurrentMessage();
		else
			EnqueueMessage(DetachCurrentMessage());

		return;
	}

	SERIAL_PRINT(("CannaLooper: HandleKeyDown() calling "
		"CannaInterface::KeyIn()...\n", result));

	uint32 result = fCanna->KeyIn(character, modifier, key);

	SERIAL_PRINT(("CannaLooper: HandleKeyDown() received result = %d from "
		"CannaInterface.\n", result));

	_ProcessResult(result);
}
Esempio n. 12
0
void WorkerThread::EnqueueWorkerThreadExposeRequest(usImage *pImage, int exposureDuration, int exposureOptions, const wxRect& subframe)
{
    m_interruptRequested &= ~INT_STOP;

    WORKER_THREAD_REQUEST message;
    memset(&message, 0, sizeof(message));

    Debug.AddLine("Enqueuing Expose request");

    message.request                      = REQUEST_EXPOSE;
    message.args.expose.pImage           = pImage;
    message.args.expose.exposureDuration = exposureDuration;
    message.args.expose.options          = exposureOptions;
    message.args.expose.subframe = subframe;
    message.args.expose.pSemaphore       = NULL;

    EnqueueMessage(message);
}
Esempio n. 13
0
void WorkerThread::EnqueueWorkerThreadMoveRequest(Mount *pMount, const PHD_Point& vectorEndpoint, MountMoveType moveType)
{
    m_interruptRequested &= ~INT_STOP;

    WORKER_THREAD_REQUEST message;
    memset(&message, 0, sizeof(message));

    Debug.AddLine(wxString::Format("Enqueuing Move request for %s (%.2f, %.2f)", pMount->GetMountClassName(), vectorEndpoint.X, vectorEndpoint.Y));

    message.request                   = REQUEST_MOVE;
    message.args.move.pMount          = pMount;
    message.args.move.calibrationMove = false;
    message.args.move.vectorEndpoint  = vectorEndpoint;
    message.args.move.moveType        = moveType;
    message.args.move.pSemaphore      = NULL;

    EnqueueMessage(message);
}
Esempio n. 14
0
void WorkerThread::EnqueueWorkerThreadMoveRequest(Mount *pMount, const GUIDE_DIRECTION direction, int duration)
{
    m_interruptRequested &= ~INT_STOP;

    WORKER_THREAD_REQUEST message;
    memset(&message, 0, sizeof(message));

    Debug.AddLine("Enqueuing Calibration Move request for direction %d", direction);

    message.request                   = REQUEST_MOVE;
    message.args.move.pMount          = pMount;
    message.args.move.calibrationMove = true;
    message.args.move.direction       = direction;
    message.args.move.duration        = duration;
    message.args.move.moveType        = MOVETYPE_DIRECT;
    message.args.move.pSemaphore      = NULL;

    EnqueueMessage(message);
}
Esempio n. 15
0
    /// Function running in the output logging loop
    void
    LogLoop()
    {
        while (true)
        {
            // Check outStream
            // Convert and append to messages
            // empty stream
            // Check message queue
            // output and empty queue
            {
                ScopeLock lock(streamLock_);
                if (outStream_.str().length() > 0)
                {
                    EnqueueMessage(outStream_.str());
                }
                outStream_.str("");
            }

            {
                ScopeLock lock(queueLock_);
                for (const auto& msg : messageQueue_)
                {
                    // We want to flush between each message
                    std::cout << msg << std::endl;
                }
                messageQueue_.resize(0);
            }

            // Check this here to get a final print after exit is
            // called if we're in the process of sleeping
            if (exit_)
                break;

            // NOTE(Chris): A condition variable might be better, but I'm lazy
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
    }
Esempio n. 16
0
void	Server::SendEnqueuedMessages( Conn* conn )
{
	int buf_len;
	MsgPacketStamp msg;
	int num_resends;
	MsgDesc timestamp_msg_desc;
	bool buffer_full;
	
	// Should we send this frame?
	if(	ShouldSendThisFrame( conn ) == false )
	{
		return;
	}

	buffer_full = false;
	while( !buffer_full && MessagesToSend( conn ) && !BandwidthExceeded( conn ))
	{    
		// Send Latency Tests/Responses if applicable
		if( ( conn->IsRemote()) &&
			( conn->IsForeign() == false ) &&
			( m_flags.TestMask( App::mDYNAMIC_RESEND )))
		{
			MsgDesc msg_desc;
			MsgTimestamp latency_msg;
			unsigned int cur_time;
	
			cur_time = m_Timestamp;
			latency_msg.m_Timestamp = cur_time;
			// send out a new latency test, keeping track of the time at which
			// we sent it
			if(	( conn->m_latency_test.m_SendTime == 0 ) ||
				( ( cur_time - conn->m_latency_test.m_SendTime ) > App::MAX_LATENCY ))
			{   
				// If we never got a response, simulate an increased latency
				if( conn->m_latency_test.m_SendTime > conn->m_latency_test.m_ReceiveTime )
				{
					unsigned int latency_value;
	
					latency_value = conn->GetAveLatency();
					latency_value += 100;
	
					if( latency_value > App::MAX_LATENCY )
					{
						latency_value = App::MAX_LATENCY;
					}
					conn->m_latency_test.InputLatencyValue( latency_value );
				}
#ifdef __PLAT_NGPS__
				SignalSema( m_send_semaphore_id );
#endif
				conn->m_latency_test.m_SendTime = cur_time;
	
				msg_desc.m_Data = &latency_msg;
				msg_desc.m_Length = sizeof( MsgTimestamp );
				msg_desc.m_Id = MSG_ID_PING_TEST;
				EnqueueMessage( conn->GetHandle(), &msg_desc );
#ifdef __PLAT_NGPS__
				WaitSema( m_send_semaphore_id );
#endif
			}
		}	
    
#ifdef __PLAT_NGPS__
		SignalSema( m_send_semaphore_id );
#endif
	
		msg.m_Packetstamp = (unsigned short) conn->m_latest_sent_packet_stamp;
		//msg.m_Handle = conn->GetHandle();
	
		timestamp_msg_desc.m_Data = &msg;
		timestamp_msg_desc.m_Length = sizeof( MsgPacketStamp );
		timestamp_msg_desc.m_Id = MSG_ID_TIMESTAMP;
		timestamp_msg_desc.m_Priority = HIGHEST_PRIORITY;
		EnqueueMessage( conn->GetHandle(), &timestamp_msg_desc );

#ifdef __PLAT_NGPS__
		WaitSema( m_send_semaphore_id );
#endif

		num_resends = conn->GetNumResends();

		if( !BuildMsgStream( conn, QUEUE_DEFAULT ))
		{
			buffer_full = true;
		}
		// First, use up our bandwidth with re-sends or else they might remain un-sent
		// indefinitely, causing a bad backup on the client if he's waiting on 
		// one particular sequence
		if( !BuildMsgStream( conn, QUEUE_SEQUENCED, true ))
		{
			buffer_full = true;
		}
		if( !BuildMsgStream( conn, QUEUE_IMPORTANT, true ))
		{
			buffer_full = true;
		}
		if( !BuildMsgStream( conn, QUEUE_SEQUENCED ))
		{
			buffer_full = true;
		}
		if( !BuildMsgStream( conn, QUEUE_IMPORTANT ))
		{
			buffer_full = true;
		}

		// If we had to resend some messages this frame, affect the latency for this client
		// so that we don't expect so much from their connection.
		// Also, reduce their estimated bandwidth
		if( conn->GetNumResends() > num_resends )
		{
			conn->m_latency_test.InputLatencyValue( App::MAX_LATENCY );
			conn->SetBandwidth( conn->GetBandwidth() - 500 );
			// Make sure that we'll still be able to send at least one large (max-size) packet.
			// Otherwise, we might get deadlocked.
			if( conn->GetBandwidth() < ( MAX_UDP_PACKET_SIZE + vUDP_PACKET_OVERHEAD ))
			{
				conn->SetBandwidth( MAX_UDP_PACKET_SIZE + vUDP_PACKET_OVERHEAD );
			}
		}

		buf_len = conn->m_write_ptr - conn->m_write_buffer;
		// If there is data to send
		if( ( buf_len > 0 ) &&
			( conn->IsRemote()))
		{
#ifdef NET_DEBUG_MESSAGES
			/*Dbg_Printf( "(%d) Conn %d: Sending pstamp %d at time %d\n", 
							m_FrameCounter, 
							conn->GetHandle(),
							conn->m_latest_sent_packet_stamp,
							m_Timestamp );*/
#endif																	
			if ( SendTo( conn->GetIP(), conn->GetPort(), conn->m_write_buffer, buf_len, 0 ))
			{
				m_TotalBytesOut += buf_len;
				conn->GetOutboundMetrics()->AddPacket( buf_len + vUDP_PACKET_OVERHEAD, m_Timestamp );
				conn->SetForceSendThisFrame( false );
				conn->m_last_send_time = m_Timestamp;
			}
			else
			{
				// If it didn't send the messages properly, flag them for resend next frame
				conn->FlagMessagesForResending( conn->m_latest_sent_packet_stamp );
				conn->m_write_ptr = conn->m_write_buffer;		
				break;
			}
			
			conn->m_write_ptr = conn->m_write_buffer;		
		}

		conn->m_latest_sent_packet_stamp++;
	}

	// If we're successfully sending data at/near the connection's estimated max bandwidth and there
	// are no problems, try ramping up the estimated bandwidth for this connection
	if( BandwidthExceeded( conn ) && ( conn->GetNumResends() == 0 ))
	{
		conn->SetBandwidth( conn->GetBandwidth() + 1000 );
	}
}
Esempio n. 17
0
void
CannaLooper::_ProcessResult(uint32 result)
{
	SERIAL_PRINT(("CannaLooper: _ProcessResult() processing result = %d\n",
		result));

	if ((result & GUIDELINE_APPEARED) != 0) {
		SERIAL_PRINT(("CannaLooper: _ProcessResult() processing "
			"GUIDELINE_APPEARED\n"));

		if (fCanna->MikakuteiLength() != 0) {
			// usual guideline i.e. kouho

			BMessage* msg = new BMessage(B_INPUT_METHOD_EVENT);
			msg->AddInt32("be:opcode", B_INPUT_METHOD_LOCATION_REQUEST);
			fOwner->EnqueueMessage(msg);

			SERIAL_PRINT(("CannaLooper: B_INPUT_METHOD_LOCATION_REQUEST has "
				"been sent\n"));
		} else {
			// guideline exists, but no mikakutei string - means extend mode
			// and such.
			SERIAL_PRINT(("  GUIDELINE_APPEARED: calling "
				"GenerateKouho()...\n"));

			fKouhoWindow->PostMessage(fCanna->GenerateKouhoString());
			SERIAL_PRINT(("  GUIDELINE_APPEARED: posting KouhoMsg to "
				"KouhoWindow %x...\n", fKouhoWindow));

			fKouhoWindow->PostMessage(KOUHO_WINDOW_SHOW_ALONE);
		}
	}

	if ((result & GUIDELINE_DISAPPEARED) != 0) {
		SERIAL_PRINT(("CannaLooper: _ProcessResult() processing "
			"GUIDELINE_DISAPPEARED\n"));
		fKouhoWindow->PostMessage(KOUHO_WINDOW_HIDE);
	}

	if ((result & MODE_CHANGED) != 0) {
		SERIAL_PRINT(("CannaLooper: _ProcessResult() processing "
			"MODE_CHANGED\n"));

		BMessage message(PALETTE_WINDOW_BUTTON_UPDATE);
		message.AddInt32("mode", fCanna->GetMode());
		fPaletteWindow->PostMessage(&message);

		SERIAL_PRINT(("CannaLooper: PALETTE_BUTTON_UPDATE has been sent. "
			"mode = %d\n", fCanna->GetMode()));
	}

	if ((result & GUIDELINE_CHANGED) != 0) {
		SERIAL_PRINT(("CannaLooper: _ProcessResult() processing "
			"GUIDELINE_CHANGED\n"));
		fKouhoWindow->PostMessage(fCanna->GenerateKouhoString());
	}

	if ((result & THROUGH_INPUT) != 0) {
		SERIAL_PRINT(("CannaLooper: _ProcessResult() processing "
			"THROUGH_INPUT\n"));
		EnqueueMessage(DetachCurrentMessage());
	}

	if ((result & NEW_INPUT_STARTED) != 0) {
		SERIAL_PRINT(("CannaLooper: _ProcessResult() processing "
			"NEW_INPUT_STARTED\n"));
		SendInputStarted();
	}

	if ((result & KAKUTEI_EXISTS) != 0) {
		SERIAL_PRINT(("CannaLooper: _ProcessResult() processing "
			"KAKUTEI_EXISTS\n"));

		BMessage* msg = new BMessage(B_INPUT_METHOD_EVENT);
		msg->AddInt32("be:opcode", B_INPUT_METHOD_CHANGED);

		msg->AddString("be:string", fCanna->GetKakuteiStr());
		msg->AddInt32("be:clause_start", 0);
		msg->AddInt32("be:clause_end", fCanna->KakuteiLength());
		msg->AddInt32("be:selection", fCanna->KakuteiLength());
		msg->AddInt32("be:selection", fCanna->KakuteiLength());
		msg->AddBool("be:confirmed", true);
		fOwner->EnqueueMessage(msg);

		SERIAL_PRINT(("CannaLooper: B_INPUT_METHOD_CHANGED (confired) has "
			"been sent\n"));

		// if both kakutei and mikakutei exist, do not send B_INPUT_STOPPED
		if (!(result & MIKAKUTEI_EXISTS))
			SendInputStopped();
	}

	if ((result & MIKAKUTEI_EXISTS) != 0) {
		SERIAL_PRINT(("CannaLooper: _ProcessResult() processing "
			"MIKAKUTEI_EXISTS\n" ));

		int32 start, finish;
		BMessage* msg = new BMessage(B_INPUT_METHOD_EVENT);
		msg->AddInt32("be:opcode", B_INPUT_METHOD_CHANGED);
		msg->AddString("be:string", fCanna->GetMikakuteiStr());

		if (fCanna->HasRev()) {
			fCanna->GetRevPosition( &start, &finish);
			msg->AddInt32("be:clause_start", 0);
			msg->AddInt32("be:clause_end", start);
			msg->AddInt32("be:clause_start", start);
			msg->AddInt32("be:clause_end", finish);
			msg->AddInt32("be:clause_start", finish);
			msg->AddInt32("be:clause_end", fCanna->MikakuteiLength());
		} else {
			start = finish = fCanna->MikakuteiLength();
			msg->AddInt32("be:clause_start", 0);
			msg->AddInt32("be:clause_end", fCanna->MikakuteiLength());
		}

		msg->AddInt32("be:selection", start);
		msg->AddInt32("be:selection", finish);
		//msg->AddBool("be:confirmed", false);
		fOwner->EnqueueMessage(msg);

		SERIAL_PRINT(("CannaLooper: B_INPUT_METHOD_CHANGED (non-confirmed) "
			"has been sent\n"));
	}

	if ((result & MIKAKUTEI_BECOME_EMPTY) != 0) {
		SERIAL_PRINT(("CannaLooper: _ProcessResult() processing "
			"MIKAKUTEI_BECOME_EMPTY\n" ));
		BMessage* msg = new BMessage(B_INPUT_METHOD_EVENT);
		msg->AddInt32("be:opcode", B_INPUT_METHOD_CHANGED);

		msg->AddString("be:string", B_EMPTY_STRING);
		msg->AddInt32("be:clause_start", 0);
		msg->AddInt32("be:clause_end", 0);
		msg->AddInt32("be:selection", 0);
		msg->AddInt32("be:selection", 0);
		msg->AddBool( "be:confirmed", true);
		fOwner->EnqueueMessage(msg);

		SERIAL_PRINT(( "CannaLooper: B_INPUT_METHOD_CHANGED (NULL, confired) "
			"has been sent\n"));

		SendInputStopped();
	}
}
Esempio n. 18
0
void CSessionThread::SessionRun()
{
	struct packet_s out_pkt;

	ClearBuffer(out_pkt);

	if (m_ask_cobranca)
	{
		out_pkt.header.type = htons(PKT_ASK_REFILL_COBRANCA);
		EnqueueMessage(out_pkt);
	}
	
	if (m_ask_planos)
	{
		out_pkt.header.type = htons(PKT_ASK_REFILL_PLANOS);
		EnqueueMessage(out_pkt);
	}

	CDBBlocos dbBlocos;
	if (m_ask_bloco || !dbBlocos.HaveBlocosReserva())
	{
		out_pkt.header.type = htons(PKT_ASK_BLOCO);
		EnqueueMessage(out_pkt);
	}
	
	if (m_ask_refill_clientes)
	{
		out_pkt.header.type = htons(PKT_ASK_REFILL_CLIENTES);
		EnqueueMessage(out_pkt);
	}
	else
	{
		out_pkt.header.type = htons(PKT_ASK_NOVOS_CLIENTES);
		EnqueueMessage(out_pkt);
	}

	if (m_ask_refill_produtos)
	{
		out_pkt.header.type = htons(PKT_ASK_REFILL_PRODUTOS);
		EnqueueMessage(out_pkt);
	}
	else
	{
		out_pkt.header.type = htons(PKT_ASK_NOVOS_PRODUTOS);
		EnqueueMessage(out_pkt);

		out_pkt.header.type = htons(PKT_ASK_NOVOS_PRECOS);
		EnqueueMessage(out_pkt);

		out_pkt.header.type = htons(PKT_ASK_NOVOS_SALDOS);
		EnqueueMessage(out_pkt);
	}
	
	if (m_ask_refill_titulos)
	{
		out_pkt.header.type = htons(PKT_ASK_REFILL_TITULOS);
		EnqueueMessage(out_pkt);
	}
	else
	{
		out_pkt.header.type = htons(PKT_ASK_NOVOS_TITULOS);
		EnqueueMessage(out_pkt);
	}

	//Solicitações locais
	if (m_snd_pedidos)
	{
		out_pkt.header.type = htons(PKT_SND_PEDIDO);
		EnqueueTask(out_pkt);
	}
	if (m_snd_clientes)
	{
		/*
		out_pkt.header.type = htons(PKT_SND_NOVO_CLIENTE);
		EnqueueTask(out_pkt);
		out_pkt.header.type = htons(PKT_SND_ATUALIZA_CLIENTE);
		EnqueueTask(out_pkt);
		*/
	}

	//Fim das solicitações
	out_pkt.header.type = htons(PKT_EOQ);
	EnqueueMessage(out_pkt);

	TriggerDispatcherThread();
	TriggerReceiverThread();
}
Esempio n. 19
0
	//------------------------------------------
	bool CEngine::Initialize(const wchar* settings/*="game.ini"*/, bool customWindow/*=false*/, sDisplayProperties *dp/*=NULL*/){
		assertd(s_bInit==false, "DOUBLE ENGINE INITIALIZATION!");

		s_bInit = true; //predict :-P

		// initialize random generator
		srand( (unsigned int)milisec() );

		cInternalWindow()->BeginSplash();

		// memory leaks detection
#if defined(_DEBUG) && defined(_MSC_VER) && _MSC_VER >= 800
		_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
		//_CrtSetBreakAlloc(23296);
#endif

		// ---------------------------------------------------
		// QUEUE TESTS
		CON(MSG_INFO, _W("------- Command Queue Test -------"));
		CCommandQueue q;
		DWORD tim;
		for (int t=0; t<10; t++)
		{
			tim = GetTickCount();
			// FILL IN QUEUE
			for (int i=0; i<20000; i++)
			{
					sE2RCanvasDesc *cd;
					q.Enqueue(NULL, CQI_ENGINE2RENDERER_CANVAS_CREATE, (void*&)cd, sizeof(sE2RCanvasDesc));
					cd->handle = 0;
			}
			CON(MSG_INFO, _W("Iteration #%d: Enqueue %d ms"), t, GetTickCount()-tim );

			// DEQUEUE
			unsigned int cqi; const void* optr; IQueueCommandReceiver *recv;
			tim = GetTickCount();
			while (q.Dequeue(cqi, optr, recv))
			{
				switch(cqi)
				{
				case CQI_ENGINE2RENDERER_CANVAS_CREATE:
					{
						sE2RCanvasDesc *cd = (sE2RCanvasDesc *)optr;
					}
					break;
				}
			}
			CON(MSG_INFO, _W("Iteration #%d: Dequeue %d ms"), t, GetTickCount()-tim );
		}
		CON(MSG_INFO, _W("----------------------------------"));
		// ---------------------------------------------------


		// --- WRITE INFO ABOUT LIBRARIES AND MODULES
		I_DebugPrint( ConsoleMsg );

		CON(MSG_INFO, _W("= %s %s build %d initialization ="), _W(P3DNAME), sizeof(void*)==8?_W("x64"):_W("x86"), GetBuildNum());
		if (sizeof(wchar)>1) 
			CON(MSG_INFO, _W("Unicode support \x263A"));
		else
			CON(MSG_INFO, _W("Multibyte character set"));

		// --- LOAD SETTINGS
		m_szSettings = new wchar[wstrlen(settings)+1];
		wstrcpy(m_szSettings, settings);

		cConfig()->Load(m_szSettings);
		//cConfig()->Save(m_szSettings);

		// --- INITIALIZE SCRIPT SYSTEM
		CON(MSG_INFO, _W("Script system initialization"));
		cScriptEngine()->Initialize();

		// --- LOAD KEY BINDINGS
		cInputManager()->Assign(_W("GUI_CURSOR"), WE_MOUSE_MOTION, 0);
		cInputManager()->Assign(_W("GUI_SELECT"), WE_MOUSE_DOWN, 0);

		cInputManager()->Save(_W("keys.ini")); // TODO: FIXME: What about load? :D

		// --- CREATE MAIN WINDOW
		Vec2i mainWindowSize(800,600);
		bool initFullscreen = false;
		if (customWindow)
		{
			// use primary screen resolution for frame buffer
			// TODO: multiplatform
#ifdef _WIN32
			mainWindowSize.x = GetSystemMetrics(SM_CXSCREEN);
			mainWindowSize.y = GetSystemMetrics(SM_CYSCREEN);
#endif
		}
		else
		{
			if (dp) 
			{
				// use user-defined resolution
				initFullscreen = dp->Fullscreen;
				mainWindowSize.x = dp->HorRes;
				mainWindowSize.y = dp->VertRes;
			}
			else
			{
				// use settings
				initFullscreen = svFullscreen.GetBool();
				mainWindowSize.x = svResolutionX.GetInt();
				mainWindowSize.y = svResolutionY.GetInt();
			}
		}
		cInternalWindow()->Create(mainWindowSize);

		//Init the internal input system
		cInternalInput()->Init( cInternalWindow()->GetHandle() );
		//Init the Filesystem
		cFilesystem()->Init();

		
		// --- LOAD SELECTED MODULES
		s_pRenderer = (IRenderer*)I_GetModule(_W("renderer"), svRenderer.GetString());
		if (!s_pRenderer) CON(MSG_ERR_FATAL, _W("Cannot load renderer module. It is a core module, cannot continue!"));
		s_pSound = (ISoundEngine*)I_GetModule(_W("sound"), svSound.GetString());
		if (!s_pSound) CON(MSG_ERR_FATAL, _W("Cannot load sound module. It is a core module, cannot continue!"));
		s_pPhys = (IPhysEngine*)I_GetModule(_W("physics"), svPhysics.GetString());
		if (!s_pPhys) CON(MSG_ERR_FATAL, _W("Cannot load phys module. It is a core module, cannot continue!"));
		s_pFS = (IFileSystem*)I_GetModule(_W("filesystem"), svFileSystem.GetString());
		if (!s_pFS) CON(MSG_ERR_FATAL, _W("Cannot load filesystem module. It is a core module, cannot continue!"));
		s_pGUI = (IGUI*)I_GetModule(_W("gui"), svGUI.GetString());
		if (!s_pGUI) CON(MSG_ERR_FATAL, _W("Cannot load GUI module. It is a core module, cannot continue!"));
		m_bModulesLoaded=true;

		// ==== INITIALIZE MODULES ====
		s_pRenderer->Initialize(this, &m_queueRenderer);

		bool ret = s_pRenderer->iGraphicsDevice()->Initialize(mainWindowSize.x, mainWindowSize.y, initFullscreen, cInternalWindow()->GetHandle());
		if (!ret)
		{
			CON(MSG_ERR_FATAL, _W("Failed to initialize graphics device!"));
		}

		// ===== SERIALIZATION DEBUG AND TEST =======
		Scene scene;
		//scene.Save(s_pFS, _W("scenes/test.robject"), iConsole());
		
		//CModel model;

		/*model = (Model*)cObjectManager()->CreateObject( _W("Model") );
		MeshData md;
          MeshSubset ms;
//           Material m;
//		  ms.Material = m;
		  ms.NumTriangles = 1;
		  ms.StartIndex = 0;
		  //ms.StartVertex = 0;
		 md.Subsets.AddEx(ms);
		 md.Indices.AddEx(0);
		 md.Indices.AddEx(1);
		 md.Indices.AddEx(2);
		 md.NumIndices = 3;
		  MeshVertexData mvd;
		  mvd.Usage = _W("P3DVU_POSITION");
		  mvd.DataSize = 3;
		  mvd.Float3.AddEx(Vec3Param(0.0f, 0.0f, 0.0f));
		  mvd.Float3.AddEx(Vec3Param(0.0f, 1.0f, 0.0f));
		  mvd.Float3.AddEx(Vec3Param(1.0f, 1.0f , 0.0f));
		 md.DataStreams.AddEx(mvd);
		 md.NumVerts = 3;
		model->LODs.AddEx(md);

		model->Save(s_pFS, _W("triangle.robject"), iConsole());
		model->PreCache();*/
		// ===========================================

		bool initOK=true;
		initOK &= s_pSound->Initialize(this);
		initOK &= s_pPhys->Initialize(this);
		initOK &= s_pFS->Initialize(this);
		initOK &= s_pGUI->Initialize(this);

		if (!initOK)
			CON(MSG_ERR_FATAL, _W("Failed to initialize some core module(s)! Cannot continue. For more details see console.htm."));

		cSceneManager()->Create();

		cConsole()->InitializeGUI(); // at this time, coz it uses GUI module and it must be initialized ;)

		// FIXME: register engine to script, temporary here
		/*using namespace luabind;
		lua_State* L = cScriptEngine()->GetLVM();
		module(L)
		[
			class_<CEngine>("Engine")
			.scope
			[
				def("GetBuildNum", &CEngine::GetBuildNum )
			]
		];*/

		// load bootstrap script
		cScriptEngine()->LoadScript(_W("scripts/bootstrap.rscript"));

		// DEBUG TESTING OF QUEUE TO RENDERER
		sE2RCanvasDesc* canvas;
		EnqueueMessage( MC_RENDERER, this, CQI_ENGINE2RENDERER_CANVAS_CREATE, (void*&)canvas, sizeof(sE2RCanvasDesc) );
		canvas->handle = cInternalWindow()->GetHandle();
		canvas->size = Vec2i(800,600);
		canvas->windowed = !initFullscreen;

		//Sleep(10000);
		cInternalWindow()->EndSplash();
		cInternalWindow()->SetVisible(true);

		
		//Filesystem test
		/*UINT oSize;
		void *lData=0;
		if(cFilesystem()->Load(_W("scripts.bootstrap"), &lData, oSize)==P3D_FILERESULT_OK)
			cFilesystem()->FreeLoadedData(lData);
		const char* testStr = "this is a test string";
		cFilesystem()->Save(_W("scripts.fstest"), testStr, sizeof(char)*strlen(testStr));*/

		return true;
	}
Esempio n. 20
0
void CSessionThread::DispatchTask(struct packet_s& pkt)
{
	switch (ntohs(pkt.header.type))
	{
	case PKT_SND_PEDIDO :
		{
			struct packet_s out_pkt;

			m_generic_outbound_record_counter = 0;
			dbPedidos.MoveFirst();

			while (!dbPedidos.IsEOF())
			{
				dbPedidos.Read();
				if (!dbPedidos.GetReterPedido() && !dbPedidos.GetPedidoEnviado())
				{
					ClearBuffer(out_pkt);
					out_pkt.header.type = htons(PKT_SND_PEDIDO);
					out_pkt.pedido.numero = htonl(dbPedidos.GetNumeroPedido());
					out_pkt.pedido.cliente_codigo = htonl(dbPedidos.GetCodigoCliente());
					out_pkt.pedido.condicao_venda = htons(dbPedidos.GetCondicaoVenda());
					out_pkt.pedido.plano = htons(dbPedidos.GetPlano());
					out_pkt.pedido.data_entrada = htonl(dbPedidos.GetDataPedido());
					CString2sz(out_pkt.pedido.cobranca, dbPedidos.GetCodigoCobranca());

					EnqueueMessage(out_pkt);

					if (dbItens.FindFirstItem(dbPedidos.GetNumeroPedido()))
					{
						do
						{
							dbItens.Read();

							ClearBuffer(out_pkt);
							out_pkt.header.type = htons(PKT_SND_PEDIDO_ITEM);
							out_pkt.pedido_item.pedido = htonl(dbPedidos.GetNumeroPedido());
							out_pkt.pedido_item.produto = htonl(dbItens.GetProduto());
							out_pkt.pedido_item.quantidade = htonl(dbItens.GetQuantidadePedida());
							out_pkt.pedido_item.preco = htonl(dbItens.GetPreco());
							EnqueueMessage(out_pkt);
						}
						while (dbItens.FindNextItem());
					}

					ClearBuffer(out_pkt);
					out_pkt.header.type = htons(PKT_SND_PEDIDO_FIM);
					out_pkt.pedido_fim.pedido = htonl(dbPedidos.GetNumeroPedido());
					EnqueueMessage(out_pkt);

					AddEvent(EVENT_SENT, PKT_SND_PEDIDO, _T("%d pedidos enviados"), ++m_generic_outbound_record_counter);
				}
				dbPedidos.MoveNext();
			}
		}
		break;
    case PKT_SND_PEDIDO_ITEM_CONF :
        {
            DWORD dwPedido      = ntohl(pkt.pedido_item_conf.pedido);
            DWORD dwProduto     = ntohl(pkt.pedido_item_conf.produto);
            DWORD dwQuantidade  = ntohl(pkt.pedido_item_conf.quantidade);

            if (dbItens.FindItem(dwPedido, dwProduto))
            {
				if (pd.FindByCodigo(dwProduto))
				{
					dbItens.Read();
                    dbItens.SetQuantidadeAtendida(dwQuantidade);
					dbItens.Write();
				}
            }
        }
        break;
	case PKT_SND_PEDIDO_STATUS :
		{
            DWORD dwPedido = ntohl(pkt.pedido_status.pedido);

            if (dbPedidos.Find(dwPedido))
            {
                dbPedidos.Read();
				dbPedidos.SetPedidoEnviado(ntohs(pkt.pedido_status.reenviar) == 0);
				dbPedidos.SetDiagnostico(pkt.pedido_status.diagnostico);
				dbPedidos.Write();

				if (cl.FindByCodigo(dbPedidos.GetCodigoCliente()))
				{
					WORD wRecord = cl.GetRecordNumber();
					cl.m_record.valor_disponivel = ntohl(pkt.pedido_status.novo_saldo_cliente);
					cl.SetRecord(wRecord);
					cl.WriteRecord();
				}
				AddEvent(EVENT_RECEIVED, 0, _T("Pedido %ld processado"), dwPedido);
            }
        }
		break;
	case PKT_ASK_CLEAR_TITULOS :
		{
			CQSTitulos ti;

			ti.Reset();

			AddEvent(EVENT_RECEIVED, 0, _T("Títulos apagados"));

			m_generic_inbound_record_counter = 0;
		}
		break;
	case PKT_SND_TITULO :
		{
			CQSTitulos ti;

			ti.ClearBuffer();
			strcpy(ti.m_record.emissao, pkt.titulo.emissao);
			strcpy(ti.m_record.vencimento, pkt.titulo.vencimento);
			strcpy(ti.m_record.numero, pkt.titulo.numero);
			ti.m_record.cliente = ntohl(pkt.titulo.cliente);
			ti.m_record.valor = ntohl(pkt.titulo.valor);
			ti.AddRecord();
			AddEvent(EVENT_RECEIVED, PKT_SND_TITULO, _T("%ld titulos recebidos"), ++m_generic_inbound_record_counter);
		}
		break;
	case PKT_ASK_CLEAR_COBRANCA :
		{
			CQSCobranca cb;

			cb.Reset();

			AddEvent(EVENT_RECEIVED, 0, _T("Códigos de cobrança apagados"));

			m_generic_inbound_record_counter = 0;
		}
		break;
	case PKT_SND_COBRANCA :
		{
			CQSCobranca cb;

			cb.ClearBuffer();
			strcpy(cb.m_record.codigo, pkt.cobranca.codigo);
			strcpy(cb.m_record.descricao, pkt.cobranca.descricao);
			cb.AddRecord();
			AddEvent(EVENT_RECEIVED, PKT_SND_COBRANCA, _T("%ld codigos de cobranca recebidos"), ++m_generic_inbound_record_counter);
		}
		break;
	case PKT_ASK_CLEAR_COND_VENDA :
		/*
		{
			CQSCondicoesVenda cv;

			cv.Reset();

			AddEvent(EVENT_RECEIVED, 0, _T("Condições de venda apagadas"));

			m_generic_inbound_record_counter = 0;
		}
		*/
		break;
	case PKT_SND_COND_VENDA :
		/*
		{
			CQSCondicoesVenda cv;

			cv.ClearBuffer();
			cv.m_record.codigo = ntohs(pkt.cond_venda.codigo);
			cv.m_record.pede_percentual = ntohs(pkt.cond_venda.pede_percentual);
			cv.AddRecord();
			AddEvent(EVENT_RECEIVED, PKT_SND_COND_VENDA, _T("%ld codigos de venda recebidos"), ++m_generic_inbound_record_counter);
		}
		*/
		break;
	case PKT_ASK_CLEAR_PLANOS :
		{
			CQSPlanos p;

			p.Reset();

			AddEvent(EVENT_RECEIVED, 0, _T("Planos apagados"));

			m_generic_inbound_record_counter = 0;
		}
		break;
	case PKT_SND_PLANO :
		{
			CQSPlanos pl;

			pl.ClearBuffer();
			pl.m_record.codigo = ntohs(pkt.plano.codigo);
			strcpy(pl.m_record.descricao, pkt.plano.descricao);
			pl.m_record.coluna = ntohs(pkt.plano.coluna);
			pl.AddRecord();
			AddEvent(EVENT_RECEIVED, PKT_SND_PLANO, _T("%ld codigos de planos de pagamento recebidos"), ++m_generic_inbound_record_counter);
		}
		break;
	case PKT_ASK_CLEAR_PRODUTOS :
		{
			pd.Reset();

			AddEvent(EVENT_RECEIVED, 0, _T("Produtos apagados"));

			m_generic_inbound_record_counter = 0;
		}
		break;
	case PKT_SND_PRODUTO :
		{
			pd.ClearBuffer();
			pd.m_record.codigo = ntohl(pkt.produto.codigo);
			pd.m_record.digito = ntohs(pkt.produto.digito);
            strcpy(pd.m_record.embalagem, pkt.produto.embalagem);
            strcpy(pd.m_record.unidade, pkt.produto.unidade);
            pd.m_record.unidades = ntohs(pkt.produto.unidades);
            pd.m_record.embalagem_master = ntohs(pkt.produto.embalagem_master);
            pd.m_record.peso_bruto = ntohs(pkt.produto.peso_bruto);
            strcpy(pd.m_record.descricao, pkt.produto.descricao);
			for (int i=0; i < 8; i++)
				pd.m_record.preco[i] = ntohl(pkt.produto.preco[i]);
			pd.m_record.disponivel = ntohs(pkt.produto.disponivel);
			strcpy(pd.m_record.complemento, pkt.produto.complemento);
			pd.m_record.brinde = ntohs(pkt.produto.brinde);
			pd.m_record.desconto_maximo = ntohl(pkt.produto.desconto_maximo);

			pd.AddRecord();

			AddEvent(EVENT_RECEIVED, PKT_SND_PRODUTO, _T("%ld itens adicionados"), ++m_generic_inbound_record_counter);
		}
		break;
	case PKT_ASK_REINDEX_PRODUTOS :
        {
            AddEvent(EVENT_RECEIVED, 0, _T("Ordenando produtos por codigo"));
            pd.Reindex();
            AddEvent(EVENT_RECEIVED, 0, _T("Produtos ordenados."));
        }
		break;
	case PKT_ASK_CLEAR_CLIENTES :
		{
			cl.Reset();

			AddEvent(EVENT_RECEIVED, 0, _T("Clientes apagados"));

			m_generic_inbound_record_counter = 0;
		}
		break;
	case PKT_SND_CLIENTE :
		{
			cl.ClearBuffer();
			cl.m_record.codigo = ntohl(pkt.cliente.codigo);
			cl.m_record.digito = ntohs(pkt.cliente.digito);
			strcpy(cl.m_record.cgc, pkt.cliente.cgc);
			strcpy(cl.m_record.razao_social, pkt.cliente.razao_social);
			strcpy(cl.m_record.fantasia, pkt.cliente.fantasia);
			strcpy(cl.m_record.contato, pkt.cliente.contato);
			strcpy(cl.m_record.telefone, pkt.cliente.telefone);
			strcpy(cl.m_record.fax, pkt.cliente.fax);
			cl.m_record.ramo_atividade = ntohs(pkt.cliente.ramo_atividade);
			strcpy(cl.m_record.cod_cobranca, pkt.cliente.cod_cobranca);
			cl.m_record.emitir_duplicata = ntohs(pkt.cliente.emitir_duplicata);
			cl.m_record.cod_vendedor = ntohs(pkt.cliente.cod_vendedor);
			cl.m_record.cod_praca = ntohs(pkt.cliente.cod_praca);
			cl.m_record.limite = ntohl(pkt.cliente.limite);
			cl.m_record.valor_disponivel = ntohl(pkt.cliente.valor_disponivel);
			cl.m_record.bloqueado = ntohs(pkt.cliente.bloqueado);
            cl.m_record.tabela = ntohs(pkt.cliente.tabela);
			strcpy(cl.m_record.motivo_bloqueio, pkt.cliente.motivo_bloqueio);
			strcpy(cl.m_record.endereco_comercial.endereco, pkt.cliente.endereco_comercial.endereco);
			strcpy(cl.m_record.endereco_comercial.bairro, pkt.cliente.endereco_comercial.bairro);
			strcpy(cl.m_record.endereco_comercial.cidade, pkt.cliente.endereco_comercial.cidade);
			strcpy(cl.m_record.endereco_comercial.estado, pkt.cliente.endereco_comercial.estado);
			strcpy(cl.m_record.endereco_comercial.cep, pkt.cliente.endereco_comercial.cep);
			strcpy(cl.m_record.endereco_cobranca.endereco, pkt.cliente.endereco_cobranca.endereco);
			strcpy(cl.m_record.endereco_cobranca.bairro, pkt.cliente.endereco_cobranca.bairro);
			strcpy(cl.m_record.endereco_cobranca.cidade, pkt.cliente.endereco_cobranca.cidade);
			strcpy(cl.m_record.endereco_cobranca.estado, pkt.cliente.endereco_cobranca.estado);
			strcpy(cl.m_record.endereco_cobranca.cep, pkt.cliente.endereco_cobranca.cep);

			cl.AddRecord();

			//if (++m_generic_inbound_record_counter % 10 == 0) AddEvent(EVENT_RECEIVED, PKT_SND_CLIENTE, _T("%ld clientes adicionados"), m_generic_inbound_record_counter);
			AddEvent(EVENT_RECEIVED, PKT_SND_CLIENTE, _T("%ld clientes adicionados"), ++m_generic_inbound_record_counter);
		}
		break;
	case PKT_ASK_REINDEX_CLIENTES :
		break;
	case PKT_SND_BLOCO :
		{
			DWORD dwInicio, dwFinal;
			CDBBlocos dbBlocos;

			dwInicio = ntohl(pkt.bloco.inicial);
			dwFinal = ntohl(pkt.bloco.final);
			dbBlocos.Add(dwInicio, dwFinal);
			AddEvent(EVENT_RECEIVED, 0, _T("Recebido bloco %lu - %lu"), dwInicio, dwFinal);
		}
		break;
	case PKT_EOJ :
		{
			struct packet_s pkt;

			ClearBuffer(pkt);
			pkt.header.type = htons(PKT_EOJ_ACK);
			EnqueueMessage(pkt);
			TriggerCloserThread();
		}
		break;
    case PKT_SND_MENSAGEM :
        {
            CString msg = pkt.mensagem.texto;
            AddEvent(EVENT_RECEIVED, 0, msg.GetBuffer(80));
            msg.ReleaseBuffer();
        }
        break;
	default :
		AddEvent(EVENT_RECEIVED, 0, _T("[0x%lx] Solicitação não tratada"), (LONG)ntohs(pkt.header.type));
		break;
	}
}