Пример #1
0
UString UString::from(unsigned u)
{
    UChar buf[sizeof(u) * 3];
    UChar* end = buf + sizeof(buf) / sizeof(UChar);
    UChar* p = end;

    if (u == 0)
        *--p = '0';
    else {
        while (u) {
            *--p = static_cast<unsigned short>((u % 10) + '0');
            u /= 10;
        }
    }

    return UString(p, static_cast<unsigned>(end - p));
}
Пример #2
0
UString UString::from(unsigned int u)
{
  UChar buf[20];
  UChar *end = buf + 20;
  UChar *p = end;
  
  if (u == 0) {
    *--p = '0';
  } else {
    while (u) {
      *--p = (unsigned short)((u % 10) + '0');
      u /= 10;
    }
  }
  
  return UString(p, end - p);
}
void Profile::debugPrintDataSampleStyle() const
{
    typedef Vector<NameCountPair> NameCountPairVector;

    FunctionCallHashCount countedFunctions;
    printf("Call graph:\n");
    m_head->debugPrintDataSampleStyle(0, countedFunctions);

    printf("\nTotal number in stack:\n");
    NameCountPairVector sortedFunctions(countedFunctions.size());
    copyToVector(countedFunctions, sortedFunctions);

    std::sort(sortedFunctions.begin(), sortedFunctions.end(), functionNameCountPairComparator);
    for (NameCountPairVector::iterator it = sortedFunctions.begin(); it != sortedFunctions.end(); ++it)
        printf("        %-12d%s\n", (*it).second, UString((*it).first).UTF8String().c_str());

    printf("\nSort by top of stack, same collapsed (when >= 5):\n");
}
Пример #4
0
STDMETHODIMP P7ZipArchiveUpdateCallback::GetVolumeStream(UInt32 index, ISequentialOutStream **volumeStream)
{
  wchar_t temp[16];
  ConvertUInt32ToString(index + 1, temp);
  UString res = temp;
  while (res.Length() < 2)
    res = UString(L'0') + res;
  UString fileName = VolName;
  fileName += L'.';
  fileName += res;
  fileName += VolExt;
  COutFileStream *streamSpec = new COutFileStream;
  CMyComPtr<ISequentialOutStream> streamLoc(streamSpec);
  if (!streamSpec->Create(fileName, false))
    return ::GetLastError();
  *volumeStream = streamLoc.Detach();
  return S_OK;
}
Пример #5
0
UString UString::substr(int pos, int len) const
{
    int s = size();

    if (pos < 0)
        pos = 0;
    else if (pos >= s)
        pos = s;
    if (len < 0)
        len = s;
    if (pos + len >= s)
        len = s - pos;

    if (pos == 0 && len == s)
        return *this;

    return UString(Rep::create(m_rep, pos, len));
}
Пример #6
0
UfopaediaCategory::UfopaediaCategory(Framework &fw, tinyxml2::XMLElement* Element) : Stage(fw)
{
	UString nodename;

	ViewingEntry = 0;

	if( Element->Attribute("id") != nullptr && UString(Element->Attribute("id")) != "" )
	{
		ID = Element->Attribute("id");
	}

	tinyxml2::XMLElement* node;
	for( node = Element->FirstChildElement(); node != nullptr; node = node->NextSiblingElement() )
	{
		nodename = node->Name();

		if( nodename == "backgroundimage" )
		{
			BackgroundImageFilename = node->GetText();
		}
		if( nodename == "title" )
		{
			Title = node->GetText();
		}
		if( nodename == "text_info" )
		{
			BodyInformation = node->GetText();
		}
		if( nodename == "entries" )
		{
			tinyxml2::XMLElement* node2;
			for( node2 = node->FirstChildElement(); node2 != nullptr; node2 = node2->NextSiblingElement() )
			{
				std::shared_ptr<UfopaediaEntry> newentry = std::make_shared<UfopaediaEntry>( node2 );
				Entries.push_back( newentry );
			}
		}
	}

	menuform = fw.gamecore->GetForm("FORM_UFOPAEDIA_BASE");


}
Пример #7
0
void Debugger::recompileAllJSFunctions(JSGlobalData* globalData)
{
    // If JavaScript is running, it's not safe to recompile, since we'll end
    // up throwing away code that is live on the stack.
    ASSERT(!globalData->dynamicGlobalObject);
    if (globalData->dynamicGlobalObject)
        return;

    typedef HashSet<FunctionExecutable*> FunctionExecutableSet;
    typedef HashMap<SourceProvider*, ExecState*> SourceProviderMap;

    FunctionExecutableSet functionExecutables;
    SourceProviderMap sourceProviders;

    LiveObjectIterator it = globalData->heap.primaryHeapBegin();
    LiveObjectIterator heapEnd = globalData->heap.primaryHeapEnd();
    for ( ; it != heapEnd; ++it) {
        if (!(*it)->inherits(&JSFunction::info))
            continue;

        JSFunction* function = asFunction(*it);
        if (function->executable()->isHostFunction())
            continue;

        FunctionExecutable* executable = function->jsExecutable();

        // Check if the function is already in the set - if so,
        // we've already retranslated it, nothing to do here.
        if (!functionExecutables.add(executable).second)
            continue;

        ExecState* exec = function->scope().globalObject()->JSGlobalObject::globalExec();
        executable->recompile(exec);
        if (function->scope().globalObject()->debugger() == this)
            sourceProviders.add(executable->source().provider(), exec);
    }

    // Call sourceParsed() after reparsing all functions because it will execute
    // JavaScript in the inspector.
    SourceProviderMap::const_iterator end = sourceProviders.end();
    for (SourceProviderMap::const_iterator iter = sourceProviders.begin(); iter != end; ++iter)
        sourceParsed(iter->second, SourceCode(iter->first), -1, UString());
}
Пример #8
0
JSValue* DebuggerCallFrame::evaluate(const UString& script, JSValue*& exception) const
{
    if (!m_codeBlock)
        return 0;

    JSObject* thisObject = this->thisObject();

    ExecState newExec(m_scopeChain->globalObject(), thisObject, m_scopeChain);

    int sourceId;
    int errLine;
    UString errMsg;
    RefPtr<SourceProvider> sourceProvider = UStringSourceProvider::create(script);
    RefPtr<EvalNode> evalNode = newExec.parser()->parse<EvalNode>(&newExec, UString(), 1, sourceProvider, &sourceId, &errLine, &errMsg);
    if (!evalNode)
        return Error::create(&newExec, SyntaxError, errMsg, errLine, sourceId, 0);

    return newExec.machine()->execute(evalNode.get(), &newExec, thisObject, m_scopeChain, &exception);
}
Пример #9
0
UString ConvertPropVariantToString(const PROPVARIANT &prop)
{
  switch (prop.vt)
  {
    case VT_EMPTY: return UString();
    case VT_BSTR: return prop.bstrVal;
    case VT_UI1: return ConvertUInt64ToString(prop.bVal);
    case VT_UI2: return ConvertUInt64ToString(prop.uiVal);
    case VT_UI4: return ConvertUInt64ToString(prop.ulVal);
    case VT_UI8: return ConvertUInt64ToString(prop.uhVal.QuadPart);
    case VT_FILETIME: return ConvertFileTimeToString(prop.filetime, true, true);
    // case VT_I1: return ConvertInt64ToString(prop.cVal);
    case VT_I2: return ConvertInt64ToString(prop.iVal);
    case VT_I4: return ConvertInt64ToString(prop.lVal);
    case VT_I8: return ConvertInt64ToString(prop.hVal.QuadPart);
    case VT_BOOL: return VARIANT_BOOLToBool(prop.boolVal) ? L"+" : L"-";
    default: throw 150245;
  }
}
Пример #10
0
void mtstring::atlocation(const double& rX,
                          const double& rY,
                          MString& rValues) const
{
  rValues.SetDefined(false);

  if(IsDefined() &&
     IsValidLocation(rX, rY))
  {
    rValues.SetDefined(true);

    Rectangle<3> boundingBox;
    bbox(boundingBox);
    Instant minimumTime = boundingBox.MinD(2);
    Instant maximumTime = boundingBox.MaxD(2);
    datetime::DateTime duration = m_Grid.GetDuration();

    rValues.StartBulkLoad();

    for(Instant currentTime = minimumTime;
        currentTime < maximumTime;
        currentTime += duration)
    {
      CcString value;
      atlocation(rX, rY, currentTime.ToDouble(), value);

      if(value.IsDefined())
      {
        Interval<Instant> interval(currentTime, currentTime + duration,
                                   true, false);
        rValues.Add(UString(interval, value, value));
      }
    }

    rValues.EndBulkLoad();

    if(rValues.IsEmpty())
    {
      rValues.SetDefined(false);
    }
  }
}
Пример #11
0
//------------------------------------------------------------------------
RangeParameter::RangeParameter (const TChar* title, ParamID tag, const TChar* units,
								ParamValue minPlain, ParamValue maxPlain, ParamValue defaultValuePlain,
								int32 stepCount, int32 flags, UnitID unitID)
