Beispiel #1
0
void ExternalProcess::SetEnvironment( const StringList& environment )
{
   Array<const char16_type*> vars;
   for ( StringList::const_iterator i = environment.Begin(); i != environment.End(); ++i )
      vars.Add( i->c_str() );
   if ( (*API->ExternalProcess->SetExternalProcessEnvironment)( handle, vars.Begin(), vars.Length() ) == api_false )
      throw APIFunctionError( "SetExternalProcessEnvironment" );
}
Beispiel #2
0
void ExternalProcess::Start( const String& program, const StringList& arguments )
{
   Array<const char16_type*> argv;
   for ( StringList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
      argv.Add( i->c_str() );
   if ( (*API->ExternalProcess->StartExternalProcess)( handle, program.c_str(), argv.Begin(), argv.Length() ) == api_false )
      throw APIFunctionError( "StartExternalProcess" );
}
Beispiel #3
0
void SWOptionFilter::setOptionValue(const char *ival) {
	for (StringList::const_iterator loop = optValues->begin(); loop != optValues->end(); loop++) {
		if (!stricmp(loop->c_str(), ival)) {
			optionValue = *loop;
			option = (!strnicmp(ival, "On", 2));	// convenience for boolean filters
			break;
		}
	}
}
Beispiel #4
0
int ExternalProcess::ExecuteProgram( const String& program, const StringList& arguments )
{
   Array<const char16_type*> argv;
   for ( StringList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
      argv.Add( i->c_str() );
   int retVal = (*API->ExternalProcess->ExecuteProgram)( program.c_str(), argv.Begin(), argv.Length() );
   if ( retVal < -1 )
      ExternalProcessPrivate::Throw( ExternalProcessContext::FailedToStart );
   return retVal;
}
Beispiel #5
0
ExternalProcess::pid_type ExternalProcess::StartProgram( const String& program, const StringList& arguments, const String& workingDirectory )
{
   Array<const char16_type*> argv;
   for ( StringList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
      argv.Add( i->c_str() );
   uint64 pid = 0;
   api_bool ok = (*API->ExternalProcess->StartProgram)( program.c_str(), argv.Begin(), argv.Length(), workingDirectory.c_str(), &pid );
   if ( ok == api_false || pid == 0 )
      ExternalProcessPrivate::Throw( ExternalProcessContext::FailedToStart );
   return pid_type( pid );
}
Beispiel #6
0
        /* {{{ MySQL_ArtResultSet::MySQL_ArtResultSet() -I- */
        MySQL_ArtResultSet::MySQL_ArtResultSet(const StringList& fn, rset_t* const rs, boost::shared_ptr< MySQL_DebugLogger > & l)
            : num_fields(static_cast<int>(fn.size())), rset(rs), current_record(rset->begin()),
              started(false), field_index_to_name_map(new sql::SQLString[num_fields]),
              num_rows(rset->size()), row_position(0), is_closed(false), logger(l)
        {
            CPP_ENTER("MySQL_ArtResultSet::MySQL_ArtResultSet");
            CPP_INFO_FMT("metadata.size=%d resultset.size=%d", fn.size(), rset->size());

            //	field_index_to_name_map = new sql::SQLString[num_fields];

            unsigned int idx = 0;
            for (StringList::const_iterator it = fn.begin(), e = fn.end(); it != e; ++it, ++idx) {
                boost::scoped_array< char > upstring(sql::mysql::util::utf8_strup(it->c_str(), 0));
                field_name_to_index_map[sql::SQLString(upstring.get())] = idx;
                field_index_to_name_map[idx] = upstring.get();
            }

            meta.reset(new MySQL_ArtResultSetMetaData(this, logger));
        }
void ClassMenuItemAdder::generateMenu(IMenu& createItem, const StringList& comboStrings)
{
	StringList::const_iterator it;
	int index = 0;
	for (it = comboStrings.begin(); it != comboStrings.end(); ++it) {
		StringList path;
		splitStringList(&path, it->c_str(), '\\');
		int level = 0;
		IMenu* item = &createItem;

		for(int level = 0; level < int(path.size()); ++level){
			const char* leaf = path[level].c_str();
			if(level == path.size() - 1){
				addAction(*item, leaf, index++);
			}
			else{
				if (property_tree::IMenu* menu = item->findMenu(leaf))
					item = menu;
				else
					item = addMenu(*item, leaf);
			}
		}
	}
}
	//------------------------------
	bool LibraryControllersLoader::begin__input____InputLocal( const input____InputLocal__AttributeData& attributeData )
	{
		// we ignore inputs that don't have semantics or source
		if ( !attributeData.semantic || !attributeData.source  )
		{
			return true;
		}

		ControllerInputSemantics semantic = getControllerInputSemanticsBySemanticStr( attributeData.semantic );
		if ( semantic == SEMANTIC_UNKNOWN )
		{
			return true;
		}

		switch ( mCurrentControllerType )
		{
		case SKIN_CONTROLLER:
			{
				switch ( semantic )
				{
				case SEMANTIC_JOINT:
					{
						if ( !mCurrentSkinControllerData )
						{
							break;
						}

						String sourceId = getIdFromURIFragmentType(attributeData.source);

						const StringList* nodeSidsOrIds = 0;
						bool isIdArray = false;
						StringListMap::const_iterator itSid = mJointSidsMap.find(sourceId);
						// check if the node sid array could be found
						if ( itSid != mJointSidsMap.end() )
						{
							nodeSidsOrIds = &itSid->second;
							isIdArray = false;
						}
						else
						{
							// check if it is an id_array
							StringListMap::const_iterator itId = mJointIdsMap.find(sourceId);
							if ( itId != mJointIdsMap.end() )
							{
								nodeSidsOrIds = &itId->second;
								isIdArray = true;
							}
							else
							{
								if ( !handleFWLError ( SaxFWLError::ERROR_SOURCE_NOT_FOUND, "Source with id \"" + sourceId + "\" in skin controller with  id \"" + mOriginalId + "\" used in input with semantic SEMANTIC_JOINT could not be found!" ))
									return false;
								break;
							}
						}

						const COLLADAFW::UniqueId& controllerUniqueId = mCurrentSkinControllerData->getUniqueId();
						addSkinDataJointSidsPair( controllerUniqueId, *nodeSidsOrIds, isIdArray);

						// try to write the SkinController here
						if ( ((getObjectFlags() & Loader::CONTROLLER_FLAG) != 0) && (mCurrentControllerSourceUniqueId.isValid()) )
						{
							Loader::InstanceControllerDataList& instanceControllerDataList = getInstanceControllerDataListByControllerUniqueId(controllerUniqueId);
							Loader::InstanceControllerDataList::iterator listIt = instanceControllerDataList.begin();

							while ( listIt != instanceControllerDataList.end() )
							{
								const Loader::InstanceControllerData& instanceControllerData = *listIt;
								bool success = getFileLoader()->createAndWriteSkinController( instanceControllerData, 
																					   		  controllerUniqueId, 
									                                                          mCurrentControllerSourceUniqueId,
									                                                          *nodeSidsOrIds,
																							  isIdArray);
								//on success we need to remove this controller instance
								if ( success )
								{
									listIt = instanceControllerDataList.erase( listIt );
								}
								else
								{
									listIt++;
								}
							}
						}
						mCurrentSkinControllerData->setJointsCount(nodeSidsOrIds->size());
					}
					break;
				case SEMANTIC_INV_BIND_MATRIX:
					{
						if ( !mCurrentSkinControllerData)
						{
							break;
						}

						String sourceId = getIdFromURIFragmentType(attributeData.source);
						SourceBase* sourceBase = getSourceById ( sourceId );

						if ( !sourceBase || (sourceBase->getDataType() != SourceBase::DATA_TYPE_REAL) )
						{
                            handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "SourceBase of skin controller with semantic SEMANTIC_INV_BIND_MATRIX not valid!" );
							break;
						}

						if ( sourceBase->getStride() != 16 )
						{
                            handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "Stride of sourceBase of skin controller with semantic SEMANTIC_INV_BIND_MATRIX not valid!" );
							break;
						}

						const RealSource *inverseBindMatricesSource = (const RealSource *)sourceBase;
						const RealArrayElement& inverseBindMatricesElement = inverseBindMatricesSource->getArrayElement();

						const RealArray& inverseBindMatricesArray = inverseBindMatricesElement.getValues();

						size_t matrixElementsCount = inverseBindMatricesArray.getCount();

						size_t matrixCount = matrixElementsCount / 16;


						COLLADAFW::Matrix4Array& inverseBindMatrices = mCurrentSkinControllerData->getInverseBindMatrices();
						inverseBindMatrices.allocMemory( matrixCount );
						inverseBindMatrices.setCount( matrixCount );

						size_t index = 0;
						for ( size_t i = 0; i < matrixCount; ++i)
						{
							// fill the matrix
							COLLADABU::Math::Matrix4 matrix;
							for ( size_t j = 0; j < 16; ++j,++index)
							{
								matrix.setElement( j, inverseBindMatricesArray[index]);
							}
							inverseBindMatrices[i] = matrix;
						}
					}
					break;
				}
			}
			break;
		case MORPH_CONTROLLER:
			{
				switch ( semantic )
				{
				case SEMANTIC_MORPH_TARGET:
					{
						if ( !mCurrentMorphController )
						{
							break;
						}

						String sourceId = getIdFromURIFragmentType(attributeData.source);
						StringListMap::const_iterator it = mJointIdsMap.find(sourceId);

						// check if the node sid array could be found
						if ( it == mJointIdsMap.end() )
						{
							if ( !handleFWLError ( SaxFWLError::ERROR_SOURCE_NOT_FOUND, "Source with id \"" + sourceId + "\" in morph controller with  id \"" + mOriginalId + "\" used in input with semantic SEMANTIC_MORPH_TARGET could not be found!" ))
								return false;
							break;
						}

						const StringList& meshIds = it->second;
						size_t meshIdCount = meshIds.size();

						COLLADAFW::UniqueIdArray& morphTargets = mCurrentMorphController->getMorphTargets();
						morphTargets.allocMemory(meshIdCount);
						morphTargets.setCount(meshIdCount);
						StringList::const_iterator itTarget = meshIds.begin();
						for ( size_t i = 0 ; itTarget != meshIds.end(); ++itTarget, ++i)
						{
							morphTargets[i] = createUniqueIdFromId( itTarget->c_str(), COLLADAFW::Geometry::ID());
						}

					}
					break;
				case SEMANTIC_MORPH_WEIGHT:
					{
						if ( !mCurrentMorphController)
						{
							break;
						}

						String sourceId = getIdFromURIFragmentType(attributeData.source);
						SourceBase* sourceBase = getSourceById( sourceId );

						if ( !sourceBase || (sourceBase->getDataType() != SourceBase::DATA_TYPE_REAL) )
						{
                            handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "SourceBase of skin controller with semantic SEMANTIC_MORPH_WEIGHT not valid!" );
							break;
						}


						unsigned long long stride = sourceBase->getStride();
						if( stride == 0 )
						{
							handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "Stride of sourceBase of skin controller with semantic SEMANTIC_MORPH_WEIGHT not found! Assuming stride 1!" );
							stride = 1;
						}
						if ( stride != 1 )
						{
                            handleFWLError ( SaxFWLError::ERROR_DATA_NOT_VALID, "Stride of sourceBase of skin controller with semantic SEMANTIC_MORPH_WEIGHT not valid!" );
							break;
						}
						const RealSource *weightSource = (const RealSource *)sourceBase;
						COLLADAFW::FloatOrDoubleArray& morphWeights = mCurrentMorphController->getMorphWeights();
						addToSidTree( sourceId.c_str(), 0, &morphWeights );
						moveUpInSidTree();

						setRealValues( morphWeights, weightSource );
					}
					break;
				}
			}
			break;
		}

		return true;
	}
