Example #1
0
XmlNode* UnifiedDomain::getXml()
{
    XmlNode* domain = XmlNode::createWrapperElement("domain");

    domain->addChild(XmlNode::createDataElement("index", StatusFormat::friendlyValue(m_domainIndex)));
    domain->addChild(XmlNode::createDataElement("name", getName()));
    domain->addChild(XmlNode::createDataElement("description", getDescription()));

    // Active Control XML Status
    try
    {
        domain->addChild(getActiveControlInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get active control XML status!"));
    }

    // cTDP Control XML Status
    try
    {
        domain->addChild(getConfigTdpControlInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get cTDP control XML status!"));
    }

    // Core Control XML Status
    try
    {
        domain->addChild(getCoreControlInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get core control XML status!"));
    }

    // Display Control XML Status
    try
    {
        domain->addChild(getDisplayControlInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get display control XML status!"));
    }

    // Performance Control XML Status
    try
    {
        domain->addChild(getPerformanceControlInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get performance control XML status!"));
    }

    // Pixel Clock Control
    try
    {
        domain->addChild(getPixelClockControlInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get pixel clock control XML!"));
    }

    // Pixel Clock Status
    try
    {
        domain->addChild(getPixelClockStatusInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get pixel clock status XML!"));
    }

    // Power Control XML Status
    try
    {
        domain->addChild(getPowerControlInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get power control XML status!"));
    }

    // Power Status XML Status
    try
    {
        domain->addChild(getPowerStatusInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get power reporting XML status!"));
    }

    // Domain Priority XML Status
    try
    {
        domain->addChild(getDomainPriorityInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get domain priority XML status!"));
    }

    // RF Profile Control XML Status
    try
    {
        domain->addChild(getRfProfileControlInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get rf profile control XML status!"));
    }

    // RF Profile Status XML Status
    try
    {
        domain->addChild(getRfProfileStatusInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get rf profile status XML status!"));
    }

    // Temperature XML Status
    try
    {
        domain->addChild(getTemperatureInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get temperature XML status!"));
    }

    // Utilization XML Status
    try
    {
        domain->addChild(getUtilizationInterfaceExPtr()->getXml(m_domainIndex));
    }
    catch (not_implemented)
    {
    }
    catch (...)
    {
        // Write message log error
        m_participantServicesInterface->writeMessageWarning(ParticipantMessage(FLF, "Unable to get utilization XML status!"));
    }

    return domain;
}
GtkWidget * XAP_UnixDialog_Image::_constructWindow ()
{
	const XAP_StringSet * pSS = m_pApp->getStringSet();
	const char * ui_file;

#if defined(EMBEDDED_TARGET) && EMBEDDED_TARGET == EMBEDDED_TARGET_HILDON
    ui_file = "xap_UnixHildonDlg_Image.ui";
#else
#if GTK_CHECK_VERSION(3,0,0)
    ui_file = "xap_UnixDlg_Image.ui";
#else
    ui_file = "xap_UnixDlg_Image-2.ui";
#endif
#endif

    GtkBuilder * builder = newDialogBuilder(ui_file);
	
	mMainWindow = GTK_WIDGET(gtk_builder_get_object(builder, "xap_UnixDlg_Image"));
	m_wHeightSpin = GTK_WIDGET(gtk_builder_get_object(builder, "sbHeight"));
	m_wHeightEntry = GTK_WIDGET(gtk_builder_get_object(builder, "edHeight"));
	m_wWidthSpin = GTK_WIDGET(gtk_builder_get_object(builder, "sbWidth"));
	m_wWidthEntry = GTK_WIDGET(gtk_builder_get_object(builder, "edWidth"));
	m_wAspectCheck = GTK_WIDGET(gtk_builder_get_object(builder, "cbAspect"));

	m_wTitleEntry = GTK_WIDGET(gtk_builder_get_object(builder, "edTitle"));
	m_wDescriptionEntry = GTK_WIDGET(gtk_builder_get_object(builder, "edDescription"));

	m_bAspect = getPreserveAspect();
	gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (m_wAspectCheck), m_bAspect);
	
	m_oHeightSpin_adj = (GtkAdjustment*)gtk_adjustment_new( 1,-2000, 2000, 1, 1, 10);
   	gtk_widget_set_size_request(m_wHeightSpin,14,-1);  
	gtk_spin_button_set_adjustment (GTK_SPIN_BUTTON(m_wHeightSpin), GTK_ADJUSTMENT(m_oHeightSpin_adj));
	
	m_oWidthSpin_adj = (GtkAdjustment*)gtk_adjustment_new( 1,-2000, 2000, 1, 1, 10);
	gtk_widget_set_size_request(m_wWidthSpin,14,-1);  
	gtk_spin_button_set_adjustment (GTK_SPIN_BUTTON(m_wWidthSpin), GTK_ADJUSTMENT(m_oWidthSpin_adj));
	
    std::string s;
	pSS->getValueUTF8(XAP_STRING_ID_DLG_Image_Title,s);
	abiDialogSetTitle(mMainWindow, "%s", s.c_str());

    localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbDescTab")), pSS, XAP_STRING_ID_DLG_Image_DescTabLabel);
    localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbWrapTab")), pSS, XAP_STRING_ID_DLG_Image_WrapTabLabel);
#if defined(EMBEDDED_TARGET) && EMBEDDED_TARGET == EMBEDDED_TARGET_HILDON
    localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbPlacementTab")), pSS, XAP_STRING_ID_DLG_Image_PlacementTabLabel);
#endif

	localizeLabelMarkup(GTK_WIDGET(gtk_builder_get_object(builder, "lbSize")), pSS, XAP_STRING_ID_DLG_Image_ImageSize);
	localizeLabelMarkup(GTK_WIDGET(gtk_builder_get_object(builder, "lbImageDescription")), pSS, XAP_STRING_ID_DLG_Image_ImageDesc);
	localizeLabelMarkup(GTK_WIDGET(gtk_builder_get_object(builder, "lbTextWrapping")), pSS, XAP_STRING_ID_DLG_Image_TextWrapping);
	localizeLabelMarkup(GTK_WIDGET(gtk_builder_get_object(builder, "lbImagePlacement")), pSS, XAP_STRING_ID_DLG_Image_Placement);
	localizeLabelMarkup(GTK_WIDGET(gtk_builder_get_object(builder, "lbWrapType")), pSS, XAP_STRING_ID_DLG_Image_WrapType);
	
	localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbHeight")), pSS, XAP_STRING_ID_DLG_Image_Height);
	localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbWidth")), pSS, XAP_STRING_ID_DLG_Image_Width);
	localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbTitle")), pSS, XAP_STRING_ID_DLG_Image_LblTitle);
	localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbDescription")), pSS, XAP_STRING_ID_DLG_Image_LblDescription);

	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbInLine")), pSS, XAP_STRING_ID_DLG_Image_InLine);
	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbNone")), pSS, XAP_STRING_ID_DLG_Image_WrappedNone);
	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbWrappedRight")), pSS, XAP_STRING_ID_DLG_Image_WrappedRight);
	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbWrappedLeft")), pSS, XAP_STRING_ID_DLG_Image_WrappedLeft);
	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbWrappedBoth")), pSS, XAP_STRING_ID_DLG_Image_WrappedBoth);

	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbPlaceParagraph")), pSS, XAP_STRING_ID_DLG_Image_PlaceParagraph);
	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbPlaceColumn")), pSS, XAP_STRING_ID_DLG_Image_PlaceColumn);
	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbPlacePage")), pSS, XAP_STRING_ID_DLG_Image_PlacePage);

	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbSquareWrap")), pSS, XAP_STRING_ID_DLG_Image_SquareWrap);
	localizeButton(GTK_WIDGET(gtk_builder_get_object(builder, "rbTightWrap")), pSS, XAP_STRING_ID_DLG_Image_TightWrap);

	m_wPlaceTable = GTK_WIDGET(gtk_builder_get_object(builder, "tbPlacement"));
	m_wrbInLine = GTK_WIDGET(gtk_builder_get_object(builder, "rbInLine"));
	m_wrbNone = GTK_WIDGET(gtk_builder_get_object(builder, "rbNone"));
	m_wrbWrappedRight = GTK_WIDGET(gtk_builder_get_object(builder, "rbWrappedRight"));
	m_wrbWrappedLeft = GTK_WIDGET(gtk_builder_get_object(builder, "rbWrappedLeft"));
	m_wrbWrappedBoth = GTK_WIDGET(gtk_builder_get_object(builder, "rbWrappedBoth"));

	m_wrbPlaceParagraph = GTK_WIDGET(gtk_builder_get_object(builder, "rbPlaceParagraph"));
	m_wrbPlaceColumn = GTK_WIDGET(gtk_builder_get_object(builder, "rbPlaceColumn"));
	m_wrbPlacePage = GTK_WIDGET(gtk_builder_get_object(builder, "rbPlacePage"));

	m_wWrapTable = GTK_WIDGET(gtk_builder_get_object(builder, "tbWrapTable"));
	m_wrbSquareWrap = GTK_WIDGET(gtk_builder_get_object(builder, "rbSquareWrap"));
	m_wrbTightWrap = GTK_WIDGET(gtk_builder_get_object(builder, "rbTightWrap"));


// the check button already contains a label. We have to remove this
// before we can localize it

	gtk_container_remove(GTK_CONTAINER(m_wAspectCheck), gtk_bin_get_child(GTK_BIN(m_wAspectCheck)));
	pSS->getValueUTF8 (XAP_STRING_ID_DLG_Image_Aspect,s);
	gtk_button_set_label(GTK_BUTTON(m_wAspectCheck), s.c_str());

	m_iWidth = gtk_spin_button_get_value_as_int( GTK_SPIN_BUTTON(m_wWidthSpin));
	m_iHeight = gtk_spin_button_get_value_as_int( GTK_SPIN_BUTTON(m_wHeightSpin));

	gtk_entry_set_text (GTK_ENTRY(m_wTitleEntry), getTitle().utf8_str());
	gtk_entry_set_text (GTK_ENTRY(m_wDescriptionEntry), getDescription().utf8_str());

	_connectSignals ();
	
	g_object_unref(G_OBJECT(builder));

	return mMainWindow;
}
//-------------------------------------------------------------------------------------
PyObject* ClientEntityMethod::callmethod(PyObject* args, PyObject* kwds)
{
	Entity* srcEntity = Cellapp::getSingleton().findEntity(srcEntityID_);

	if(srcEntity == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "Entity::clientEntity(%s): srcEntityID(%d) not found!\n",		
			methodDescription_->getName(), srcEntityID_);		
		PyErr_PrintEx(0);
		return 0;
	}

	if(srcEntity->isDestroyed())
	{
		PyErr_Format(PyExc_AssertionError, "Entity::clientEntity(%s): srcEntityID(%d) is destroyed!\n",		
			methodDescription_->getName(), srcEntityID_);		
		PyErr_PrintEx(0);
		return 0;
	}

	if(srcEntity->pWitness() == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): no client, srcEntityID(%d).\n",		
			srcEntity->scriptName(), methodDescription_->getName(), srcEntity->id());		
		PyErr_PrintEx(0);
		return 0;
	}

	EntityRef::AOI_ENTITIES::iterator iter = srcEntity->pWitness()->aoiEntities().begin();
	Entity* e = NULL;

	for(; iter != srcEntity->pWitness()->aoiEntities().end(); ++iter)
	{
		if((*iter)->id() == clientEntityID_ && ((*iter)->flags() & 
			(ENTITYREF_FLAG_ENTER_CLIENT_PENDING | ENTITYREF_FLAG_LEAVE_CLIENT_PENDING)) <= 0)
		{
			e = (*iter)->pEntity();
			break;
		}
	}

	if(e == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): not found entity(%d), srcEntityID(%d).\n",		
			srcEntity->scriptName(), methodDescription_->getName(), clientEntityID_, srcEntity->id());	

		PyErr_PrintEx(0);

		return 0;
	}

	MethodDescription* methodDescription = getDescription();
	if(methodDescription->checkArgs(args))
	{
		MemoryStream* mstream = MemoryStream::ObjPool().createObject();
		methodDescription->addToStream(mstream, args);

		Network::Bundle* pForwardBundle = Network::Bundle::ObjPool().createObject();
		Network::Bundle* pSendBundle = Network::Bundle::ObjPool().createObject();

		srcEntity->pWitness()->addSmartAOIEntityMessageToBundle(pForwardBundle, ClientInterface::onRemoteMethodCall, 
				ClientInterface::onRemoteMethodCallOptimized, clientEntityID_);

		if(mstream->wpos() > 0)
			(*pForwardBundle).append(mstream->data(), (int)mstream->wpos());

		if(Network::g_trace_packet > 0)
		{
			if(Network::g_trace_packet_use_logfile)
				DebugHelper::getSingleton().changeLogger("packetlogs");

			DEBUG_MSG(fmt::format("ClientEntityMethod::callmethod: pushUpdateData: ClientInterface::onRemoteOtherEntityMethodCall({}::{})\n",
				srcEntity->scriptName(), methodDescription->getName()));
																								
			switch(Network::g_trace_packet)							
			{																								
			case 1:																							
				mstream->hexlike();																			
				break;																						
			case 2:																							
				mstream->textlike();																			
				break;																						
			default:																						
				mstream->print_storage();																	
				break;																						
			};																								

			if(Network::g_trace_packet_use_logfile)	
				DebugHelper::getSingleton().changeLogger(COMPONENT_NAME_EX(g_componentType));																				
		}

		NETWORK_ENTITY_MESSAGE_FORWARD_CLIENT(srcEntity->id(), (*pSendBundle), (*pForwardBundle));

		srcEntity->pWitness()->sendToClient(ClientInterface::onRemoteMethodCallOptimized, pSendBundle);

		// 记录这个事件产生的数据量大小
		g_publicClientEventHistoryStats.trackEvent(srcEntity->scriptName(), 
			(std::string(e->scriptName()) + "." + methodDescription->getName()), 
			pForwardBundle->currMsgLength(), 
			"::");

		MemoryStream::ObjPool().reclaimObject(mstream);
		Network::Bundle::ObjPool().reclaimObject(pForwardBundle);
	}

	S_Return;
}
Example #4
0
void scoreDataToScreen(WIDGET *psWidget)
{
	int index, x, y, width, height;
	bool bMoreBars;

	if (!bDispStarted)
	{
		bDispStarted = true;
		dispST = realTime;
		audio_PlayTrack(ID_SOUND_BUTTON_CLICK_5);
	}

	fillUpStats();

	pie_UniTransBoxFill(16 + D_W, MT_Y_POS - 16, pie_GetVideoBufferWidth() - D_W - 16, MT_Y_POS + 256 + 16, WZCOL_SCORE_BOX);
	iV_Box(16 + D_W, MT_Y_POS - 16, pie_GetVideoBufferWidth() - D_W - 16, MT_Y_POS + 256 + 16, WZCOL_SCORE_BOX_BORDER);

	iV_DrawText(_("Unit Losses"), LC_X + D_W, 80 + 16 + D_H);
	iV_DrawText(_("Structure Losses"), LC_X + D_W, 140 + 16 + D_H);
	iV_DrawText(_("Force Information"), LC_X + D_W, 200 + 16 + D_H);

	index = 0;
	bMoreBars = true;
	while (bMoreBars)
	{
		/* Is it time to display this bar? */
		if (infoBars[index].bActive)
		{
			/* Has it been queued before? */
			if (infoBars[index].bQueued == false)
			{
				/* Don't do this next time...! */
				infoBars[index].bQueued = true;

				/* Play a sound */
				audio_PlayTrack(ID_SOUND_BUTTON_CLICK_5);
			}
			x = infoBars[index].topX + D_W;
			y = infoBars[index].topY + D_H;
			width = infoBars[index].width;
			height = infoBars[index].height;

			iV_Box(x, y, x + width, y + height, WZCOL_BLACK);

			/* Draw the background border box */
			pie_BoxFill(x - 1, y - 1, x + width + 1, y + height + 1, WZCOL_MENU_BACKGROUND);

			/* Draw the interior grey */
			pie_BoxFill(x, y, x + width, y + height, WZCOL_MENU_SCORES_INTERIOR);

			if (((realTime - dispST) > infoBars[index].queTime))
			{
				/* Now draw amount filled */
				const float mul = (realTime - dispST < BAR_CRAWL_TIME) ?
				                  (float)(realTime - dispST) / (float)BAR_CRAWL_TIME
				                  : 1.f;

				const float length = (float)infoBars[index].percent / 100.f * (float)infoBars[index].width * mul;

				if ((int)length > 4)
				{

					/* Black shadow */
					pie_BoxFill(x + 1, y + 3, x + length - 1, y + height - 1, WZCOL_MENU_SHADOW);

					/* Solid coloured bit */
					pie_BoxFill(x + 1, y + 2, x + length - 4, y + height - 4, getColour(index));
				}
			}
			/* Now render the text by the bar */
			sprintf(text, getDescription((MR_STRING)infoBars[index].stringID), infoBars[index].number);
			iV_DrawText(text, x + width + 16, y + 12);

			/* If we're beyond STAT_ROOKIE, then we're on rankings */
			if (index >= STAT_GREEN && index <= STAT_ACE)
			{
				iV_DrawImage(IntImages, (UWORD)(IMAGE_LEV_0 + (index - STAT_GREEN)), x - 8, y + 2);
			}
		}
		/* Move onto the next bar */
		index++;
		if ((index > STAT_ACE) || (infoBars[index].topX == 0 && infoBars[index].topY == 0))
		{
			bMoreBars = false;
		}
	}

	/* We now need to display the mission time, game time, average unit experience level an number of artefacts found */

	/* Firstly, top of the screen, number of artefacts found */
	sprintf(text, _("ARTIFACTS RECOVERED: %d"), missionData.artefactsFound);
	iV_DrawText(text, (pie_GetVideoBufferWidth() - iV_GetTextWidth(text)) / 2, 300 + D_H);

	/* Get the mission result time in a string - and write it out */
	getAsciiTime((char *)&text2, gameTime - missionData.missionStarted);
	sprintf(text, _("Mission Time - %s"), text2);
	iV_DrawText(text, (pie_GetVideoBufferWidth() - iV_GetTextWidth(text)) / 2, 320 + D_H);

	/* Write out total game time so far */
	getAsciiTime((char *)&text2, gameTime);
	sprintf(text, _("Total Game Time - %s"), text2);
	iV_DrawText(text, (pie_GetVideoBufferWidth() - iV_GetTextWidth(text)) / 2, 340 + D_H);
	if (Cheated)
	{
		// A quick way to flash the text
		((realTime / 250) % 2) ? iV_SetTextColour(WZCOL_RED) : iV_SetTextColour(WZCOL_YELLOW);
		sprintf(text, _("You cheated!"));
		iV_DrawText(text, (pie_GetVideoBufferWidth() - iV_GetTextWidth(text)) / 2, 360 + D_H);
		iV_SetTextColour(WZCOL_TEXT_BRIGHT);
	}
}
Example #5
0
void KTListTasks::refresh()
{
  setText(0, getDescription());
  setPixmap(0, KTIcon::tasks(true));
}
Boolean UNIX_BGPService::getDescription(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
	return true;
}
Example #7
0
std::string Exception::getExtendedDescription() const
{
   return this->getExceptionName() + std::string(": ") + getDescription();
}
/*! Returns the thread's description.
 *  \deprecated Obsolete coding style.
 */
icl_core::String Thread::Description() const
{
  return getDescription();
}
Example #9
0
void CComponent::clickRight(tribool down, bool previousState)
{
	if(!getDescription().empty())
		adventureInt->handleRightClick(getDescription(), down);
}
Example #10
0
/*------------------------------------------------------------------------------
 *  Log in to the IceCast2 server
 *----------------------------------------------------------------------------*/
bool
IceCast2 :: sendLogin ( void )                           throw ( Exception )
{
    Sink          * sink   = getSink();
    Source        * source = getSocket();
    const char    * str;
    char            resp[STRBUF_SIZE];

    if ( !source->isOpen() ) {
        return false;
    }
    if ( !sink->isOpen() ) {
        return false;
    }

    /* send the request, a string like:
     * "SOURCE <mountpoint> ICE/1.0" */
    str = "SOURCE /";
    sink->write( str, strlen( str));
    str = getMountPoint();
    sink->write( str, strlen( str));
    str = " HTTP/1.0";
    sink->write( str, strlen( str));

    /* send the content type, Ogg Vorbis */
    str = "\nContent-type: ";
    sink->write( str, strlen( str));
    switch ( format ) {
        case mp3:
            str = "audio/mpeg";
            break;

        case oggVorbis:
            str = "application/x-ogg";
            break;

        default:
            throw Exception( __FILE__, __LINE__,
                             "unsupported stream format", format);
            break;
    }
    sink->write( str, strlen( str));

    /* send the authentication info */
    str = "\nAuthorization: Basic ";
    sink->write( str, strlen(str));
    {
        /* send source:<password> encoded as base64 */
        char        * source = "source:";
        const char  * pwd    = getPassword();
        char        * tmp    = new char[Util::strLen(source) +
                                        Util::strLen(str) + 1];
        Util::strCpy( tmp, source);
        Util::strCat( tmp, pwd);
        char  * base64 = Util::base64Encode( tmp);
        delete[] tmp;
        sink->write( base64, strlen(base64));
        delete[] base64;
    }

    /* send user agent info */
    str = "\nUser-Agent: DarkIce/" VERSION " (http://darkice.sourceforge.net/)";
    sink->write( str, strlen( str));

    /* send the ice- headers */
    str = "\nice-bitrate: ";
    sink->write( str, strlen( str));
    if ( log10(getBitRate()) >= (STRBUF_SIZE-2) ) {
        throw Exception( __FILE__, __LINE__,
                         "bitrate does not fit string buffer", getBitRate());
    }
    sprintf( resp, "%d", getBitRate());
    sink->write( resp, strlen( resp));

    str = "\nice-public: ";
    sink->write( str, strlen( str));
    str = getIsPublic() ? "1" : "0";
    sink->write( str, strlen( str));

    if ( getName() ) {
        str = "\nice-name: ";
        sink->write( str, strlen( str));
        str = getName();
        sink->write( str, strlen( str));
    }

    if ( getDescription() ) {
        str = "\nice-description: ";
        sink->write( str, strlen( str));
        str = getDescription();
        sink->write( str, strlen( str));
    }

    if ( getUrl() ) {
        str = "\nice-url: ";
        sink->write( str, strlen( str));
        str = getUrl();
        sink->write( str, strlen( str));
    }

    if ( getGenre() ) {
        str = "\nice-genre: ";
        sink->write( str, strlen( str));
        str = getGenre();
        sink->write( str, strlen( str));
    }

    str = "\n\n";
    sink->write( str, strlen( str));
    sink->flush();

    return true;
}
Example #11
0
std::string Player::getComment() const {
    return getDescription();
}
Example #12
0
 bool Rom::readDescription(Description& description, const char* path)
 {
     Header header;
     EMU_VERIFY(readHeader(header, path));
     return getDescription(description, header);
 }
//-------------------------------------------------------------------------------------
PyObject* ClientsRemoteEntityMethod::callmethod(PyObject* args, PyObject* kwds)
{
	// 获取entityAOI范围内其他entity
	// 向这些entity的client推送这个方法的调用
	MethodDescription* methodDescription = getDescription();

	Entity* pEntity = Cellapp::getSingleton().findEntity(id_);
	if(pEntity == NULL || /*pEntity->pWitness() == NULL ||*/
		pEntity->isDestroyed() /*|| pEntity->clientMailbox() == NULL*/)
	{
		//WARNING_MSG(fmt::format("EntityRemoteMethod::callClientMethod: not found entity({}).\n", 
		//	mailbox->id()));

		S_Return;
	}
	
	const std::list<ENTITY_ID>& entities = pEntity->witnesses();

	if(otherClients_)
	{
		if(pEntity->witnessesSize() == 0)
			S_Return;
	}
	
	// 先发给自己
	if(methodDescription->checkArgs(args))
	{
		MemoryStream* mstream = MemoryStream::ObjPool().createObject();
		methodDescription->addToStream(mstream, args);

		if((!otherClients_ && (pEntity->pWitness() || (pEntity->clientMailbox()))))
		{
			Network::Bundle* pBundle = Network::Bundle::ObjPool().createObject();
			pEntity->clientMailbox()->newMail((*pBundle));

			if(mstream->wpos() > 0)
				(*pBundle).append(mstream->data(), mstream->wpos());

			if(Network::g_trace_packet > 0)
			{
				if(Network::g_trace_packet_use_logfile)
					DebugHelper::getSingleton().changeLogger("packetlogs");

				DEBUG_MSG(fmt::format("ClientsRemoteEntityMethod::callmethod: pushUpdateData: ClientInterface::onRemoteMethodCall({}::{})\n", 
					pEntity->scriptName(), methodDescription->getName()));
																									
				switch(Network::g_trace_packet)																	
				{																								
				case 1:																							
					mstream->hexlike();																			
					break;																						
				case 2:																							
					mstream->textlike();																			
					break;																						
				default:																						
					mstream->print_storage();																	
					break;																						
				};																								

				if(Network::g_trace_packet_use_logfile)	
					DebugHelper::getSingleton().changeLogger(COMPONENT_NAME_EX(g_componentType));																				
			}

			//mailbox->postMail((*pBundle));
			pEntity->pWitness()->sendToClient(ClientInterface::onRemoteMethodCall, pBundle);

			// 记录这个事件产生的数据量大小
			g_publicClientEventHistoryStats.trackEvent(pEntity->scriptName(), 
				methodDescription->getName(), 
				pBundle->currMsgLength(), 
				"::");
		}
		
		// 广播给其他人
		std::list<ENTITY_ID>::const_iterator iter = entities.begin();
		for(; iter != entities.end(); ++iter)
		{
			Entity* pAoiEntity = Cellapp::getSingleton().findEntity((*iter));
			if(pAoiEntity == NULL || pAoiEntity->pWitness() == NULL || pAoiEntity->isDestroyed())
				continue;
			
			EntityMailbox* mailbox = pAoiEntity->clientMailbox();
			if(mailbox == NULL)
				continue;

			Network::Channel* pChannel = mailbox->getChannel();
			if(pChannel == NULL)
				continue;

			if(!pAoiEntity->pWitness()->entityInAOI(pEntity->id()))
				continue;

			Network::Bundle* pSendBundle = Network::Bundle::ObjPool().createObject();
			Network::Bundle* pForwardBundle = Network::Bundle::ObjPool().createObject();
			
			pAoiEntity->pWitness()->addSmartAOIEntityMessageToBundle(pForwardBundle, ClientInterface::onRemoteMethodCall, 
					ClientInterface::onRemoteMethodCallOptimized, pEntity->id());

			if(mstream->wpos() > 0)
				(*pForwardBundle).append(mstream->data(), mstream->wpos());

			if(Network::g_trace_packet > 0)
			{
				if(Network::g_trace_packet_use_logfile)
					DebugHelper::getSingleton().changeLogger("packetlogs");

				DEBUG_MSG(fmt::format("ClientsRemoteEntityMethod::callmethod: pushUpdateData: ClientInterface::onRemoteOtherEntityMethodCall({}::{})\n", 
					pAoiEntity->scriptName(), methodDescription->getName()));
																									
				switch(Network::g_trace_packet)																	
				{																								
				case 1:																							
					mstream->hexlike();																			
					break;																						
				case 2:																							
					mstream->textlike();																			
					break;																						
				default:																						
					mstream->print_storage();																	
					break;																						
				};																								

				if(Network::g_trace_packet_use_logfile)	
					DebugHelper::getSingleton().changeLogger(COMPONENT_NAME_EX(g_componentType));																				
			}

			NETWORK_ENTITY_MESSAGE_FORWARD_CLIENT(pAoiEntity->id(), (*pSendBundle), (*pForwardBundle));

			//mailbox->postMail((*pBundle));
			pAoiEntity->pWitness()->sendToClient(ClientInterface::onRemoteMethodCallOptimized, pSendBundle);

			// 记录这个事件产生的数据量大小
			g_publicClientEventHistoryStats.trackEvent(pAoiEntity->scriptName(), 
				methodDescription->getName(), 
				pForwardBundle->currMsgLength(), 
				"::");

			Network::Bundle::ObjPool().reclaimObject(pForwardBundle);
		}

		MemoryStream::ObjPool().reclaimObject(mstream);
	}

	S_Return;
}
Example #14
0
 QString description() const {
     return QString::fromStdString(getDescription());
 }
Boolean UNIX_BootConfigSetting::getDescription(CIMProperty &p) const
{
	p = CIMProperty(PROPERTY_DESCRIPTION, getDescription());
	return true;
}
Example #16
0
char *SaveConverter::getDescription(const Common::String &fileName) {
	setFileName(fileName);
	return getDescription();
}
Example #17
0
bool StAVImage::load(const StString& theFilePath,
                     ImageType       theImageType,
                     uint8_t*        theDataPtr,
                     int             theDataSize) {

    // reset current data
    StImage::nullify();
    setState();
    close();
    myMetadata.clear();

    switch(theImageType) {
        case ST_TYPE_PNG:
        case ST_TYPE_PNS: {
            myCodec = avcodec_find_decoder_by_name("png");
            break;
        }
        case ST_TYPE_JPEG:
        case ST_TYPE_MPO:
        case ST_TYPE_JPS: {
            myCodec = avcodec_find_decoder_by_name("mjpeg");
            break;
        }
        case ST_TYPE_EXR: {
            myCodec = avcodec_find_decoder_by_name("exr");
            break;
        }
        case ST_TYPE_WEBP:
        case ST_TYPE_WEBPLL: {
            myCodec = avcodec_find_decoder_by_name("webp");
            break;
        }
        default: {
            break;
        }
    }

    if(theImageType == ST_TYPE_NONE
    || (theDataPtr == NULL && !StFileNode::isFileExists(theFilePath))) {
        // open image file and detect its type, its could be non local file!
    #if(LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(53, 2, 0))
        int avErrCode = avformat_open_input(&myFormatCtx, theFilePath.toCString(), myImageFormat, NULL);
    #else
        int avErrCode = av_open_input_file (&myFormatCtx, theFilePath.toCString(), myImageFormat, 0, NULL);
    #endif
        if(avErrCode != 0
        || myFormatCtx->nb_streams < 1
        || myFormatCtx->streams[0]->codec->codec_id == 0) {
            if(myFormatCtx != NULL) {
            #if(LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(53, 17, 0))
                avformat_close_input(&myFormatCtx);
            #else
                av_close_input_file(myFormatCtx);
                myFormatCtx = NULL;
            #endif
            }

        #if(LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(53, 2, 0))
            avErrCode = avformat_open_input(&myFormatCtx, theFilePath.toCString(), NULL, NULL);
        #else
            avErrCode = av_open_input_file(&myFormatCtx, theFilePath.toCString(), NULL, 0, NULL);
        #endif
        }

        if(avErrCode != 0
        || myFormatCtx->nb_streams < 1) {
            setState(StString("AVFormat library, couldn't open image file. Error: ") + stAV::getAVErrorDescription(avErrCode));
            close();
            return false;
        }

        // find the decoder for the video stream
        myCodecCtx = myFormatCtx->streams[0]->codec;
        if(theImageType == ST_TYPE_NONE) {
            myCodec = avcodec_find_decoder(myCodecCtx->codec_id);
        }
    }

    if(myCodec == NULL) {
        setState("AVCodec library, video codec not found");
        close();
        return false;
    } else if(myFormatCtx == NULL) {
        // use given image type to load decoder
    #if(LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53, 8, 0))
        myCodecCtx = avcodec_alloc_context3(myCodec);
    #else
        myCodecCtx = avcodec_alloc_context();
    #endif
    }

    // stupid check
    if(myCodecCtx == NULL) {
        setState("AVCodec library, codec context is NULL");
        close();
        return false;
    }

    // open VIDEO codec
#if(LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53, 8, 0))
    if(avcodec_open2(myCodecCtx, myCodec, NULL) < 0) {
#else
    if(avcodec_open(myCodecCtx, myCodec) < 0) {
#endif
        setState("AVCodec library, could not open video codec");
        close();
        return false;
    }

    // read one packet or file
    StRawFile aRawFile(theFilePath);
    StAVPacket anAvPkt;
    if(theDataPtr != NULL && theDataSize != 0) {
        anAvPkt.getAVpkt()->data = theDataPtr;
        anAvPkt.getAVpkt()->size = theDataSize;
    } else {
        if(myFormatCtx != NULL) {
            if(av_read_frame(myFormatCtx, anAvPkt.getAVpkt()) < 0) {
                setState("AVFormat library, could not read first packet");
                close();
                return false;
            }
        } else {
            if(!aRawFile.readFile()) {
                setState("StAVImage, could not read the file");
                close();
                return false;
            }
            anAvPkt.getAVpkt()->data = (uint8_t* )aRawFile.getBuffer();
            anAvPkt.getAVpkt()->size = (int )aRawFile.getSize();
        }
    }
    anAvPkt.setKeyFrame();

    // decode one frame
    int isFrameFinished = 0;
#if(LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 23, 0))
    avcodec_decode_video2(myCodecCtx, myFrame.Frame, &isFrameFinished, anAvPkt.getAVpkt());
#else
    avcodec_decode_video(myCodecCtx, myFrame.Frame, &isFrameFinished,
                         theDataPtr, theDataSize);
#endif

    if(isFrameFinished == 0) {
        // thats not an image!!! try to decode more packets???
        setState("AVCodec library, input file is not an Image!");
        close();
        return false;
    }

    // check frame size
    if(myCodecCtx->width <= 0 || myCodecCtx->height <= 0) {
        setState("AVCodec library, codec returns wrong frame size");
        close();
        return false;
    }

    // read aspect ratio
    if(myCodecCtx->sample_aspect_ratio.num == 0
    || myCodecCtx->sample_aspect_ratio.den == 0) {
        setPixelRatio(1.0f);
    } else {
        const GLfloat aRatio = GLfloat(myCodecCtx->sample_aspect_ratio.num) / GLfloat(myCodecCtx->sample_aspect_ratio.den);
        if(aRatio > 70.0f) {
            ST_DEBUG_LOG("AVCodec library, igning wrong PAR " + myCodecCtx->sample_aspect_ratio.num + ":" + myCodecCtx->sample_aspect_ratio.den);
            setPixelRatio(1.0f);
        } else {
            setPixelRatio(aRatio);
        }
    }

#ifdef ST_AV_NEWSTEREO
    // currently it is unlikelly... but maybe in future?
    AVFrameSideData* aSideData = av_frame_get_side_data(myFrame.Frame, AV_FRAME_DATA_STEREO3D);
    if(aSideData != NULL) {
        AVStereo3D* aStereo = (AVStereo3D* )aSideData->data;
        mySrcFormat = stAV::stereo3dAvToSt(aStereo->type);
        if(aStereo->flags & AV_STEREO3D_FLAG_INVERT) {
            mySrcFormat = st::formatReversed(mySrcFormat);
        }
    } else {
        mySrcFormat = StFormat_AUTO;
    }
#endif

    // it is unlikely that there would be any metadata from format...
    // but lets try
    if(myFormatCtx != NULL) {
        for(stAV::meta::Tag* aTag = stAV::meta::findTag(myFormatCtx->metadata, "", NULL, stAV::meta::SEARCH_IGNORE_SUFFIX);
            aTag != NULL;
            aTag = stAV::meta::findTag(myFormatCtx->metadata, "", aTag, stAV::meta::SEARCH_IGNORE_SUFFIX)) {
            myMetadata.add(StDictEntry(aTag->key, aTag->value));
        }
        for(stAV::meta::Tag* aTag = stAV::meta::findTag(myFormatCtx->streams[0]->metadata, "", NULL, stAV::meta::SEARCH_IGNORE_SUFFIX);
            aTag != NULL;
            aTag = stAV::meta::findTag(myFormatCtx->streams[0]->metadata, "", aTag, stAV::meta::SEARCH_IGNORE_SUFFIX)) {
            myMetadata.add(StDictEntry(aTag->key, aTag->value));
        }
    }

    // collect metadata from the frame
    stAV::meta::Dict* aFrameMetadata = stAV::meta::getFrameMetadata(myFrame.Frame);
    for(stAV::meta::Tag* aTag = stAV::meta::findTag(aFrameMetadata, "", NULL, stAV::meta::SEARCH_IGNORE_SUFFIX);
        aTag != NULL;
        aTag = stAV::meta::findTag(aFrameMetadata, "", aTag, stAV::meta::SEARCH_IGNORE_SUFFIX)) {
        myMetadata.add(StDictEntry(aTag->key, aTag->value));
    }

    stAV::dimYUV aDimsYUV;
    if(myCodecCtx->pix_fmt == stAV::PIX_FMT::RGB24) {
        setColorModel(StImage::ImgColor_RGB);
        changePlane(0).initWrapper(StImagePlane::ImgRGB, myFrame.getPlane(0),
                                   myCodecCtx->width, myCodecCtx->height,
                                   myFrame.getLineSize(0));
    } else if(myCodecCtx->pix_fmt == stAV::PIX_FMT::BGR24) {
        setColorModel(StImage::ImgColor_RGB);
        changePlane(0).initWrapper(StImagePlane::ImgBGR, myFrame.getPlane(0),
                                   myCodecCtx->width, myCodecCtx->height,
                                   myFrame.getLineSize(0));
    } else if(myCodecCtx->pix_fmt == stAV::PIX_FMT::RGBA32) {
        setColorModel(StImage::ImgColor_RGBA);
        changePlane(0).initWrapper(StImagePlane::ImgRGBA, myFrame.getPlane(0),
                                   myCodecCtx->width, myCodecCtx->height,
                                   myFrame.getLineSize(0));
    } else if(myCodecCtx->pix_fmt == stAV::PIX_FMT::BGRA32) {
        setColorModel(StImage::ImgColor_RGBA);
        changePlane(0).initWrapper(StImagePlane::ImgBGRA, myFrame.getPlane(0),
                                   myCodecCtx->width, myCodecCtx->height,
                                   myFrame.getLineSize(0));
    } else if(myCodecCtx->pix_fmt == stAV::PIX_FMT::GRAY8) {
        setColorModel(StImage::ImgColor_GRAY);
        changePlane(0).initWrapper(StImagePlane::ImgGray, myFrame.getPlane(0),
                                   myCodecCtx->width, myCodecCtx->height,
                                   myFrame.getLineSize(0));
    } else if(myCodecCtx->pix_fmt == stAV::PIX_FMT::GRAY16) {
        setColorModel(StImage::ImgColor_GRAY);
        changePlane(0).initWrapper(StImagePlane::ImgGray16, myFrame.getPlane(0),
                                   myCodecCtx->width, myCodecCtx->height,
                                   myFrame.getLineSize(0));
    } else if(myCodecCtx->pix_fmt == stAV::PIX_FMT::RGB48) {
        setColorModel(StImage::ImgColor_RGB);
        changePlane(0).initWrapper(StImagePlane::ImgRGB48, myFrame.getPlane(0),
                                   myCodecCtx->width, myCodecCtx->height,
                                   myFrame.getLineSize(0));
    } else if(myCodecCtx->pix_fmt == stAV::PIX_FMT::RGBA64) {
        setColorModel(StImage::ImgColor_RGBA);
        changePlane(0).initWrapper(StImagePlane::ImgRGBA64, myFrame.getPlane(0),
                                   myCodecCtx->width, myCodecCtx->height,
                                   myFrame.getLineSize(0));
    } else if(stAV::isFormatYUVPlanar(myCodecCtx, aDimsYUV)) {
    #if(LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 29, 0))
        if(myCodecCtx->color_range == AVCOL_RANGE_JPEG) {
            aDimsYUV.isFullScale = true;
        }
    #endif
        setColorModel(StImage::ImgColor_YUV);
        setColorScale(aDimsYUV.isFullScale ? StImage::ImgScale_Full : StImage::ImgScale_Mpeg);
        StImagePlane::ImgFormat aPlaneFrmt = StImagePlane::ImgGray;
        if(aDimsYUV.bitsPerComp == 9) {
            aPlaneFrmt = StImagePlane::ImgGray16;
            setColorScale(aDimsYUV.isFullScale ? StImage::ImgScale_Jpeg9  : StImage::ImgScale_Mpeg9);
        } else if(aDimsYUV.bitsPerComp == 10) {
            aPlaneFrmt = StImagePlane::ImgGray16;
            setColorScale(aDimsYUV.isFullScale ? StImage::ImgScale_Jpeg10 : StImage::ImgScale_Mpeg10);
        } else if(aDimsYUV.bitsPerComp == 16) {
            aPlaneFrmt = StImagePlane::ImgGray16;
        }

        changePlane(0).initWrapper(aPlaneFrmt, myFrame.getPlane(0),
                                   size_t(aDimsYUV.widthY), size_t(aDimsYUV.heightY), myFrame.getLineSize(0));
        changePlane(1).initWrapper(aPlaneFrmt, myFrame.getPlane(1),
                                   size_t(aDimsYUV.widthU), size_t(aDimsYUV.heightU), myFrame.getLineSize(1));
        changePlane(2).initWrapper(aPlaneFrmt, myFrame.getPlane(2),
                                   size_t(aDimsYUV.widthV), size_t(aDimsYUV.heightV), myFrame.getLineSize(2));
    } else {
        ///ST_DEBUG_LOG("StAVImage, perform conversion from Pixel format '" + avcodec_get_pix_fmt_name(myCodecCtx->pix_fmt) + "' to RGB");
        // initialize software scaler/converter
        SwsContext* pToRgbCtx = sws_getContext(myCodecCtx->width, myCodecCtx->height, myCodecCtx->pix_fmt,    // source
                                               myCodecCtx->width, myCodecCtx->height, stAV::PIX_FMT::RGB24, // destination
                                               SWS_BICUBIC, NULL, NULL, NULL);
        if(pToRgbCtx == NULL) {
            setState("SWScale library, failed to create SWScaler context");
            close();
            return false;
        }

        // initialize additional buffer for converted RGB data
        setColorModel(StImage::ImgColor_RGB);
        changePlane(0).initTrash(StImagePlane::ImgRGB,
                                 myCodecCtx->width, myCodecCtx->height);

        uint8_t* rgbData[4]; stMemZero(rgbData,     sizeof(rgbData));
        int  rgbLinesize[4]; stMemZero(rgbLinesize, sizeof(rgbLinesize));
        rgbData[0]     = changePlane(0).changeData();
        rgbLinesize[0] = (int )changePlane(0).getSizeRowBytes();

        sws_scale(pToRgbCtx,
                  myFrame.Frame->data, myFrame.Frame->linesize,
                  0, myCodecCtx->height,
                  rgbData, rgbLinesize);
        // reset original data
        closeAvCtx();

        sws_freeContext(pToRgbCtx);
    }

    // set debug information
    StString aDummy, aFileName;
    StFileNode::getFolderAndFile(theFilePath, aDummy, aFileName);
    setState(StString("AVCodec library, loaded image '") + aFileName + "' " + getDescription());

    // we should not close the file because decoded image data is in codec context cache
    return true;
}

bool StAVImage::save(const StString& theFilePath,
                     ImageType       theImageType,
                     StFormat        theSrcFormat) {
    close();
    setState();
    if(isNull()) {
        return false;
    }

    PixelFormat aPFormatAV = (PixelFormat )getAVPixelFormat(*this);
    StImage anImage;
    switch(theImageType) {
        case ST_TYPE_PNG:
        case ST_TYPE_PNS: {
            myCodec = avcodec_find_encoder_by_name("png");
            if(myCodec == NULL) {
                setState("AVCodec library, video codec 'png' not found");
                close();
                return false;
            }
            if(aPFormatAV == stAV::PIX_FMT::RGB24
            || aPFormatAV == stAV::PIX_FMT::RGBA32
            || aPFormatAV == stAV::PIX_FMT::GRAY8) {
                anImage.initWrapper(*this);
            } else {
                // convert to compatible pixel format
                anImage.changePlane().initTrash(StImagePlane::ImgRGB, getSizeX(), getSizeY(), getAligned(getSizeX() * 3));
                PixelFormat aPFrmtTarget = stAV::PIX_FMT::RGB24;
                if(!convert(*this,   aPFormatAV,
                            anImage, aPFrmtTarget)) {
                    setState("SWScale library, failed to create SWScaler context");
                    close();
                    return false;
                }
                aPFormatAV = aPFrmtTarget;
            }
        #if(LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53, 8, 0))
            myCodecCtx = avcodec_alloc_context3(myCodec);
        #else
            myCodecCtx = avcodec_alloc_context();
        #endif

            // setup encoder
            myCodecCtx->pix_fmt = aPFormatAV;
            myCodecCtx->width   = (int )anImage.getSizeX();
            myCodecCtx->height  = (int )anImage.getSizeY();
            myCodecCtx->compression_level = 9; // 0..9
            break;
        }
        case ST_TYPE_JPEG:
        case ST_TYPE_MPO:
        case ST_TYPE_JPS: {
            myCodec = avcodec_find_encoder_by_name("mjpeg");
            if(myCodec == NULL) {
                setState("AVCodec library, video codec 'mjpeg' not found");
                close();
                return false;
            }

            if(aPFormatAV == stAV::PIX_FMT::YUVJ420P
            || aPFormatAV == stAV::PIX_FMT::YUVJ422P
            //|| aPFormatAV == stAV::PIX_FMT::YUVJ444P not supported by FFmpeg... yet?
            //|| aPFormatAV == stAV::PIX_FMT::YUVJ440P
               ) {
                anImage.initWrapper(*this);
            } else {
                // convert to compatible pixel format
                PixelFormat aPFrmtTarget = aPFormatAV == stAV::PIX_FMT::YUV420P ? stAV::PIX_FMT::YUVJ420P : stAV::PIX_FMT::YUVJ422P;
                anImage.setColorModel(StImage::ImgColor_YUV);
                anImage.setColorScale(StImage::ImgScale_Mpeg);
                anImage.changePlane(0).initTrash(StImagePlane::ImgGray, getSizeX(), getSizeY(), getAligned(getSizeX()));
                stMemSet(anImage.changePlane(0).changeData(), '\0', anImage.getPlane(0).getSizeBytes());
                anImage.changePlane(1).initTrash(StImagePlane::ImgGray, getSizeX(), getSizeY(), getAligned(getSizeX()));
                stMemSet(anImage.changePlane(1).changeData(), '\0', anImage.getPlane(1).getSizeBytes());
                anImage.changePlane(2).initTrash(StImagePlane::ImgGray, getSizeX(), getSizeY(), getAligned(getSizeX()));
                stMemSet(anImage.changePlane(2).changeData(), '\0', anImage.getPlane(2).getSizeBytes());
                if(!convert(*this,   aPFormatAV,
                            anImage, aPFrmtTarget)) {
                    setState("SWScale library, failed to create SWScaler context");
                    close();
                    return false;
                }
                aPFormatAV = aPFrmtTarget;
            }

        #if(LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53, 8, 0))
            myCodecCtx = avcodec_alloc_context3(myCodec);
        #else
            myCodecCtx = avcodec_alloc_context();
        #endif
            myCodecCtx->pix_fmt = aPFormatAV;
            myCodecCtx->width   = (int )anImage.getSizeX();
            myCodecCtx->height  = (int )anImage.getSizeY();
            myCodecCtx->time_base.num = 1;
            myCodecCtx->time_base.den = 1;
            myCodecCtx->qmin = myCodecCtx->qmax = 5; // quality factor - lesser is better
            break;
        }
        case ST_TYPE_NONE:
        default:
            close();
            return false;
    }

    // open VIDEO codec
#if(LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(53, 8, 0))
    if(avcodec_open2(myCodecCtx, myCodec, NULL) < 0) {
#else
    if(avcodec_open(myCodecCtx, myCodec) < 0) {
#endif
        setState("AVCodec library, could not open video codec");
        close();
        return false;
    }

    // wrap own data into AVFrame
    myFrame.Frame->format = myCodecCtx->pix_fmt;
    myFrame.Frame->width  = myCodecCtx->width;
    myFrame.Frame->height = myCodecCtx->height;
    fillPointersAV(anImage, myFrame.Frame->data, myFrame.Frame->linesize);

#ifdef ST_AV_NEWSTEREO
    bool isReversed = false;
    AVStereo3DType anAvStereoType = stAV::stereo3dStToAv(theSrcFormat, isReversed);
    if(anAvStereoType != (AVStereo3DType )-1) {
        AVStereo3D* aStereo = av_stereo3d_create_side_data(myFrame.Frame);
        if(aStereo != NULL) {
            aStereo->type = anAvStereoType;
            if(isReversed) {
                aStereo->flags |= AV_STEREO3D_FLAG_INVERT;
            }
        }
    }
#endif

    StJpegParser aRawFile(theFilePath);
    if(!aRawFile.openFile(StRawFile::WRITE)) {
        setState("Can not open the file for writing");
        close();
        return false;
    }

    // allocate the buffer, large enough (stupid formula copied from ffmpeg.c)
    int aBuffSize = int(getSizeX() * getSizeY() * 10);
    aRawFile.initBuffer(aBuffSize);

    // encode the image
    StAVPacket aPacket;
    aPacket.getAVpkt()->data = (uint8_t* )aRawFile.changeBuffer();
    aPacket.getAVpkt()->size = aBuffSize;
#if(LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(54, 2, 100))
    int isGotPacket = 0;
    int anEncSize   = avcodec_encode_video2(myCodecCtx, aPacket.getAVpkt(), myFrame.Frame, &isGotPacket);
    if(anEncSize == 0 && isGotPacket != 0) {
        anEncSize = aPacket.getSize();
    }
#else
    int anEncSize = avcodec_encode_video(myCodecCtx, aPacket.changeData(), aPacket.getSize(), myFrame.Frame);
#endif
    if(anEncSize <= 0) {
        setState("AVCodec library, fail to encode the image");
        close();
        return false;
    }
    aRawFile.setDataSize((size_t )anEncSize);

    // save metadata when possible
    if(theImageType == ST_TYPE_JPEG
    || theImageType == ST_TYPE_JPS) {
        if(aRawFile.parse()) {
            if(theSrcFormat != StFormat_AUTO) {
                aRawFile.setupJps(theSrcFormat);
            }
        } else {
            ST_ERROR_LOG("AVCodec library, created JPEG can not be parsed!");
        }
    }

    // store current content
    aRawFile.writeFile();
    // and finally close the file handle
    aRawFile.closeFile();

    close();

    // set debug information
    StString aDummy, aFileName;
    StFileNode::getFolderAndFile(theFilePath, aDummy, aFileName);
    setState(StString("AVCodec library, saved image '") + aFileName + "' " + getDescription());

    return true;
}
Example #18
0
bool StFreeImage::load(const StString& theFilePath, ImageType theImageType,
                       uint8_t* theDataPtr, int theDataSize) {
    if(!StFreeImage::init()) {
        setState("FreeImage library is not initialized");
        return false;
    }

    // reset current data
    StImage::nullify();
    setState();
    close();

    FREE_IMAGE_FORMAT aFIF = convertToFIF(theImageType);
    if(theDataPtr != NULL && theDataSize != 0 && aFIF != FIF_UNKNOWN) {
        FIMEMORY* aFIMemory = FreeImage_OpenMemory(theDataPtr, theDataSize);
        if(aFIMemory == NULL) {
            setState("FreeImage library, internal error");
            return false;
        }
        myDIB = FreeImage_LoadFromMemory(aFIF, aFIMemory, 0);
        FreeImage_CloseMemory(aFIMemory);
    } else {
        // check the file signature and deduce its format
    #if defined(_WIN32)
        StStringUtfWide aFilePathWide = theFilePath.toUtfWide();
        aFIF = FreeImage_GetFileType(aFilePathWide.toCString(), 0);
    #else
        aFIF = FreeImage_GetFileType(theFilePath.toCString(), 0);
    #endif
        if(aFIF == FIF_UNKNOWN) {
            // no signature? try to guess the file format from the file extension
        #if defined(_WIN32)
            aFIF = FreeImage_GetFIFFromFilename(aFilePathWide.toCString());
        #else
            aFIF = FreeImage_GetFIFFromFilename(theFilePath.toCString());
        #endif
        }
        if((aFIF == FIF_UNKNOWN) || !FreeImage_FIFSupportsReading(aFIF)) {
            setState("FreeImage library does not support image format");
            return false;
        }

        int loadFlags = 0;
        if(aFIF == FIF_GIF) {
            // GIF_PLAYBACK - 'Play' the GIF to generate each frame (as 32bpp) instead of returning raw frame data when loading
            loadFlags = 2;
        } else if(aFIF == FIF_ICO) {
            // ICO_MAKEALPHA - convert to 32bpp and create an alpha channel from the AND-mask when loading
            loadFlags = 1;
        }
    #if defined(_WIN32)
        myDIB = FreeImage_Load(aFIF, aFilePathWide.toCString(), loadFlags);
    #else
        myDIB = FreeImage_Load(aFIF, theFilePath.toCString(),   loadFlags);
    #endif
    }
    if(myDIB == NULL) {
        setState("FreeImage library, loading file failed");
        return false;
    }

    StImagePlane::ImgFormat stImgFormat = convertFromFreeFormat(FreeImage_GetImageType(myDIB),
                                                                FreeImage_GetColorType(myDIB),
                                                                FreeImage_GetBPP(myDIB));

    if(stImgFormat == StImagePlane::ImgUNKNOWN) {
        setState(StString("StFreeImage, image format ")
                 + FreeImage_GetImageType(myDIB) + ", " + FreeImage_GetColorType(myDIB)
                 + " doesn't supported by application");
        close();
        return false;
    }

    setColorModelPacked(stImgFormat);
    changePlane(0).initWrapper(stImgFormat, FreeImage_GetBits(myDIB),
                               FreeImage_GetWidth(myDIB),
                               FreeImage_GetHeight(myDIB),
                               FreeImage_GetPitch(myDIB));
    // FreeImage data always bottom-up...
    changePlane(0).setTopDown(false);

    // set debug information
    StString aDummy, aFileName;
    StFileNode::getFolderAndFile(theFilePath, aDummy, aFileName);
    setState(StString("FreeImage library, loaded image '") + aFileName + "' " + getDescription());

    // we should not close the file because we create a wrapper over FreeImage native object
    return true;
}
  virtual bool adaptAndPlan(const PlannerFn &planner,
                            const planning_scene::PlanningSceneConstPtr& planning_scene,
                            const planning_interface::MotionPlanRequest &req, 
                            planning_interface::MotionPlanResponse &res,
                            std::vector<std::size_t> &added_path_index) const
  {
    ROS_DEBUG("Running '%s'", getDescription().c_str());
    
    // get the specified start state
    robot_state::RobotState start_state = planning_scene->getCurrentState();
    robot_state::robotStateMsgToRobotState(*planning_scene->getTransforms(), req.start_state, start_state);

    const std::vector<robot_state::JointState*> &jstates = 
      planning_scene->getRobotModel()->hasJointModelGroup(req.group_name) ? 
      start_state.getJointStateGroup(req.group_name)->getJointStateVector() : 
      start_state.getJointStateVector(); 
    
    bool change_req = false;
    for (std::size_t i = 0 ; i < jstates.size() ; ++i)
    { 
      // Check if we have a revolute, continuous joint. If we do, then we only need to make sure
      // it is within de model's declared bounds (usually -Pi, Pi), since the values wrap around. 
      // It is possible that the encoder maintains values outside the range [-Pi, Pi], to inform
      // how many times the joint was wrapped. Because of this, we remember the offsets for continuous
      // joints, and we un-do them when the plan comes from the planner
      
      const robot_model::JointModel* jm = jstates[i]->getJointModel();
      if (jm->getType() == robot_model::JointModel::REVOLUTE)
      {
        if (static_cast<const robot_model::RevoluteJointModel*>(jm)->isContinuous())
        {
          double initial = jstates[i]->getVariableValues()[0];
          jstates[i]->enforceBounds();
          double after = jstates[i]->getVariableValues()[0];
          if (fabs(initial - after) > std::numeric_limits<double>::epsilon())
            change_req = true;
        } 
      }
      else
        // Normalize yaw; no offset needs to be remembered
        if (jm->getType() == robot_model::JointModel::PLANAR)
        {   
          double initial = jstates[i]->getVariableValues()[2];
          if (static_cast<const robot_model::PlanarJointModel*>(jm)->normalizeRotation(jstates[i]->getVariableValues()))
            change_req = true;
        }
        else
          // Normalize quaternions
          if (jm->getType() == robot_model::JointModel::FLOATING)
          {
            if (static_cast<const robot_model::FloatingJointModel*>(jm)->normalizeRotation(jstates[i]->getVariableValues()))
              change_req = true;
          }
    }
    
    // pointer to a prefix state we could possibly add, if we detect we have to make changes
    robot_state::RobotStatePtr prefix_state;
    for (std::size_t i = 0 ; i < jstates.size() ; ++i)
    {   
      if (!jstates[i]->satisfiesBounds())
      {    
        if (jstates[i]->satisfiesBounds(bounds_dist_))
        {
          if (!prefix_state)
            prefix_state.reset(new robot_state::RobotState(start_state));
          jstates[i]->enforceBounds();
          change_req = true;
          ROS_INFO("Starting state is just outside bounds (joint '%s'). Assuming within bounds.", jstates[i]->getName().c_str());
        }
        else
        {
          std::stringstream joint_values;
          std::stringstream joint_bounds_low;
          std::stringstream joint_bounds_hi;
          for (std::size_t k = 0 ; k < jstates[i]->getVariableValues().size() ; ++k)
            joint_values << jstates[i]->getVariableValues()[k] << " ";
          for (std::size_t k = 0 ; k < jstates[i]->getVariableBounds().size() ; ++k)
          {
            joint_bounds_low << jstates[i]->getVariableBounds()[k].first << " ";
            joint_bounds_hi << jstates[i]->getVariableBounds()[k].second << " ";
          }
          ROS_WARN_STREAM("Joint '" << jstates[i]->getName() << "' from the starting state is outside bounds by a significant margin: [ " << joint_values.str() << "] should be in the range [ " << joint_bounds_low.str() <<
                          "], [ " << joint_bounds_hi.str() << "] but the error above the ~" << BOUNDS_PARAM_NAME << " parameter (currently set to " << bounds_dist_ << ")");
        }
      }
    }

    bool solved;
    // if we made any changes, use them
    if (change_req)
    {
      planning_interface::MotionPlanRequest req2 = req;
      robot_state::robotStateToRobotStateMsg(start_state, req2.start_state);
      solved = planner(planning_scene, req2, res);
    }
    else
      solved = planner(planning_scene, req, res);

    // re-add the prefix state, if it was constructed
    if (prefix_state && res.trajectory_)
    {    
      if (!res.trajectory_->empty())
        // heuristically decide a duration offset for the trajectory (induced by the additional point added as a prefix to the computed trajectory)
        res.trajectory_->setWayPointDurationFromPrevious(0, std::min(max_dt_offset_, res.trajectory_->getAverageSegmentDuration()));
      res.trajectory_->addPrefixWayPoint(prefix_state, 0.0);
      added_path_index.push_back(0);
    }

    return solved;
  }
Example #20
0
bool StFreeImage::save(const StString& theFilePath,
                       ImageType       theImageType,
                       StFormatEnum ) {
    if(!StFreeImage::init()) {
        setState("FreeImage library is not initialized");
        return false;
    }

    FREE_IMAGE_FORMAT aFIF = convertToFIF(theImageType);
    if(aFIF == FIF_UNKNOWN) {
        setState("FreeImage library, not supported image file format");
        return false;
    }

    StImage stSaveImage;
    if(getColorModel() != ImgColor_RGB && getColorModel() != ImgColor_RGBA && getColorModel() != ImgColor_GRAY) {
        // convert from YUV and so on
        if(!stSaveImage.initRGB(*this)) {
            setState("StFreeImage, only RGB image could be saved");
            return false;
        }
    } else {
        stSaveImage.initWrapper(*this);
    }
    const StImagePlane& stImgPlane = stSaveImage.getPlane();

    FREE_IMAGE_TYPE aSaveFormatFI = FIT_UNKNOWN;
    if(!convertToFreeFormat(stImgPlane.getFormat(), aSaveFormatFI)) {
        setState("StFreeImage, image format currently not supported");
        return false;
    }

    // allocate FreeImage native structure
    FIBITMAP* aSaveDIB = FreeImage_AllocateT(aSaveFormatFI, (int )stImgPlane.getSizeX(), (int )stImgPlane.getSizeY(),
                                             (unsigned )stImgPlane.getSizePixelBytes() * 8, 0, 0, 0);
    if(aSaveDIB == NULL) {
        setState("FreeImage library, internal error");
        FreeImage_Unload(aSaveDIB);
        return false;
    }
    // wrapper the created data
    StImagePlane stImgPlaneSave;
    StImagePlane::ImgFormat stImgFormatSave = convertFromFreeFormat(FreeImage_GetImageType(aSaveDIB),
                                                                    FreeImage_GetColorType(aSaveDIB),
                                                                    FreeImage_GetBPP(aSaveDIB));
    stImgPlaneSave.initWrapper(stImgFormatSave, FreeImage_GetBits(aSaveDIB),
                               FreeImage_GetWidth(aSaveDIB), FreeImage_GetHeight(aSaveDIB),
                               FreeImage_GetPitch(aSaveDIB));
    // FreeImage data should be bottom-up...
    stImgPlaneSave.setTopDown(false);

    // copy from local structure to the FreeImage structure
    size_t aRowInc = (( stImgPlaneSave.isTopDown() &&  stImgPlane.isTopDown()) ||
                      (!stImgPlaneSave.isTopDown() && !stImgPlane.isTopDown())) ? 1 : size_t(-1);
    size_t aRowTo = (aRowInc == 1) ? 0 : (stImgPlane.getSizeY() - 1);
    for(size_t aRowFrom = 0; aRowFrom < stImgPlane.getSizeY(); ++aRowFrom, aRowTo += aRowInc) {
        for(size_t aCol = 0; aCol < stImgPlane.getSizeX(); ++aCol) {
            stMemCpy(stImgPlaneSave.changeData(aRowTo, aCol), stImgPlane.getData(aRowFrom, aCol), stImgPlane.getSizePixelBytes());
        }
    }

    // now save the image file!
#if defined(_WIN32)
    if(!FreeImage_Save(aFIF, aSaveDIB, theFilePath.toUtfWide().toCString(), 0)) {
#else
    if(!FreeImage_Save(aFIF, aSaveDIB, theFilePath.toCString(), 0)) {
#endif
        setState("FreeImage library, image save failed");
        FreeImage_Unload(aSaveDIB);
        return false;
    }

    // free resources
    FreeImage_Unload(aSaveDIB);

    // set debug information
    StString aDummy, aFileName;
    StFileNode::getFolderAndFile(theFilePath, aDummy, aFileName);
    setState(StString("FreeImage library, saved image '") + aFileName + "' " + getDescription());

    return true;
}

bool StFreeImage::resize(size_t , size_t ) {
    return false;
}
Example #21
0
void Scenario::save( VariantMap& stream ) const
{
  stream[ "description" ] = Variant( getDescription() );
}
Example #22
0
int main(int argc, char *argv[])
{
    FILE *fd;
    int len,i;
    char *dsc;
    char bgr[3];
    short svalue;
    int   lvalue;
    unsigned char header[54],*ptr=&header[0];
    char * name = argv[2];
    short extendedThreads = FALSE;

    HANDLE * handles;
    HANDLE * handlesEx;
    struct THREAD_PARAMS * tParams;
    struct THREAD_PARAMS * tParamsEx;
    LPDWORD * lpThreadIds;
    LPDWORD * lpThreadIdsEx;
    DWORD dWait;

    short threadNum = 1;
    if(argc >= 2) threadNum = atoi(argv[1]);

    if(threadNum > 128)
    {
        printf("To much threads!");
        return -1;
    }else if(threadNum > 64)
    {
        extendedThreads = TRUE;
        handlesEx = (HANDLE*) malloc(sizeof(HANDLE) * (threadNum - 64));
        tParamsEx = (struct THREAD_PARAMS *) malloc(sizeof(struct THREAD_PARAMS) * (threadNum - 64));
        lpThreadIdsEx = (LPDWORD*) malloc(sizeof(LPDWORD) * (threadNum - 64));
    }

    handles = (HANDLE*) malloc(sizeof(HANDLE) * threadNum);
    tParams = (struct THREAD_PARAMS *) malloc(sizeof(struct THREAD_PARAMS) * threadNum);
    lpThreadIds = (LPDWORD*) malloc(sizeof(LPDWORD) * threadNum);
    mutex = CreateMutex(NULL, FALSE, NULL);
    if(mutex == NULL)
    {
        printf("could not create mutex.");
        return 1;
    }

    getDescription(NULL,&len);
    if(NULL==(dsc=(char*)malloc(sizeof(char)*len)))
    {
        perror("malloc");
        exit(1);
    }
    getDescription(dsc,&len);

    printf("Calculate %s %d\n",dsc,getId());
    fd=fopen(name,"wb+");
    if(NULL==fd)
    {
        perror("open"); exit(1);
    }

    svalue=0x4d42;
    memcpy(ptr,&svalue,2);//signatur
    ptr+=2;
    lvalue=XSIZE*YSIZE*3+54;
    memcpy(ptr,&lvalue,4); //filesize
    ptr+=4;
    lvalue=0;
    memcpy(ptr,&lvalue,4);//reserved
    ptr+=4;
    lvalue=54;
    memcpy(ptr,&lvalue,4);//image offset
    ptr+=4;
    lvalue=40;
    memcpy(ptr,&lvalue,4);//size of header follows
    ptr+=4;
    lvalue=XSIZE;
    memcpy(ptr,&lvalue,4);//with of image
    ptr+=4;
    lvalue=YSIZE;
    memcpy(ptr,&lvalue,4); //height of image
    ptr+=4;
    svalue=1;
    memcpy(ptr,&svalue,2); //number of planes
    ptr+=2;
    svalue=24;
    memcpy(ptr,&svalue,2); //number of pixel
    ptr+=2;
    lvalue=0; //compression
    memcpy(ptr,&lvalue,4); //compression
    ptr+=4;
    lvalue=XSIZE*YSIZE*3;
    memcpy(ptr,&lvalue,4); //size of image
    ptr+=4;
    lvalue=0;
    memcpy(ptr,&lvalue,4); //xres
    ptr+=4;
    lvalue=0;
    memcpy(ptr,&lvalue,4); //yres
    ptr+=4;
    lvalue=0;
    memcpy(ptr,&lvalue,4); //number of colortables
    ptr+=4;
    lvalue=0;
    memcpy(ptr,&lvalue,4); //number of important colors
    ptr+=4;

    len=fwrite(header,1,sizeof(header),fd); //write header

    if(-1==len || len!=sizeof(header))
    {
        perror("write");
        exit(2);
    }
#pragma message("!!!!       Implement Multithreading here    !!!!")

    for(i=0; i<threadNum; i++)
    {
        if(i < 64)
        {
            tParams[i].yMin = i * (floor(YSIZE/(float)threadNum));
            tParams[i].yMax = tParams[i].yMin + (floor(YSIZE/(float)threadNum));
            if(i == (threadNum -1))tParams[i].yMax = YSIZE;
            tParams[i].file = fd;
            handles[i] = createThread(NULL, 0, threadFunc, &(tParams[i]), 0, &(lpThreadIds[i]));
        }else{
            tParamsEx[i%64].yMin = (i%64) * (floor(YSIZE/(float)threadNum));
            tParamsEx[i%64].yMax = tParamsEx[i%64].yMin + (floor(YSIZE/(float)threadNum));
            if(i == (threadNum -1))tParamsEx[i%64].yMax = YSIZE;
            tParamsEx[i%64].file = fd;
            handlesEx[i%64] = createThread(NULL, 0, threadFunc, &(tParamsEx[i%64]), 0, &(lpThreadIdsEx[i%64]));
        }
    }
    dWait = WaitForMultipleObjects(threadNum, handles, TRUE, 10000); //INFINITE
    if(extendedThreads == TRUE)dWait = WaitForMultipleObjects(threadNum-64, handlesEx, TRUE, 10000);

    fclose(fd);

    return 0;
}
Example #23
0
bool InvoiceLine::operator==(const InvoiceLine &l)
{
    return (getId() == l.getId() && getQte() == l.getQte() &&
            getName() == l.getName() && getDescription() == l.getDescription());
}
GtkWidget * AP_UnixDialog_Annotation::_constructWindow ()
{
	GtkWidget * window;
	const XAP_StringSet * pSS = m_pApp->getStringSet();
	
	// load the dialog from the UI file
#if GTK_CHECK_VERSION(3,0,0)
	GtkBuilder* builder = newDialogBuilder("ap_UnixDialog_Annotation.ui");
#else
	GtkBuilder* builder = newDialogBuilder("ap_UnixDialog_Annotation-2.ui");
#endif
	
	// Update our member variables with the important widgets that 
	// might need to be queried or altered later
	window = GTK_WIDGET(gtk_builder_get_object(builder, "ap_UnixDialog_Annotation"));
	m_entryTitle = GTK_WIDGET(gtk_builder_get_object(builder, "enTitle"));
	m_entryAuthor = GTK_WIDGET(gtk_builder_get_object(builder, "enAuthor"));
	m_textDescription = GTK_WIDGET(gtk_builder_get_object(builder, "tvDescription"));
	
	// set the dialog title
	std::string s;
	pSS->getValueUTF8(AP_STRING_ID_DLG_Annotation_Title,s);
	abiDialogSetTitle(window, "%s", s.c_str());
	
	// localize the strings in our dialog, and set some userdata for some widgets
	localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbTitle")), pSS, AP_STRING_ID_DLG_Annotation_Title_LBL);
	localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbAuthor")), pSS, AP_STRING_ID_DLG_Annotation_Author_LBL);
	localizeLabel(GTK_WIDGET(gtk_builder_get_object(builder, "lbDescription")), pSS, AP_STRING_ID_DLG_Annotation_Description_LBL);
	
	// signals
	g_signal_connect(G_OBJECT(m_entryTitle), "focus-out-event", G_CALLBACK(s_focus_out), static_cast<gpointer>(this));
	g_signal_connect(G_OBJECT(m_entryAuthor), "focus-out-event", G_CALLBACK(s_focus_out), static_cast<gpointer>(this));
	
	// now set the text in all the fields
	std::string prop;
	
	#define SET_ENTRY_TXT(name) \
	prop = get##name () ;                      \
	if ( !prop.empty() ) {                          \
		gtk_entry_set_text (GTK_ENTRY(m_entry##name), prop.c_str() ) ; \
	}
	
	GtkWidget * wReplace = GTK_WIDGET(gtk_builder_get_object(builder, "btReplace"));
	pSS->getValueUTF8(AP_STRING_ID_DLG_Annotation_Replace_LBL,s);
	gtk_button_set_label(GTK_BUTTON(wReplace),s.c_str()); 
	GtkWidget * wOK = GTK_WIDGET(gtk_builder_get_object(builder, "btOK"));
	pSS->getValueUTF8(AP_STRING_ID_DLG_Annotation_OK_tooltip,s);
	gtk_widget_set_tooltip_text (wOK,s.c_str());
	pSS->getValueUTF8(AP_STRING_ID_DLG_Annotation_Replace_tooltip,s);
	gtk_widget_set_tooltip_text (wReplace,s.c_str());


	SET_ENTRY_TXT(Title)
	SET_ENTRY_TXT(Author)
	
	#undef SET_ENTRY_TXT
	
	prop = getDescription ();
	if ( !prop.empty() )
	{
		GtkTextBuffer * buffer = gtk_text_view_get_buffer ( GTK_TEXT_VIEW(m_textDescription) ) ;
		gtk_text_buffer_set_text ( buffer, prop.c_str(), -1 ) ;
	}	

	g_object_unref(G_OBJECT(builder));
	
	return window;
}
Example #25
0
int main(int argc, char *argv[])
{

    char **playersNameList;
    int totalPlayersNumber;
    int turn, i;
    char buffer[BUFF_SIZE];
    FILE *configFile;

    /* legge gli argomenti */
    char **name1, **name2;

    if (argc < 4) {
        fprintf(stderr,
                "ERROR: Wrong number of arguments. \n USAGE: %s\n",
                USAGE);
        exit(EXIT_FAILURE);
    }
    playersNameList = argv + 3;
    totalPlayersNumber = argc - 3;

    /* controlla se ci sono due giocatori con lo stesso nome */
    for (name1 = playersNameList; *name1; name1++)
        for (name2 = name1 + 1; *name2; name2++)
            if (strcmp(*name1, *name2) == 0) {
                fprintf(stderr, "ERROR: found two player with the"
                        "same name \"%s\"\n", *name1);
                exit(EXIT_FAILURE);
            }
    initIoInterface(argv[2]);
    /* crea e inizializza le strutture dati per i giocatori */
    initPlayersManager(totalPlayersNumber);
    for (; *playersNameList; playersNameList++)
        addPlayer(*playersNameList);

    initBoard();
    /*
     * legge il file di configurazione secondo il formato: 
     *     numero_casella:descrizione della prova\n
     * e aggiunge le descrizioni al tabellone
     */
    if ((configFile = fopen(argv[1], "r")) == NULL) {
        printErr("ERROR: error while opening configuration file\n");
        exit(EXIT_FAILURE);
    }
    while (fgets(buffer, BUFF_SIZE, configFile)) {
        char *description;
        int boxNumber;
        /* legge il numero di casella */
        if ((boxNumber = atoi(buffer)) <= 0) {
            printErr("ERROR:invalid box num(\"%s\") in"
                     " configuration file\n", buffer);
            exit(EXIT_FAILURE);
        }
        /* aggiunge una nuova casella con la relativa descrizione */
        if ((description = strchr(buffer, ':')) == NULL) {
            printErr("ERROR: missing ':' in configuration file\n");
            exit(EXIT_FAILURE);
        }
        addBox(boxNumber, description + 1);
    }
    if (getTotalBoxesNumber() == 0) {
        printErr("ERROR: invalid configuration file\n");
        exit(EXIT_FAILURE);
    }
    fclose(configFile);
    printBoard();
    showGame();
    /* avvia la simulazione del gioco */
    srand(time(NULL));
    for (turn = 0; !allPlayersDone(); turn++) {
        if (!nextStep())
            return EXIT_SUCCESS;
        printMessage("\n**************************************\n");
        printMessage("turno %d", turn + 1);
        printMessage("\n**************************************\n");
        showGame();
        /*
         * per ogni giocatore G che non ha terminato il gioco: 
         * 1. se G  e' fermo per un turno cambia il suo stato in
         *      modo che al turno successivo venga rimesso in gioco 
         * 2. altrimenti viene lanciato il dado, mosso il giocatore
         *              e visualizzata la sua prova 
         */
        while (nextPlayer()) {
            int state = getPlayerState();

            if (state == ACTIVE || state == TEST_PASSED
                || state == TO_BE_ACTIVATED) {
                if (state != ACTIVE)
                    setPlayerState(ACTIVE, 0);
                movePlayer((rand() % 6) + 1);
                if (getPlayerBox() > getTotalBoxesNumber())
                    setPlayerState(DONE, turn);
                else
                    printMessage("player %s: \"%s\"\n",
                                 getPlayerName(),
                                 getDescription(getPlayerBox()));
            } else if (state == OUT_OF_TURN)
                setPlayerState(TO_BE_ACTIVATED, 0);
        }
        showGame();
        /*
         * Legge e registra l'esito di tutte le prove sostenute nel
         * turno corrente dai giocatori 
         */
        for (i = getActivePlayersNumber(); i > 0; i--) {
            int playerNumber;
            bool result;

            do {
                result = askPlayerResult(&playerNumber);
                if (playerNumber > totalPlayersNumber)
                    printErr("WARNING: player number %d out of "
                             "bounds [1; %d]\n", playerNumber,
                             totalPlayersNumber);
                else {
                    setCurrentPlayer(playerNumber);
                    if (getPlayerState() != ACTIVE)
                        printErr("WARNING: player number %d not "
                                 "valid because player:"
                                 "\n\t-won"
                                 "\n\t-is out of turn"
                                 "\n\t-already passed the test\n",
                                 playerNumber);
                }
            }
            while (playerNumber > totalPlayersNumber
                   || getPlayerState() != ACTIVE);
            if (result)
                setPlayerState(TEST_PASSED, 0);
            else
                setPlayerState(OUT_OF_TURN, 0);
        }
    }
    printScore();
    closeIoInterface();

    return EXIT_SUCCESS;
}
Example #26
0
bool SFXProfile::isLooping() const
{
   return getDescription()->mIsLooping;
}
Example #27
0
/*------------------------------------------------------------------------------
 *  Log in to the IceCast server
 *----------------------------------------------------------------------------*/
bool
IceCast :: sendLogin ( void )                           throw ( Exception )
{
    Sink          * sink   = getSink();
    Source        * source = getSocket();
    const char    * str;
    char            resp[STRBUF_SIZE];
    unsigned int    len;

    if ( !source->isOpen() ) {
        return false;
    }
    if ( !sink->isOpen() ) {
        return false;
    }

    /* send the request, a string like:
     * "SOURCE <password> /<mountpoint>\n" */
    str = "SOURCE ";
    sink->write( str, strlen( str));
    str = getPassword();
    sink->write( str, strlen( str));
    str = " /";
    sink->write( str, strlen( str));
    str = getMountPoint();
    sink->write( str, strlen( str));

    /* send the x-audiocast headers */
    str = "\nx-audiocast-bitrate: ";
    sink->write( str, strlen( str));
    if ( snprintf( resp, STRBUF_SIZE, "%d", getBitRate()) == -1 ) {
        throw Exception( __FILE__, __LINE__, "snprintf overflow");
    }
    sink->write( resp, strlen( resp));

    str = "\nx-audiocast-public: ";
    sink->write( str, strlen( str));
    str = getIsPublic() ? "1" : "0";
    sink->write( str, strlen( str));

    if ( getName() ) {
        str = "\nx-audiocast-name: ";
        sink->write( str, strlen( str));
        str = getName();
        sink->write( str, strlen( str));
    }

    if ( getDescription() ) {
        str = "\nx-audiocast-description: ";
        sink->write( str, strlen( str));
        str = getDescription();
        sink->write( str, strlen( str));
    }

    if ( getUrl() ) {
        str = "\nx-audiocast-url: ";
        sink->write( str, strlen( str));
        str = getUrl();
        sink->write( str, strlen( str));
    }

    if ( getGenre() ) {
        str = "\nx-audiocast-genre: ";
        sink->write( str, strlen( str));
        str = getGenre();
        sink->write( str, strlen( str));
    }

    if ( getRemoteDumpFile() ) {
        str = "\nx-audiocast-dumpfile: ";
        sink->write( str, strlen( str));
        str = getRemoteDumpFile();
        sink->write( str, strlen( str));
    }

    str = "\n\n";
    sink->write( str, strlen( str));
    sink->flush();

    /* read the anticipated response: "OK" */
    len = source->read( resp, STRBUF_SIZE);
    if ( len < 2 || resp[0] != 'O' || resp[1] != 'K' ) {
        return false;
    }

    /* suck anything that the other side has to say */
    while ( source->canRead( 0, 0) && 
           (len = source->read( resp, STRBUF_SIZE)) ) {
        ;
    }


    return true;
}
  virtual bool adaptAndPlan(const PlannerFn &planner,
                            const planning_scene::PlanningSceneConstPtr& planning_scene,
                            const planning_interface::MotionPlanRequest &req,
                            planning_interface::MotionPlanResponse &res,
                            std::vector<std::size_t> &added_path_index) const
  {
    ROS_DEBUG("Running '%s'", getDescription().c_str());

    // get the specified start state
    robot_state::RobotState start_state = planning_scene->getCurrentState();
    robot_state::robotStateMsgToRobotState(planning_scene->getTransforms(), req.start_state, start_state);

    // if the start state is otherwise valid but does not meet path constraints
    if (planning_scene->isStateValid(start_state, req.group_name) &&
        !planning_scene->isStateValid(start_state, req.path_constraints, req.group_name))
    {
      ROS_INFO("Path constraints not satisfied for start state...");
      planning_scene->isStateValid(start_state, req.path_constraints, req.group_name, true);
      ROS_INFO("Planning to path constraints...");

      planning_interface::MotionPlanRequest req2 = req;
      req2.goal_constraints.resize(1);
      req2.goal_constraints[0] = req.path_constraints;
      req2.path_constraints = moveit_msgs::Constraints();
      planning_interface::MotionPlanResponse res2;
      // we call the planner for this additional request, but we do not want to include potential 
      // index information from that call
      std::vector<std::size_t> added_path_index_temp;
      added_path_index_temp.swap(added_path_index);
      bool solved1 = planner(planning_scene, req2, res2);
      added_path_index_temp.swap(added_path_index);
      
      if (solved1)
      {
        planning_interface::MotionPlanRequest req3 = req;
        ROS_INFO("Planned to path constraints. Resuming original planning request.");

        // extract the last state of the computed motion plan and set it as the new start state
        robot_state::robotStateToRobotStateMsg(res2.trajectory_->getLastWayPoint(), req3.start_state);
        bool solved2 = planner(planning_scene, req3, res);
        res.planning_time_ += res2.planning_time_;

        if (solved2)
        {
          // since we add a prefix, we need to correct any existing index positions
          for (std::size_t i = 0 ; i < added_path_index.size() ; ++i)
            added_path_index[i] += res2.trajectory_->getWayPointCount();
          
          // we mark the fact we insert a prefix path (we specify the index position we just added)
          for (std::size_t i = 0 ; i < res2.trajectory_->getWayPointCount() ; ++i)
            added_path_index.push_back(i);
          
          // we need to append the solution paths.
          res2.trajectory_->append(*res.trajectory_, 0.0);
          res2.trajectory_->swap(*res.trajectory_);
          return true;
        }
        else
          return false;
      }
      else
      {
        ROS_WARN("Unable to plan to path constraints. Running usual motion plan.");
        bool result = planner(planning_scene, req, res);
        res.planning_time_ += res2.planning_time_;
        return result;
      }
    }
    else
    {
      ROS_DEBUG("Path constraints are OK. Running usual motion plan.");
      return planner(planning_scene, req, res);
    }
  }
Example #29
0
int64_t SocketConnection::readSync( void* buffer, const uint64_t bytes,
                                    const bool block )
{
    LB_TS_THREAD( _recvThread );

    if( _readFD == INVALID_SOCKET )
    {
        LBERROR << "Invalid read handle" << std::endl;
        return READ_ERROR;
    }

    if( _overlappedDone > 0 )
        return _overlappedDone;

    DWORD got   = 0;
    DWORD flags = 0;
    DWORD startTime = 0;

    while( true )
    {
        if( WSAGetOverlappedResult( _readFD, &_overlappedRead, &got, block,
                                    &flags ))
            return got;

        const int err = WSAGetLastError();
        if( err == ERROR_SUCCESS || got > 0 )
        {
            LBWARN << "Got " << lunchbox::sysError << " with " << got
                   << " bytes on " << getDescription() << std::endl;
            return got;
        }

        if( startTime == 0 )
            startTime = GetTickCount();

        switch( err )
        {
            case WSA_IO_INCOMPLETE:
                return READ_TIMEOUT;

            case WSASYSCALLFAILURE:  // happens sometimes!?
            case WSA_IO_PENDING:
                if( GetTickCount() - startTime > CO_RECV_TIMEOUT ) // timeout
                {
                    LBWARN << "Error timeout " << std::endl;
                    return READ_ERROR;
                }

                LBWARN << "WSAGetOverlappedResult error loop"
                       << std::endl;
                // one millisecond to recover
                boost::this_thread::sleep( bp::milliseconds( 1 ));
                break;

            default:
                LBWARN << "Got " << lunchbox::sysError
                       << ", closing connection" << std::endl;
                close();
                return READ_ERROR;
        }
    }
}
Example #30
0
AREXPORT void ArArg::log(void) const
{
    std::list<ArArgumentBuilder *>::const_iterator it;
    const std::list<ArArgumentBuilder *> *argList;

    switch (getType())
    {
    case ArArg::INVALID:
        ArLog::log(ArLog::Terse,
                   "\tType: %10s.  This argument was not created properly.",
                   "invalid");
    case ArArg::INT:
        ArLog::log(ArLog::Terse, "\tType: %10s name: %12s value: %d", "int",
                   getName(), getInt());
        if (strlen(getDescription()) != 0)
            ArLog::log(ArLog::Terse, "\t\tDescription: %s",
                       getDescription());
        break;
    case ArArg::DOUBLE:
        ArLog::log(ArLog::Terse, "\tType: %10s name: %12s value: %f", "double",
                   getName(), getDouble());
        if (strlen(getDescription()) != 0)
            ArLog::log(ArLog::Terse, "\t\tDescription: %s",
                       getDescription());
        break;
    case ArArg::STRING:
        ArLog::log(ArLog::Terse, "\tType: %10s name: %12s value: %s", "string",
                   getName(), getString());
        if (strlen(getDescription()) != 0)
            ArLog::log(ArLog::Terse, "\t\tDescription: %s",
                       getDescription());
        break;
    case ArArg::BOOL:
        ArLog::log(ArLog::Terse, "\tType: %10s name: %12s value: %d", "bool",
                   getName(), getBool());
        if (strlen(getDescription()) != 0)
            ArLog::log(ArLog::Terse, "\t\tDescription: %s",
                       getDescription());
        break;
    case ArArg::POSE:
        ArLog::log(ArLog::Terse, "\tType: %10s name: %12s value: (%.1f %.1f %.1f)",
                   "pose", getName(), getPose().getX(), getPose().getY(),
                   getPose().getTh());
        if (strlen(getDescription()) != 0)
            ArLog::log(ArLog::Terse, "\t\tDescription: %s",
                       getDescription());
        break;
    case ArArg::FUNCTOR:
        ArLog::log(ArLog::Terse, "\tType: %10s name: %12s",
                   "functor", getName(), getPose().getX(), getPose().getY(),
                   getPose().getTh());
        if (strlen(getDescription()) != 0)
            ArLog::log(ArLog::Terse, "\t\tDescription: %s",
                       getDescription());
        ArLog::log(ArLog::Terse, "\t\tValues:");
        argList = myGetFunctor->invokeR();
        for (it = argList->begin(); it != argList->end(); it++)
            ArLog::log(ArLog::Terse, "\t\t\t%s", (*it)->getFullString());
        break;
    case ArArg::DESCRIPTION_HOLDER:
        ArLog::log(ArLog::Terse, "\tType: %20s Description: %s",
                   "description_holder", getDescription());

    default:
        ArLog::log(ArLog::Terse,
                   "\tType: %10s.  This type doesn't have a case in ArArg::print.",
                   "unknown");
        break;
    }

    if (myConfigPrioritySet)
        ArLog::log(ArLog::Terse, "\t\tPriority: %s",
                   ArPriority::getPriorityName(myConfigPriority));
}