: minPlain (minPlain)
, maxPlain (maxPlain)
{
	UString (info.title, tStrBufferSize(String128)).assign (title);

	UString uUnits (info.units, tStrBufferSize(String128));
	if (units)
	{
		uUnits.assign (units);
	}

	info.stepCount = stepCount;
	info.defaultNormalizedValue = toNormalized (defaultValuePlain);
	info.flags = flags;
	info.id = tag;
	info.unitId = unitID;
}
Пример #12
0
EncodedJSValue JSC_HOST_CALL regExpProtoFuncCompile(ExecState* exec)
{
    JSValue thisValue = exec->hostThisValue();
    if (!thisValue.inherits(&RegExpObject::s_info))
        return throwVMTypeError(exec);

    RegExp* regExp;
    JSValue arg0 = exec->argument(0);
    JSValue arg1 = exec->argument(1);

    if (arg0.isSymbolic() || arg1.isSymbolic()) {
        Statistics::statistics()->accumulate("Concolic::MissingInstrumentation::regExpProtoFuncCompile", 1);
    }
    
    if (arg0.inherits(&RegExpObject::s_info)) {
        if (!arg1.isUndefined())
            return throwVMError(exec, createTypeError(exec, "Cannot supply flags when constructing one RegExp from another."));
        regExp = asRegExpObject(arg0)->regExp();
    } else {
        UString pattern = !exec->argumentCount() ? UString("") : arg0.toString(exec)->value(exec);
        if (exec->hadException())
            return JSValue::encode(jsUndefined());

        RegExpFlags flags = NoFlags;
        if (!arg1.isUndefined()) {
            flags = regExpFlags(arg1.toString(exec)->value(exec));
            if (exec->hadException())
                return JSValue::encode(jsUndefined());
            if (flags == InvalidFlags)
                return throwVMError(exec, createSyntaxError(exec, "Invalid flags supplied to RegExp constructor."));
        }
        regExp = RegExp::create(exec->globalData(), pattern, flags);
    }

    if (!regExp->isValid())
        return throwVMError(exec, createSyntaxError(exec, regExp->errorMessage()));

    asRegExpObject(thisValue)->setRegExp(exec->globalData(), regExp);
    asRegExpObject(thisValue)->setLastIndex(exec, 0);
    return JSValue::encode(jsUndefined());
}
Пример #13
0
static bool parseFrame(tinyxml2::XMLElement *root, DoodadFrame &f)
{
	if (UString(root->Name()) != "frame")
	{
		LogError("Called on unexpected node \"%s\"", root->Name());
		return false;
	}
	if (!ReadAttribute(root, "time", f.time))
	{
		LogError("No \"time\" attribute in frame");
		return false;
	}
	UString spritePath = root->GetText();
	f.image = fw().data->load_image(spritePath);
	if (!f.image)
	{
		LogError("Failed to load sprite \"%s\" for doodad frame", spritePath.c_str());
		return false;
	}
	return true;
}
Пример #14
0
void TextEntry::maybe_scroll()
{
   const Theme & theme = dialog->get_theme();

   if (cursor_pos < left_pos + 3) {
      if (cursor_pos < 3)
         left_pos = 0;
      else
         left_pos = cursor_pos - 3;
   }
   else {
      for (;;) {
         const int tw = al_get_ustr_width(theme.font,
            UString(text, left_pos, cursor_pos));
         if (x1 + tw + CURSOR_WIDTH < x2) {
            break;
         }
         al_ustr_next(text, &left_pos);
      }
   }
}
Пример #15
0
JSValue* stringProtoFuncToLocaleUpperCase(ExecState* exec, JSObject*, JSValue* thisValue, const ArgList&)
{
    JSString* sVal = thisValue->toThisJSString(exec);
    const UString& s = sVal->value();
    
    int ssize = s.size();
    if (!ssize)
        return sVal;
    Vector<UChar> buffer(ssize);
    bool error;
    int length = Unicode::toUpper(buffer.data(), ssize, reinterpret_cast<const UChar*>(s.data()), ssize, &error);
    if (error) {
        buffer.resize(length);
        length = Unicode::toUpper(buffer.data(), length, reinterpret_cast<const UChar*>(s.data()), ssize, &error);
        if (error)
            return sVal;
    }
    if (length == ssize && memcmp(buffer.data(), s.data(), length * sizeof(UChar)) == 0)
        return sVal;
    return jsString(exec, UString(buffer.releaseBuffer(), length, false));
}
Пример #16
0
JSValue JSC_HOST_CALL stringProtoFuncFontsize(ExecState* exec, JSObject*, JSValue thisValue, const ArgList& args)
{
    UString s = thisValue.toThisString(exec);
    JSValue a0 = args.at(0);

    uint32_t smallInteger;
    if (a0.getUInt32(smallInteger) && smallInteger <= 9) {
        unsigned stringSize = s.size();
        unsigned bufferSize = 22 + stringSize;
        UChar* buffer = static_cast<UChar*>(tryFastMalloc(bufferSize * sizeof(UChar)));
        if (!buffer)
            return jsUndefined();
        buffer[0] = '<';
        buffer[1] = 'f';
        buffer[2] = 'o';
        buffer[3] = 'n';
        buffer[4] = 't';
        buffer[5] = ' ';
        buffer[6] = 's';
        buffer[7] = 'i';
        buffer[8] = 'z';
        buffer[9] = 'e';
        buffer[10] = '=';
        buffer[11] = '"';
        buffer[12] = '0' + smallInteger;
        buffer[13] = '"';
        buffer[14] = '>';
        memcpy(&buffer[15], s.data(), stringSize * sizeof(UChar));
        buffer[15 + stringSize] = '<';
        buffer[16 + stringSize] = '/';
        buffer[17 + stringSize] = 'f';
        buffer[18 + stringSize] = 'o';
        buffer[19 + stringSize] = 'n';
        buffer[20 + stringSize] = 't';
        buffer[21 + stringSize] = '>';
        return jsNontrivialString(exec, UString(buffer, bufferSize, false));
    }

    return jsNontrivialString(exec, "<font size=\"" + a0.toString(exec) + "\">" + s + "</font>");
}
	void WindowsClipboardHandler::handleClipboardChanged(const std::string& _type, const std::string& _data)
	{
		if (_type == "Text")
		{
			mPutTextInClipboard = TextIterator::getOnlyText(UString(_data));
			size_t size = (mPutTextInClipboard.size() + 1) * 2;
			//открываем буфер обмена
			if (OpenClipboard((HWND)mHwnd))
			{
				EmptyClipboard(); //очищаем буфер
				HGLOBAL hgBuffer = GlobalAlloc(GMEM_DDESHARE, size);//выделяем память
				wchar_t* chBuffer = hgBuffer ? (wchar_t*)GlobalLock(hgBuffer) : NULL;
				if (chBuffer)
				{
					memcpy(chBuffer, mPutTextInClipboard.asWStr_c_str(), size);
					GlobalUnlock(hgBuffer);//разблокируем память
					SetClipboardData(CF_UNICODETEXT, hgBuffer);//помещаем текст в буфер обмена
				}
				CloseClipboard(); //закрываем буфер обмена
			}
		}
	}