Beispiel #9
0
char ThMLHeadings::processText(SWBuf &text, const SWKey *key, const SWModule *module) {
	SWBuf token;
	bool intoken    = false;
	bool isheader   = false;
	bool hide       = false;
	bool preverse   = false;
	bool withinDiv  = false;
	SWBuf header;
	int headerNum   = 0;
	int pvHeaderNum = 0;
	char buf[254];
	XMLTag startTag;

	SWBuf orig = text;
	const char *from = orig.c_str();
	
	XMLTag tag;

	for (text = ""; *from; ++from) {
		if (*from == '<') {
			intoken = true;
			token = "";
			
			continue;
		}
		if (*from == '>') {	// process tokens
			intoken = false;

			if (!strnicmp(token.c_str(), "div", 3) || !strnicmp(token.c_str(), "/div", 4)) {
				withinDiv =  (!strnicmp(token.c_str(), "div", 3));
				tag = token;
				if (hide && tag.isEndTag()) {
					if (module->isProcessEntryAttributes() && (option || (!preverse))) {
						if (preverse) {
							sprintf(buf, "%i", pvHeaderNum++);
							module->getEntryAttributes()["Heading"]["Preverse"][buf] = header;
						}
						else {
							sprintf(buf, "%i", headerNum++);
							module->getEntryAttributes()["Heading"]["Interverse"][buf] = header;
							if (option) {	// we want the tag in the text
								text.append(header);
							}
						}
						
						StringList attributes = startTag.getAttributeNames();
						for (StringList::const_iterator it = attributes.begin(); it != attributes.end(); it++) {
							module->getEntryAttributes()["Heading"][buf][it->c_str()] = startTag.getAttribute(it->c_str());
						}
					}
					
					hide = false;
					if (!option || preverse) {	// we don't want the tag in the text anymore
						preverse = false;
						continue;
					}
					preverse = false;
				}
				if (tag.getAttribute("class") && ((!stricmp(tag.getAttribute("class"), "sechead"))
										 ||  (!stricmp(tag.getAttribute("class"), "title")))) {

					isheader = true;
					
					if (!tag.isEndTag()) { //start tag
						if (!tag.isEmpty()) {
							startTag = tag;
					
/* how do we tell a ThML preverse title from one that should be in the text?  probably if any text is before the title...  just assuming all are preverse for now
					}
					if (tag.getAttribute("subtype") && !stricmp(tag.getAttribute("subtype"), "x-preverse")) {
*/
						hide = true;
						preverse = true;
						header = "";
						continue;
						}	// move back up under startTag = tag
					}
/* this is where non-preverse will go eventually
					if (!tag.isEndTag()) { //start tag
						hide = true;
						header = "";
						if (option) {	// we want the tag in the text
							text.append('<');
							text.append(token);
							text.append('>');
						}
						continue;
					}
*/
				}
				else
					isheader = false;
			}

			if (withinDiv && isheader) {
				header.append('<');
				header.append(token);
				header.append('>');
			} else {
				// if not a heading token, keep token in text
				if (!hide) {
					text.append('<');
					text.append(token);
					text.append('>');
				}
			}
			continue;
		}
		if (intoken) { //copy token
			token.append(*from);
		}
		else if (!hide) { //copy text which is not inside a token
			text.append(*from);
		}
		else header.append(*from);
	}
	return 0;
}
Beispiel #10
0
Plugin::List Plugin::scan( TPContext * context , const String & prefix , const StringList & symbols )
{
	Plugin::List result;

    if ( ! g_module_supported() )
    {
        tpwarn( "PLUGINS ARE NOT SUPPORTED ON THIS PLATFORM" );

        return result;
    }

    const gchar * plugins_path = context->get( TP_PLUGINS_PATH );

    if ( ! plugins_path )
    {
        tpwarn( "PLUGINS PATH IS NOT SET" );

        return result;
    }

    if ( ! g_file_test( plugins_path , G_FILE_TEST_IS_DIR ) )
    {
    	return result;
    }

    GError * error = 0;

    GDir * dir = g_dir_open( plugins_path , 0 , & error );

    if ( ! dir )
    {
        tpwarn( "FAILED TO OPEN PLUGINS PATH '%s' : %s" , plugins_path , error->message );

        g_clear_error( & error );

        return result;
    }

    for ( const gchar * name = g_dir_read_name( dir ); name ; name = g_dir_read_name( dir ) )
    {
        if ( g_str_has_prefix( name , prefix.c_str() ) )
        {
            if ( ! g_str_has_suffix( name , ".config" ) )
            {
                gchar * file_name = g_build_filename( plugins_path , name , NULL );

                tplog( "FOUND PLUGIN %s" , file_name );

                GModule * module = g_module_open( file_name , G_MODULE_BIND_LOCAL );

                if ( 0 == module )
                {
                	tpwarn( "  FAILED TO OPEN : %s" , g_module_error() );
                }
                else
                {
                	tplog2( "  LOADED" );

                	StringList all_symbols( symbols );

                	all_symbols.push_front( TP_PLUGIN_SHUTDOWN );
                	all_symbols.push_front( TP_PLUGIN_INITIALIZE );

                	GPointerMap symbols_found;

                	for ( StringList::const_iterator it = all_symbols.begin(); it != all_symbols.end(); ++it )
                	{
                		const char * symbol_name = it->c_str();

                		if ( gpointer symbol = get_symbol( module , symbol_name ) )
                		{
                    		tplog2( "  FOUND SYMBOL '%s'" , symbol_name );
                    		symbols_found[ symbol_name ] = symbol;
                		}
                		else
                		{
                			break;
                		}
                	}

                	if ( symbols_found.size() != all_symbols.size() )
                	{
                		g_module_close( module );
                	}
                	else
                	{
                		result.push_back( new Plugin( module , symbols_found ) );
                	}
                }

                g_free( file_name );
            }
        }
    }

    g_dir_close( dir );

    return result;
}
Beispiel #11
0
bool OSISHeadings::handleToken(SWBuf &buf, const char *token, BasicFilterUserData *userData) {

	MyUserData *u = (MyUserData *)userData;
	XMLTag tag(token);
	SWBuf name = tag.getName();

	// we only care about titles and divs or if we're already in a heading
	//
	// are we currently in a heading?
	if (u->currentHeadingName.size()) {
		u->heading.append(u->lastTextNode);
		if (name == u->currentHeadingName) {
			if (tag.isEndTag(u->sID)) {
				if (!u->depth-- || u->sID) {
					// see comment below about preverse div changed and needing to preserve the <title> container tag for old school pre-verse titles
					// we've just finished a heading.  It's all stored up in u->heading
					bool canonical = (SWBuf("true") == u->currentHeadingTag.getAttribute("canonical"));
					bool preverse = (SWBuf("x-preverse") == u->currentHeadingTag.getAttribute("subType") || SWBuf("x-preverse") == u->currentHeadingTag.getAttribute("subtype"));

					// do we want to put anything in EntryAttributes?
					if (u->module->isProcessEntryAttributes() && (option || canonical || !preverse)) {
						SWBuf buf; buf.appendFormatted("%i", u->headerNum++);
						// leave the actual <title...> wrapper in if we're part of an old school preverse title
						// because now frontend have to deal with preverse as a div which may or may not include <title> elements
						// and they can't simply wrap all preverse material in <h1>, like they probably did previously
						SWBuf heading;
						if (u->currentHeadingName == "title") {
							XMLTag wrapper = u->currentHeadingTag;
							if (SWBuf("x-preverse") == wrapper.getAttribute("subType")) wrapper.setAttribute("subType", 0);
							else if (SWBuf("x-preverse") == wrapper.getAttribute("subtype")) wrapper.setAttribute("subtype", 0);
							heading = wrapper;
							heading += u->heading;
							heading += tag;
						}
						else heading = u->heading;
						u->module->getEntryAttributes()["Heading"][(preverse)?"Preverse":"Interverse"][buf] = heading;

						StringList attributes = u->currentHeadingTag.getAttributeNames();
						for (StringList::const_iterator it = attributes.begin(); it != attributes.end(); it++) {
							u->module->getEntryAttributes()["Heading"][buf][it->c_str()] = u->currentHeadingTag.getAttribute(it->c_str());
						}
					}

					// do we want the heading in the body?
					if (!preverse && (option || canonical)) {
						buf.append(u->currentHeadingTag);
						buf.append(u->heading);
						buf.append(tag);
					}
					u->suspendTextPassThru = false;
					u->clear();
				}
			}
			else u->depth++;
		}
		u->heading.append(tag);
		return true;
	}

	// are we a title or a preverse div?
	else if (   name == "title"
		|| (name == "div"
			&& ( SWBuf("x-preverse") == tag.getAttribute("subType")
			  || SWBuf("x-preverse") == tag.getAttribute("subtype")))) {

		u->currentHeadingName = name;
		u->currentHeadingTag = tag;
		u->heading = "";
		u->sID = u->currentHeadingTag.getAttribute("sID");
		u->depth = 0;
		u->suspendTextPassThru = true;

		return true;
	}

	return false;
}
STDMETHODIMP CShooterContextMenuExt::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo )
{
	// If lpVerb really points to a string, ignore this function call and bail out.
	if ( 0 != HIWORD( pCmdInfo->lpVerb ) )
		return E_INVALIDARG;

	// Get the command index - the only valid one is 0.
	switch ( LOWORD( pCmdInfo->lpVerb) )
	{
	case 0:
	case 1:
		{
			TCHAR szShooterDir[MAX_PATH];
			TCHAR szShooterDldrPath[MAX_PATH];

			//Build the ShooterDownloader's file path from this module's path.
			//Limitation: ShooterDownloader must locate in the same dir as this module.
			HINSTANCE hModule = _AtlBaseModule.GetModuleInstance();
			GetModuleFileName((HMODULE) hModule, szShooterDir, sizeof(szShooterDir));
			TCHAR* pLastSlash = _tcsrchr(szShooterDir, _T('\\'));
			*(pLastSlash + 1) = _T('\0');
			_tcscpy_s(szShooterDldrPath, szShooterDir);
			_tcscat_s(szShooterDldrPath, SHOOTER_DLDR_FILE_NAME);

			TCHAR szTempDir[MAX_PATH], szTempFilePath[MAX_PATH];
			// Get the temp path.
			DWORD dwRetVal = GetTempPath(MAX_PATH,     // length of the buffer
				szTempDir); // buffer for path 
			if (dwRetVal > MAX_PATH || (dwRetVal == 0))
			{
				return E_FAIL;
			}

			// Create a temporary file. 
			UINT uRetVal = GetTempFileName(szTempDir, // directory for tmp files
				TEXT("SDL"),  // temp file name prefix 
				0,            // create unique name 
				szTempFilePath);  // buffer for name 
			if (uRetVal == 0)
			{
				return E_FAIL;
			}

			//Write file list to a temp file.
			FILE* fp; 
			errno_t ret = _tfopen_s(&fp, szTempFilePath, _T("w, ccs=UTF-8"));
			if(ret != 0)
			{
				return E_FAIL;
			}
			
			StringList::const_iterator itor;
			for(itor = m_fileList.begin(); itor != m_fileList.end(); itor++)
			{
				_ftprintf_s(fp, _T("%s\n"), itor->c_str());
			}
			fclose(fp);

			//Call ShooterDownloader and pass it the file list.
			const static int PARAM_SIZE = 512;
			TCHAR param[PARAM_SIZE];
			if(LOWORD( pCmdInfo->lpVerb) == 0)
			{
				//download subtitle
				_stprintf_s(param, PARAM_SIZE, _T("-lst=\"%s\" /r"), szTempFilePath);
			}
			else
			{
				//convert subtitle
				_stprintf_s(param, PARAM_SIZE, _T("-lst=\"%s\" /r /c"), szTempFilePath);
			}

			ShellExecute(NULL, _T("Open"), szShooterDldrPath, param, NULL, SW_SHOWNORMAL);

			return S_OK;
		}
		break;

	default:
		return E_INVALIDARG;
		break;
	}
}
Beispiel #13
0
    virtual void Execute(const std::string& sExecute, const StringList& rlsParams)
    {
      STAFF_ASSERT(m_pProvider != NULL && m_pProvider->m_pImpl->m_pConn != NULL, "Not Initialized");

      Reset();

      std::string sExecuteParams = sExecute;
      int nIndex = 1;
      std::string sIndex;
      unsigned nCount = 0;
      std::string::size_type nPos = 0;
      while ((nPos = sExecuteParams.find("?", nPos)) != std::string::npos)
      {
        ToString(nIndex, sIndex);
        sExecuteParams.replace(nPos, 1, "$" + sIndex);
        nPos += sIndex.size() + 1;
        ++nCount;
        ++nIndex;
      }

      STAFF_ASSERT(nCount == rlsParams.size(), "Params count mismatch");

      int* panParamLengths = new int[nCount];
      int* panParamFormats = new int[nCount];
      char** paszParamValues = new char*[nCount];

      try
      {
        unsigned nPos = 0;
        for (StringList::const_iterator itParam = rlsParams.begin();
             itParam != rlsParams.end(); ++itParam, ++nPos)
        {
          panParamFormats[nPos] = 0;
          if (*itParam == STAFF_DAS_NULL_VALUE)
          {
            panParamLengths[nPos] = 0;
            paszParamValues[nPos] = NULL;
          }
          else
          {
            panParamLengths[nPos] = itParam->size();
            paszParamValues[nPos] = const_cast<char*>(itParam->c_str());
          }
        }

        m_pResult = PQexecParams(m_pProvider->m_pImpl->m_pConn,
          sExecuteParams.c_str(), nCount, NULL, paszParamValues, panParamLengths, panParamFormats, 0);

        delete[] paszParamValues;
        delete[] panParamFormats;
        delete[] panParamLengths;
      }
      catch(...)
      {
        delete[] paszParamValues;
        delete[] panParamFormats;
        delete[] panParamLengths;
        throw;
      }

      ExecStatusType tQueryStatus = PQresultStatus(m_pResult);
      if (tQueryStatus != PGRES_COMMAND_OK)
      {
        STAFF_ASSERT(tQueryStatus == PGRES_TUPLES_OK, "error executing query #"
                     + ToString(tQueryStatus) + ": \n"
                     + std::string(PQerrorMessage(m_pProvider->m_pImpl->m_pConn))
                     + "\nQuery was:\n----------\n" + sExecute + "\n----------\n");

        m_nRowsCount = static_cast<unsigned>(PQntuples(m_pResult));
        m_nFieldsCount = static_cast<unsigned>(PQnfields(m_pResult));
      }
    }