Пример #18
0
    bool TextIterator::setTagColour(const Colour& _colour)
    {
        if (mCurrent == mEnd) return false;
        // очищаем все цвета
        clearTagColour();
        // на всякий
        if (mCurrent == mEnd) return false;

        const size_t SIZE = 16;
        wchar_t buff[SIZE];

#ifdef __MINGW32__
        swprintf(buff, L"#%.2X%.2X%.2X\0", (int)(_colour.red * 255), (int)(_colour.green * 255), (int)(_colour.blue * 255));
#else
        swprintf(buff, SIZE, L"#%.2X%.2X%.2X\0", (int)(_colour.red * 255), (int)(_colour.green * 255), (int)(_colour.blue * 255));
#endif
        // непосредственная вставка
        UString tmpStr = UString(buff);
        insert(mCurrent, tmpStr);

        return true;
    }
Пример #19
0
ScriptSection *CServerDefinitions::FindEntry( std::string toFind, DEFINITIONCATEGORIES typeToFind )
{
	ScriptSection *rvalue = NULL;

	if( !toFind.empty() && typeToFind != NUM_DEFS )
	{
		UString tUFind = UString( toFind ).upper();

		VECSCRIPTLIST& toDel = ScriptListings[typeToFind];
		for( VECSCRIPTLIST_CITERATOR dIter = toDel.begin(); dIter != toDel.end(); ++dIter )
		{
			Script *toCheck = (*dIter);
			if( toCheck != NULL )
			{
				rvalue = toCheck->FindEntry( tUFind );
				if( rvalue != NULL )
					break;
			}
		}
	}
	return rvalue;
}
Пример #20
0
UString Platform::getUserDataDirectory() {
	UString directory;

#if defined(WIN32)
	// Windows: Same as getConfigDirectory()
	directory = getConfigDirectory();
#elif defined(MACOSX)
	// Mac OS X: ~/Library/Application\ Support/xoreos/

	directory = getHomeDirectory();
	if (!directory.empty())
		directory += "/Library/Application Support/xoreos";

	if (directory.empty())
		directory = ".";

#elif defined(UNIX)
	// Default Unixoid: $XDG_DATA_HOME/xoreos/ or ~/.local/share/xoreos/

	const char *pathStr = getenv("XDG_DATA_HOME");
	if (pathStr) {
		directory = UString(pathStr) + "/xoreos";
	} else {
		directory = getHomeDirectory();
		if (!directory.empty())
			directory += "/.local/share/xoreos";
	}

	if (directory.empty())
		directory = ".";

#else
	// Fallback: Same as getConfigDirectory()
	directory = getConfigDirectory();
#endif

	return FilePath::canonicalize(directory);
}
ScriptCallStack::ScriptCallStack(ExecState* exec, unsigned skipArgumentCount)
    : m_initialized(false)
    , m_exec(exec)
    , m_caller(0)
{
    int signedLineNumber;
    intptr_t sourceID;
    UString urlString;
    JSValue function;

    exec->interpreter()->retrieveLastCaller(exec, signedLineNumber, sourceID, urlString, function);

    unsigned lineNumber = signedLineNumber >= 0 ? signedLineNumber : 0;

    if (function) {
        m_caller = asFunction(function);
        m_frames.append(ScriptCallFrame(m_caller->name(m_exec), urlString, lineNumber, m_exec, skipArgumentCount));
    } else {
        // Caller is unknown, but we should still add the frame, because
        // something called us, and gave us arguments.
        m_frames.append(ScriptCallFrame(UString(), urlString, lineNumber, m_exec, skipArgumentCount));
    }
}
Пример #22
0
UString formatTime(const GregorianDateTime &t, bool utc)
{
    char buffer[100];
    if (utc) {
        snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d GMT", t.hour, t.minute, t.second);
    } else {
        int offset = abs(gmtoffset(t));
        char tzname[70];
        struct tm gtm = t;
        strftime(tzname, sizeof(tzname), "%Z", &gtm);

        if (tzname[0]) {
            snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d GMT%c%02d%02d (%s)",
                     t.hour, t.minute, t.second,
                     gmtoffset(t) < 0 ? '-' : '+', offset / (60*60), (offset / 60) % 60, tzname);
        } else {
            snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d GMT%c%02d%02d",
                     t.hour, t.minute, t.second,
                     gmtoffset(t) < 0 ? '-' : '+', offset / (60*60), (offset / 60) % 60);
        }
    }
    return UString(buffer);
}
Пример #23
0
JSValue* stringProtoFuncToLocaleLowerCase(ExecState* exec, JSObject*, JSValue* thisValue, const ArgList&)
{
    // FIXME: See http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt for locale-sensitive mappings that aren't implemented.

    JSString* sVal = thisValue->toThisJSString(exec);
    const UString& s = sVal->value();
    
    int ssize = s.size();
    if (!ssize)
        return sVal;
    Vector<UChar> buffer(ssize);
    bool error;
    int length = Unicode::toLower(buffer.data(), ssize, reinterpret_cast<const UChar*>(s.data()), ssize, &error);
    if (error) {
        buffer.resize(length);
        length = Unicode::toLower(buffer.data(), length, reinterpret_cast<const UChar*>(s.data()), ssize, &error);
        if (error)
            return sVal;
    }
    if (length == ssize && memcmp(buffer.data(), s.data(), length * sizeof(UChar)) == 0)
        return sVal;
    return jsString(exec, UString(buffer.releaseBuffer(), length, false));
}
EncodedJSValue JSC_HOST_CALL regExpProtoFuncCompile(ExecState* exec)
{
    JSValue thisValue = exec->hostThisValue();
    if (!thisValue.inherits(&RegExpObject::s_info))
        return throwVMTypeError(exec);

    RefPtr<RegExp> regExp;
    JSValue arg0 = exec->argument(0);
    JSValue arg1 = exec->argument(1);
    
    if (arg0.inherits(&RegExpObject::s_info)) {
        if (!arg1.isUndefined())
            return throwVMError(exec, createTypeError(exec, "Cannot supply flags when constructing one RegExp from another."));
        regExp = asRegExpObject(arg0)->regExp();
    } else {
        UString pattern = !exec->argumentCount() ? UString("") : arg0.toString(exec);
        if (exec->hadException())
            return JSValue::encode(jsUndefined());

        RegExpFlags flags = NoFlags;
        if (!arg1.isUndefined()) {
            flags = regExpFlags(arg1.toString(exec));
            if (exec->hadException())
                return JSValue::encode(jsUndefined());
            if (flags == InvalidFlags)
                return throwVMError(exec, createSyntaxError(exec, "Invalid flags supplied to RegExp constructor."));
        }
        regExp = exec->globalData().regExpCache()->lookupOrCreate(pattern, flags);
    }

    if (!regExp->isValid())
        return throwVMError(exec, createSyntaxError(exec, regExp->errorMessage()));

    asRegExpObject(thisValue)->setRegExp(regExp.release());
    asRegExpObject(thisValue)->setLastIndex(0);
    return JSValue::encode(jsUndefined());
}
Пример #25
0
void QtInstance::getPropertyNames(ExecState* exec, PropertyNameArray& array)
{
    // This is the enumerable properties, so put:
    // properties
    // dynamic properties
    // slots
    QObject* obj = getObject();
    if (obj) {
        const QMetaObject* meta = obj->metaObject();

        int i;
        for (i = 0; i < meta->propertyCount(); i++) {
            QMetaProperty prop = meta->property(i);
            if (prop.isScriptable())
                array.add(Identifier(exec, prop.name()));
        }

#ifndef QT_NO_PROPERTIES
        QList<QByteArray> dynProps = obj->dynamicPropertyNames();
        foreach (const QByteArray& ba, dynProps)
            array.add(Identifier(exec, ba.constData()));
#endif

        const int methodCount = meta->methodCount();
        for (i = 0; i < methodCount; i++) {
            QMetaMethod method = meta->method(i);
            if (method.access() != QMetaMethod::Private) {
#if HAVE(QT5)
                QByteArray sig = method.methodSignature();
                array.add(Identifier(exec, UString(sig.constData(), sig.length())));
#else
                array.add(Identifier(exec, method.signature()));
#endif
            }
        }
    }
}
Пример #26
0
UPosting::UPosting(uint32_t dimension, bool parsing, bool index)
{
   U_TRACE_REGISTER_OBJECT(5, UPosting, "%u,%b,%b", dimension, parsing, index)

   U_INTERNAL_ASSERT_EQUALS(word,0)
   U_INTERNAL_ASSERT_EQUALS(posting,0)
   U_INTERNAL_ASSERT_EQUALS(filename,0)
   U_INTERNAL_ASSERT_EQUALS(str_cur_doc_id,0)

   word           = U_NEW(UString);
   posting        = U_NEW(UString);
   filename       = U_NEW(UString);
   str_cur_doc_id = U_NEW(UString(sizeof(cur_doc_id)));

   approximate_num_words = 2000 + (dimension * 8);

   if (index)
      {
      U_INTERNAL_ASSERT_EQUALS(tbl_name, 0)
      U_INTERNAL_ASSERT_EQUALS(tbl_words, 0)

      dimension += dimension / 4;

      tbl_name  = U_NEW(UHashMap<UString>(U_GET_NEXT_PRIME_NUMBER(dimension)));
      tbl_words = U_NEW(UHashMap<UString>(U_GET_NEXT_PRIME_NUMBER(approximate_num_words), ignore_case));
      }

   if (parsing)
      {
      U_INTERNAL_ASSERT_EQUALS(file,0)
      U_INTERNAL_ASSERT_EQUALS(content,0)

      file    = U_NEW(UFile);
      content = U_NEW(UString);
      }
}
Пример #27
0
bool RulesLoader::ParseOrganisationDefinition(Rules &rules, tinyxml2::XMLElement *root)
{
	TRACE_FN;
	if (UString(root->Name()) != "organisation")
	{
		LogError("Called on unexpected node \"%s\"", root->Name());
		return false;
	}

	Organisation org;

	if (!ReadAttribute(root, "ID", org.ID))
	{
		LogError("Organisation with no ID");
		return false;
	}

	if (org.ID.substr(0, 4) != "ORG_")
	{
		LogError("Organisation ID \"%s\" doesn't start with \"ORG_\"", org.ID.c_str());
		return false;
	}

	if (!ReadAttribute(root, "name", org.name))
	{
		LogError("Organisation ID \"%s\" has no name", org.ID.c_str());
		return false;
	}

	ReadAttribute(root, "balance", org.balance, 0);
	ReadAttribute(root, "income", org.income, 0);

	rules.organisations.push_back(org);

	return true;
}
Пример #28
0
std::vector<UString> LinuxEnvironment::getFoldersInFolder(UString folder)
{
	std::vector<UString> folders;

	struct dirent **namelist;
	int n = scandir(folder.toUtf8(), &namelist, getFoldersInFolderFilter, alphasort);
	if (n < 0)
	{
		///debugLog("LinuxEnvironment::getFilesInFolder() error, scandir() returned %i!\n", n);
		return folders;
	}

	while (n--)
	{
		const char *name = namelist[n]->d_name;
		UString uName = UString(name);
		UString fullName = folder;
		fullName.append(uName);
		free(namelist[n]);

		struct stat stDirInfo;
		int lstatret = lstat(fullName.toUtf8(), &stDirInfo);
		if (lstatret < 0)
		{
			///perror (name);
			///debugLog("LinuxEnvironment::getFilesInFolder() error, lstat() returned %i!\n", lstatret);
			continue;
		}

		if (S_ISDIR(stDirInfo.st_mode))
			folders.push_back(uName);
	}
	free(namelist);

	return folders;
}
Пример #29
0
bool GetLongPathBase(LPCWSTR s, UString &res)
{
  res.Empty();
  int len = MyStringLen(s);
  wchar_t c = s[0];
  if (len < 1 || c == L'\\' || c == L'.' && (len == 1 || len == 2 && s[1] == L'.'))
    return true;
  UString curDir;
  bool isAbs = false;
  if (len > 3)
    isAbs = (s[1] == L':' && s[2] == L'\\' && (c >= L'a' && c <= L'z' || c >= L'A' && c <= L'Z'));

  if (!isAbs)
    {
      DWORD needLength = ::GetCurrentDirectoryW(MAX_PATH + 1, curDir.GetBuffer(MAX_PATH + 1));
      curDir.ReleaseBuffer();
      if (needLength == 0 || needLength > MAX_PATH)
        return false;
      if (curDir[curDir.Length() - 1] != L'\\')
        curDir += L'\\';
    }
  res = UString(L"\\\\?\\") + curDir + s;
  return true;
}
Пример #30
0
void GameCore::ApplyAliases(tinyxml2::XMLElement *Source)
{
	if (aliases.empty())
	{
		return;
	}

	const tinyxml2::XMLAttribute *attr = Source->FirstAttribute();

	while (attr != nullptr)
	{
		// Is the attribute value the same as an alias? If so, replace with alias' value
		if (aliases.find(UString(attr->Value())) != aliases.end())
		{
			LogInfo("%s attribute \"%s\" value \"%s\" matches alias \"%s\"", Source->Name(),
			        attr->Name(), attr->Value(), aliases[UString(attr->Value())].c_str());
			Source->SetAttribute(attr->Name(), aliases[UString(attr->Value())].c_str());
		}

		attr = attr->Next();
	}

	// Replace inner text
	if (Source->GetText() != nullptr && aliases.find(UString(Source->GetText())) != aliases.end())
	{
		LogInfo("%s  value \"%s\" matches alias \"%s\"", Source->Name(), Source->GetText(),
		        aliases[UString(Source->GetText())].c_str());
		Source->SetText(aliases[UString(Source->GetText())].c_str());
	}

	// Recurse down tree
	tinyxml2::XMLElement *child = Source->FirstChildElement();
	while (child != nullptr)
	{
		ApplyAliases(child);
		child = child->NextSiblingElement();
	}
}