Beispiel #14
0
bool ListWidget::handleKeyDown(Common::KeyState state) {
	bool handled = true;
	bool dirty = false;
	int oldSelectedItem = _selectedItem;

	if (!_editMode && isprint((char)state.ascii)) {
		// Quick selection mode: Go to first list item starting with this key
		// (or a substring accumulated from the last couple key presses).
		// Only works in a useful fashion if the list entries are sorted.
		uint32 time = getMillis();
		if (_quickSelectTime < time) {
			_quickSelectStr = (char)state.ascii;
		} else {
			_quickSelectStr += (char)state.ascii;
		}
		_quickSelectTime = time + 300;	// TODO: Turn this into a proper constant (kQuickSelectDelay ?)

		if (_quickSelect) {
			// FIXME: This is bad slow code (it scans the list linearly each time a
			// key is pressed); it could be much faster. Only of importance if we have
			// quite big lists to deal with -- so for now we can live with this lazy
			// implementation :-)
			int newSelectedItem = 0;
			int bestMatch = 0;
			bool stop;
			for (StringList::const_iterator i = _list.begin(); i != _list.end(); ++i) {
				const int match = matchingCharsIgnoringCase(i->c_str(), _quickSelectStr.c_str(), stop);
				if (match > bestMatch || stop) {
					_selectedItem = newSelectedItem;
					bestMatch = match;
					if (stop)
						break;
				}
				newSelectedItem++;
			}

			scrollToCurrent();
		} else {
			sendCommand(_cmd, 0);
		}
	} else if (_editMode) {
		// Class EditableWidget handles all text editing related key presses for us
		handled = EditableWidget::handleKeyDown(state);
	} else {
		// not editmode

		switch (state.keycode) {
		case Common::KEYCODE_RETURN:
		case Common::KEYCODE_KP_ENTER:
			if (_selectedItem >= 0) {
				// override continuous enter keydown
				if (_editable && (_currentKeyDown != Common::KEYCODE_RETURN && _currentKeyDown != Common::KEYCODE_KP_ENTER)) {
					dirty = true;
					startEditMode();
				} else
					sendCommand(kListItemActivatedCmd, _selectedItem);
			}
			break;
		case Common::KEYCODE_BACKSPACE:
		case Common::KEYCODE_KP_PERIOD:
		case Common::KEYCODE_DELETE:
			if (_selectedItem >= 0) {
				if (_editable) {
					// Ignore delete and backspace when the list item is editable
				} else {
					sendCommand(kListItemRemovalRequestCmd, _selectedItem);
				}
			}
			break;
		case Common::KEYCODE_UP:
			if (_selectedItem > 0)
				_selectedItem--;
			break;
		case Common::KEYCODE_DOWN:
			if (_selectedItem < (int)_list.size() - 1)
				_selectedItem++;
			break;
		case Common::KEYCODE_PAGEUP:
			_selectedItem -= _entriesPerPage - 1;
			if (_selectedItem < 0)
				_selectedItem = 0;
			break;
		case Common::KEYCODE_PAGEDOWN:
			_selectedItem += _entriesPerPage - 1;
			if (_selectedItem >= (int)_list.size() )
				_selectedItem = _list.size() - 1;
			break;
		case Common::KEYCODE_HOME:
			_selectedItem = 0;
			break;
		case Common::KEYCODE_END:
			_selectedItem = _list.size() - 1;
			break;
		default:
			handled = false;
		}

		scrollToCurrent();
	}

	if (dirty || _selectedItem != oldSelectedItem)
		draw();

	if (_selectedItem != oldSelectedItem) {
		sendCommand(kListSelectionChangedCmd, _selectedItem);
		// also draw scrollbar
		_scrollBar->draw();
	}

#if !defined(PALMOS_MODE)
	// not done on PalmOS because keyboard is emulated and keyup is not generated
	_currentKeyDown = state.keycode;
#endif

	return handled;
}
void
mitk::DICOMGDCMTagScanner
::Scan()
{
  // TODO integrate push/pop locale??
  m_GDCMScanner.Scan( m_InputFilenames );

  m_ScanResult.clear();
  for (StringList::const_iterator inputIter = m_InputFilenames.begin();
       inputIter != m_InputFilenames.end();
       ++inputIter)
  {
    m_ScanResult.push_back( DICOMGDCMImageFrameInfo::New( DICOMImageFrameInfo::New(*inputIter, 0), m_GDCMScanner.GetMapping(inputIter->c_str()) ) );
  }
}
Beispiel #16
0
char OSISFootnotes::processText(SWBuf &text, const SWKey *key, const SWModule *module) {
	SWBuf token;
	bool intoken    = false;
	bool hide       = false;
	SWBuf tagText;
	XMLTag startTag;
	SWBuf refs = "";
	int footnoteNum = 1;
	char buf[254];
	SWKey *p = (module) ? module->createKey() : (key) ? key->clone() : new VerseKey();
        VerseKey *parser = SWDYNAMIC_CAST(VerseKey, p);
        if (!parser) {
        	delete p;
                parser = new VerseKey();
        }
        *parser = key->getText();

	SWBuf orig = text;
	const char *from = orig.c_str();

	XMLTag tag;
	bool strongsMarkup = false;


	for (text = ""; *from; ++from) {

		// remove all newlines temporarily to fix kjv2003 module
		if ((*from == 10) || (*from == 13)) {
			if ((text.length()>1) && (text[text.length()-2] != ' ') && (*(from+1) != ' '))
				text.append(' ');
			continue;
		}


		if (*from == '<') {
			intoken = true;
			token = "";
			continue;
		}



		if (*from == '>') {	// process tokens
			intoken = false;
			if (!strncmp(token, "note", 4) || !strncmp(token.c_str(), "/note", 5)) {
				tag = token;

				if (!tag.isEndTag()) {
					if (tag.getAttribute("type") && (!strcmp("x-strongsMarkup", tag.getAttribute("type"))
											|| !strcmp("strongsMarkup", tag.getAttribute("type")))	// deprecated
							) {
						tag.setEmpty(false);  // handle bug in KJV2003 module where some note open tags were <note ... />
						strongsMarkup = true;
					}

					if (!tag.isEmpty()) {
//					if ((!tag.isEmpty()) || (SWBuf("strongsMarkup") == tag.getAttribute("type"))) {
						refs = "";
						startTag = tag;
						hide = true;
						tagText = "";
						continue;
					}
				}
				if (hide && tag.isEndTag()) {
					if (module->isProcessEntryAttributes() && !strongsMarkup) { //don`t parse strongsMarkup to EntryAttributes as Footnote
						sprintf(buf, "%i", footnoteNum++);
						StringList attributes = startTag.getAttributeNames();
						for (StringList::const_iterator it = attributes.begin(); it != attributes.end(); it++) {
							module->getEntryAttributes()["Footnote"][buf][it->c_str()] = startTag.getAttribute(it->c_str());
						}
						module->getEntryAttributes()["Footnote"][buf]["body"] = tagText;
						startTag.setAttribute("swordFootnote", buf);
						if ((startTag.getAttribute("type")) && (!strcmp(startTag.getAttribute("type"), "crossReference"))) {
							if (!refs.length())
								refs = parser->parseVerseList(tagText.c_str(), *parser, true).getRangeText();
							module->getEntryAttributes()["Footnote"][buf]["refList"] = refs.c_str();
						}
					}
					hide = false;
					if (option || (startTag.getAttribute("type") && !strcmp(startTag.getAttribute("type"), "crossReference"))) {	// we want the tag in the text; crossReferences are handled by another filter
						text.append(startTag);
//						text.append(tagText);	// we don't put the body back in because it is retrievable from EntryAttributes["Footnotes"][]["body"].
					}
					else	continue;
				}
				strongsMarkup = false;
			}

			// if not a heading token, keep token in text
			//if ((!strcmp(tag.getName(), "reference")) && (!tag.isEndTag())) {
			//	SWBuf osisRef = tag.getAttribute("osisRef");
			if (!strncmp(token, "reference", 9)) {
				if (refs.length()) {
					refs.append("; ");
				}

				const char* attr = strstr(token.c_str() + 9, "osisRef=\"");
				const char* end  = attr ? strchr(attr+9, '"') : 0;

				if (attr && end) {
					refs.append(attr+9, end-(attr+9));
				}
			}
			if (!hide) {
				text.append('<');
				text.append(token);
				text.append('>');
			}
			else {
				tagText.append('<');
				tagText.append(token);
				tagText.append('>');
			}
			continue;
		}
		if (intoken) { //copy token
			token.append(*from);
		}
		else if (!hide) { //copy text which is not inside a token
			text.append(*from);
		}
		else tagText.append(*from);
	}
        delete parser;
	return 0;
}
const string LdapTools::nextSpicePort(const Node* node) {
	int port = 0;
	int portMin = Config::getInstance()->getSpicePortMin();
	int portMax = Config::getInstance()->getSpicePortMax();
	int size = portMax - portMin + 1;
	//bool* portsUsed = new bool[size];
	bool* portsUsed = (bool *) malloc(size * sizeof(bool));
	for (int i = 0; i < size; i++) {
		portsUsed[i] = false;
	}
	string base("ou=virtual machines,ou=virtualization,ou=services,");
	base.append(Config::getInstance()->getLdapBaseDn());
//	string filter = "(&(objectClass=sstSpice))";
	string filter = "(&(objectClass=sstSpice)(sstNode=";
	filter.append(node->getName()).append("))");
	StringList attrs = StringList();
	attrs.add("sstVirtualMachine");
	attrs.add("sstSpicePort");
	LDAPSearchResults* entries = lc->search(base, LDAPConnection::SEARCH_SUB, filter, attrs);
	LDAPEntry* entry = entries->getNext();
	while (entry != 0) {
		string vmName = "";
		const LDAPAttribute* attribute = entry->getAttributeByName("sstVirtualMachine");
		const StringList values = attribute->getValues();
		StringList::const_iterator it = values.begin();
		if (it != values.end()) {
			vmName = it->c_str();
		}
		const LDAPAttribute* attribute2 = entry->getAttributeByName("sstSpicePort");
		const StringList values2 = attribute2->getValues();
		StringList::const_iterator it2 = values2.begin();
		if (it2 != values2.end()) {
			port = atoi(it2->c_str());
			SYSLOGLOGGER(logDEBUG) << "  " << port << " in use " << port - portMin << " (" << vmName << ")";
			portsUsed[port - portMin] = true;
		}
		delete entry;
		entry = entries->getNext();
	}

	filter = "(&(objectClass=sstSpice)(sstMigrationNode=";
	filter.append(node->getName()).append("))");
	attrs = StringList();
	attrs.add("sstMigrationSpicePort");
	entries = lc->search(base, LDAPConnection::SEARCH_SUB, filter, attrs);
	entry = entries->getNext();
	while (entry != 0) {
		const LDAPAttribute* attribute = entry->getAttributeByName("sstMigrationSpicePort");
		const StringList values = attribute->getValues();
		StringList::const_iterator it = values.begin();
		if (it != values.end()) {
			port = atoi(it->c_str());
			SYSLOGLOGGER(logDEBUG) << "M " << port << " in use " << port - portMin;
			portsUsed[port - portMin] = true;
		}
		delete entry;
		entry = entries->getNext();
	}

	port = 0;
	for (int i = 0; i < size; i++) {
		if (!portsUsed[i]) {
			port = portMin + i;
			break;
		}
	}

	//delete[] portsUsed;
	free(portsUsed);

	SYSLOGLOGGER(logDEBUG) << "nextSpicePort: " << base << "; " << filter << "; port: " << port;
	char buffer[10];
	sprintf(buffer, "%d", port);
	return string(buffer);
}