bool String::EndsWith(const String& str) const { return FindLast(str) == Length() - str.Length(); }
OracleConnection::ObjectType OracleConnection::ReadSPDescriptionFromDB( const String &command, Anything &desc ) { StartTrace(OracleConnection.ReadSPDescriptionFromDB); String strErr( "ReadSPDescriptionFromDB: " ); MemChecker aCheckerLocal( "OracleConnection.ReadSPDescriptionFromDB", getEnvironment().getAllocator() ); MemChecker aCheckerGlobal( "OracleConnection.ReadSPDescriptionFromDB", coast::storage::Global()); sword attrStat; DscHandleType aDschp; if ( checkError( ( attrStat = OCIHandleAlloc( getEnvironment().EnvHandle(), aDschp.getVoidAddr(), OCI_HTYPE_DESCRIBE, 0, 0 ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("after HandleAlloc, local allocator:" << reinterpret_cast<long>(getEnvironment().getAllocator())); Trace("after HandleAlloc, global allocator:" << reinterpret_cast<long>(coast::storage::Global())); OCIParam *parmh( 0 ); ObjectType aStmtType = DescribeObjectByName(command, aDschp, parmh); if ( aStmtType == TYPE_SYN ) { Trace("as we identified a synonym, we need to collect the scheme name and the referenced object name to ask for description"); text *name(0); ub4 namelen(0); String strSchemaName; attrStat = OCIAttrGet( (dvoid *) parmh, OCI_DTYPE_PARAM, (dvoid *) &name, (ub4 *) &namelen, OCI_ATTR_SCHEMA_NAME, ErrorHandle() ); if ( checkError( ( attrStat ) ) ) { throw OracleException( *this, attrStat ); } strSchemaName.Append(String( (char *) name, namelen )); Trace("SchemaName: " << strSchemaName); attrStat = OCIAttrGet( (dvoid *) parmh, OCI_DTYPE_PARAM, (dvoid *) &name, (ub4 *) &namelen, OCI_ATTR_NAME, ErrorHandle() ); if ( checkError( ( attrStat ) ) ) { throw OracleException( *this, attrStat ); } if ( strSchemaName.Length() ) { strSchemaName.Append('.'); } strSchemaName.Append(String( (char *) name, namelen )); Trace("trying to get descriptions for " << strSchemaName); aStmtType = DescribeObjectByName(strSchemaName, aDschp, parmh); } bool bIsFunction = ( aStmtType == TYPE_FUNC ); Trace("get the number of arguments and the arg list for stored " << (bIsFunction ? "function" : "procedure")) OCIParam *arglst( 0 ); ub2 numargs = 0; if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) parmh, OCI_DTYPE_PARAM, (dvoid *) &arglst, (ub4 *) 0, OCI_ATTR_LIST_ARGUMENTS, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arglst, OCI_DTYPE_PARAM, (dvoid *) &numargs, (ub4 *) 0, OCI_ATTR_NUM_PARAMS, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace(String("number of arguments: ") << numargs); OCIParam *arg( 0 ); text *name; ub4 namelen; ub2 dtype; OCITypeParamMode iomode; ub4 data_len; // For a procedure, we begin with i = 1; for a function, we begin with i = 0. int start = 0; int end = numargs; if ( !bIsFunction ) { ++start; ++end; } for ( int i = start; i < end; ++i ) { if ( checkError( ( attrStat = OCIParamGet( (dvoid *) arglst, OCI_DTYPE_PARAM, ErrorHandle(), (dvoid **) &arg, (ub4) i ) ) ) ) { throw OracleException( *this, attrStat ); } namelen = 0; name = 0; data_len = 0; if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &dtype, (ub4 *) 0, OCI_ATTR_DATA_TYPE, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("Data type: " << dtype) if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &name, (ub4 *) &namelen, OCI_ATTR_NAME, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } String strName( (char *) name, namelen ); // the first param of a function is the return param if ( bIsFunction && i == start ) { strName = command; Trace("Name: " << strName) } // 0 = IN (OCI_TYPEPARAM_IN), 1 = OUT (OCI_TYPEPARAM_OUT), 2 = IN/OUT (OCI_TYPEPARAM_INOUT) if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &iomode, (ub4 *) 0, OCI_ATTR_IOMODE, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("IO type: " << iomode) if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &data_len, (ub4 *) 0, OCI_ATTR_DATA_SIZE, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("Size: " << (int)data_len) Anything param( desc.GetAllocator() ); param["Name"] = strName; param["Type"] = dtype; param["Length"] = (int) data_len; param["IoMode"] = iomode; param["Idx"] = (long) ( bIsFunction ? i + 1 : i ); desc.Append( param ); if ( checkError( ( attrStat = OCIDescriptorFree( arg, OCI_DTYPE_PARAM ) ) ) ) { throw OracleException( *this, attrStat ); } }
void CSFunctionWriter::GenPInvokeCallParameters(String& sig) { // generate args const Vector<JSBFunctionType*>& parameters = function_->GetParameters(); if (parameters.Size()) { for (unsigned int i = 0; i < parameters.Size(); i++) { JSBFunctionType* ptype = parameters.At(i); // ignore "Context" parameters if (ptype->type_->asClassType()) { JSBClassType* classType = ptype->type_->asClassType(); JSBClass* klass = classType->class_; if (klass->GetName() == "Context") { continue; } } String name = ptype->name_; if (name == "object") name = "_object"; else if (name == "readonly") name = "readOnly"; else if (name == "params") name = "parameters"; if (ptype->type_->asClassType()) { JSBClass* pclass = ptype->type_->asClassType()->class_; if (pclass->IsNumberArray()) { sig += "ref " + name; } else { sig += name + " == null ? IntPtr.Zero : " + name + ".NativeInstance"; } } else { sig += name; } if (i + 1 != parameters.Size()) sig += ", "; } } // data marshaller if (function_->GetReturnType() && !CSTypeHelper::IsSimpleReturn(function_->GetReturnType())) { if (function_->GetReturnClass()->IsNumberArray()) { if (sig.Length()) sig += ", "; JSBClass* klass = function_->GetClass(); sig += ToString("ref %s%s%uReturnValue", klass->GetName().CString(), function_->GetName().CString(), function_->GetID()); } } else if (!function_->IsStatic() && function_->GetReturnType() && function_->GetReturnType()->type_->asVectorType()) { if (sig.Length()) sig += ", "; JSBClass* klass = function_->GetClass(); sig += "returnScriptVector"; } }
int ClipOverlap::execute(int argc, char **argv) { // Extract command line arguments. String inFile = ""; String outFile = ""; String storeOrig = ""; bool readName = false; bool stats = false; int poolSize = DEFAULT_POOL_SIZE; bool unmapped = false; bool noeof = false; bool params = false; String excludeFlags = "0x70C"; // TODO, cleanup legacy parameters ParameterList inputParameters; BEGIN_LONG_PARAMETERS(longParameterList) LONG_PARAMETER_GROUP("Required Parameters") LONG_STRINGPARAMETER("in", &inFile) LONG_STRINGPARAMETER("out", &outFile) LONG_PARAMETER_GROUP("Optional Parameters") LONG_STRINGPARAMETER("storeOrig", &storeOrig) LONG_PARAMETER("readName", &readName) LONG_PARAMETER ("stats", &stats) LONG_PARAMETER ("overlapsOnly", &myOverlapsOnly) LONG_STRINGPARAMETER ("excludeFlags", &excludeFlags) LONG_PARAMETER("unmapped", &unmapped) LONG_PARAMETER("noeof", &noeof) LONG_PARAMETER("params", ¶ms) LONG_PARAMETER_GROUP("Coordinate Processing Optional Parameters") LONG_INTPARAMETER("poolSize", &poolSize) LONG_PARAMETER("poolSkipOverlap", &myPoolSkipOverlap) LONG_PHONEHOME(VERSION) BEGIN_LEGACY_PARAMETERS() LONG_PARAMETER ("clipsOnly", &myOverlapsOnly) LONG_PARAMETER("poolSkipClip", &myPoolSkipOverlap) END_LONG_PARAMETERS(); inputParameters.Add(new LongParameters ("Input Parameters", longParameterList)); // parameters start at index 2 rather than 1. inputParameters.Read(argc, argv, 2); // If no eof block is required for a bgzf file, set the bgzf file type to // not look for it. if(noeof) { // Set that the eof block is not required. BgzfFileType::setRequireEofBlock(false); } // Check to see if the in file was specified, if not, report an error. if(inFile == "") { usage(); inputParameters.Status(); // In file was not specified but it is mandatory. std::cerr << "--in is a mandatory argument, " << "but was not specified" << std::endl; return(-1); } // Check to see if the out file was specified, if not, report an error. if(outFile == "") { usage(); inputParameters.Status(); // Out file was not specified but it is mandatory. std::cerr << "--out is a mandatory argument, " << "but was not specified" << std::endl; return(-1); } if((storeOrig.Length() != 0) && (storeOrig.Length() != 2)) { usage(); inputParameters.Status(); std::cerr << "--storeOrig tag name must be 2 characters.\n"; return(-1); } myOverlapHandler = new OverlapClipLowerBaseQual(); if(myOverlapHandler == NULL) { usage(); inputParameters.Status(); std::cerr << "Failed to allocate the overlap handler\n"; return(-1); } if(unmapped) { myOverlapHandler->markAsUnmapped(); } // Setup the overlap handler. myOverlapHandler->keepStats(stats); if(storeOrig.Length() != 0) { myOverlapHandler->storeOrigCigar(storeOrig); } myIntExcludeFlags = excludeFlags.AsInteger(); if(params) { inputParameters.Status(); } // For each step process the file. // Open the files & read/write the sam header. SamStatus::Status runStatus = SamStatus::SUCCESS; for(int i = 1; i <= myOverlapHandler->numSteps(); i++) { // Open the file for reading. mySamHeader.resetHeader(); SamFile samIn(inFile, SamFile::READ, &mySamHeader); SamFile* samOutPtr = NULL; // Check if writing, if so, open the output file. if(i == myOverlapHandler->numSteps()) { samOutPtr = new SamFile(outFile, SamFile::WRITE, &mySamHeader); } if(readName) { samIn.setSortedValidation(SamFile::QUERY_NAME); runStatus = handleSortedByReadName(samIn, samOutPtr); } else { // Coordinate sorted, so work with the pools. samIn.setSortedValidation(SamFile::COORDINATE); myPool.setMaxAllocatedRecs(poolSize); // Reset the number of failures myNumMateFailures = 0; myNumPoolFail = 0; myNumPoolFailNoHandle = 0; myNumPoolFailHandled = 0; myNumOutOfOrder = 0; // Run by coordinate if(samOutPtr != NULL) { // Setup the output buffer for writing. SamCoordOutput outputBuffer(myPool); outputBuffer.setOutputFile(samOutPtr, &mySamHeader); runStatus = handleSortedByCoord(samIn, &outputBuffer); // Cleanup the output buffer. if(!outputBuffer.flushAll()) { std::cerr << "ERROR: Failed to flush the output buffer\n"; runStatus = SamStatus::FAIL_IO; } } else { runStatus = handleSortedByCoord(samIn, NULL); } } if(runStatus != SamStatus::SUCCESS) { break; } // Close the input file, it will be reopened if there are // multiple steps. samIn.Close(); if(samOutPtr != NULL) { samOutPtr->Close(); delete samOutPtr; samOutPtr = NULL; } } // Done processing. // Print Stats myOverlapHandler->printStats(); if(myNumMateFailures != 0) { std::cerr << "WARNING: did not find expected overlapping mates for " << myNumMateFailures << " records." << std::endl; } if(myNumPoolFail != 0) { // Had to skip clipping some records due to running out of // memory and not being able to wait for the mate. std::cerr << "WARNING: " << myNumPoolFail << " record pool failures\n"; if(myNumPoolFailNoHandle != 0) { std::cerr << "Due to hitting the max record poolSize, skipped handling " << myNumPoolFailNoHandle << " records." << std::endl; } if(myNumPoolFailHandled != 0) { std::cerr << "Due to hitting the max record poolSize, default handled " << myNumPoolFailHandled << " records." << std::endl; } if(myNumOutOfOrder != 0) { std::cerr << "WARNING: Resulting File out of Order by " << myNumOutOfOrder << " records.\n"; } } if(runStatus == SamStatus::SUCCESS) { if(myNumPoolFail == 0) { std::cerr << "Completed ClipOverlap Successfully.\n"; } else { runStatus = SamStatus::NO_MORE_RECS; std::cerr << "Completed ClipOverlap with WARNINGS.\n"; } } else { std::cerr << "Failed to complete ClipOverlap.\n"; } return(runStatus); }
template<> void Add(String& value) { unsigned short size = unsigned short(value.Length()); memcpy(mBuffer + mSize, value.Str(), size); mSize += size; mBuffer[mSize++] = 0; }
void CSFunctionWriter::WriteNativeFunction(String& source) { JSBClass* klass = function_->GetClass(); JSBPackage* package = klass->GetPackage(); String fname = function_->IsConstructor() ? "Constructor" : function_->GetName(); String returnType; String functionSig = CSTypeHelper::GetNativeFunctionSignature(function_, returnType); String line; line = ToString("ATOMIC_EXPORT_API %s %s\n", returnType.CString(), functionSig.CString()); source += IndentLine(line); source += IndentLine("{\n"); Indent(); source += "\n"; bool returnValue = false; bool sharedPtrReturn = false; String returnStatement; if (returnType == "const char*") { returnValue = true; source += IndentLine("static String returnValue;\n"); returnStatement = "returnValue = "; } else if (function_->GetReturnClass() && function_->GetReturnClass()->IsNumberArray()) { returnStatement = "*returnValue = "; } else if (function_->GetReturnClass() && function_->GetReturnType()->isSharedPtr_) { returnStatement = ToString("SharedPtr<%s> returnValue = ", function_->GetReturnClass()->GetNativeName().CString()); sharedPtrReturn = true; } else { if (returnType != "void") { returnStatement = "return "; } } String callSig; GenNativeCallParameters(callSig); if (!function_->isConstructor_) line = ToString("%sself->%s(%s);\n", returnStatement.CString(), function_->GetName().CString(), callSig.CString()); else { if (klass->IsAbstract()) { line = "return 0; // Abstract Class\n"; } else if (klass->IsObject()) { if (callSig.Length()) line = ToString("return new %s(NETCore::GetContext(), %s);\n", klass->GetNativeName().CString(), callSig.CString()); else line = ToString("return new %s(NETCore::GetContext());\n", klass->GetNativeName().CString()); } else { line = ToString("return new %s(%s);\n", klass->GetNativeName().CString(), callSig.CString()); } } source += IndentLine(line); if (sharedPtrReturn) { source += IndentLine("returnValue->AddRef();\n"); source += IndentLine("return returnValue;\n"); } else if (returnType == "const char*") { source += IndentLine("return returnValue.CString();\n"); } Dedent(); source += IndentLine("}\n"); source += "\n"; }
void __fastcall TMDIChild::actWriteExecute(TObject *Sender) { if(tvParseTree->Selected == NULL) return; ParseTreeNode * curParseTree = (ParseTreeNode *)tvParseTree->Selected->Data; if(curParseTree == NULL) { return; } ClassData * curClass = GetCurParseClass(); if(curClass == NULL) return; tagSelRect selRect; if(GetTreeSelRect(selRect) == false) return; String type = curParseTree->GetClassMember()->GetType(); if(IsNormalType(type) == false) { ShowMessage("只能改变普通变量的值"); return; } String value = curParseTree->GetParseResult(); if(InputQuery("输入值", "输入值", value) == false) return; // m_HexEditor->BeginUpdate(); char *pointer = m_HexEditor->GetFastPointer(0, m_HexEditor->DataSize); int dataSize = m_HexEditor->DataSize; int pos = selRect.SelStart; int nodeSize = m_ParseEngine->GetSize(type, pointer, dataSize, pos); int childCount = curParseTree->GetClassMember()->GetArrayVar().ToIntDef(0); int curSize = 0; for(int i=0; i<m_ParseTree->GetParseTreeNodeCount(); i++) { ParseTreeNode * curTreeNode = m_ParseTree->GetParseTreeNode(i); if(curTreeNode == curParseTree) break; int curChildCount = curTreeNode->GetClassMember()->GetArrayVar().ToIntDef(0); if(curChildCount == 0) curChildCount = 1; curSize += curChildCount * m_ParseEngine->GetSize( curTreeNode->GetClassMember()->GetType(), pointer, dataSize, pos); } pos = m_LastPos + curSize; if(childCount == 0) childCount = 1; nodeSize *= childCount; //插入数据 if(pos + nodeSize > dataSize) { String buffer; buffer.SetLength(pos + nodeSize - dataSize); memset(buffer.c_str(), '\0', buffer.Length()); m_HexEditor->InsertBuffer(AnsiString(buffer).c_str(), buffer.Length(), selRect.SelStart, "insert", false); } pointer = m_HexEditor->GetFastPointer(0, m_HexEditor->DataSize); // String setEmpty; // setEmpty.SetLength(nodeSize); // int oldPos = pos; // WriteBuf(pointer, oldPos, setEmpty.c_str(), setEmpty.Length()); if(type == "char") { WriteBuf(pointer, pos, value.c_str(), value.Length()); } else { int iResult = value.ToIntDef(0); WriteBuf(pointer, pos, &iResult, sizeof(iResult)); } m_HexEditor->SelStart = m_LastPos; ParseData(false); // m_HexEditor->EndUpdate(); }
void CSPackageWriter::GenerateNativeHeader() { String source = "// This file was autogenerated by AtomicTool, changes will be lost\n\n"; source += "#pragma once\n\nnamespace Atomic\n{\n}\n"; /* if (package_->name_ != "Atomic") { source += "#include \"../../Atomic/Native/CSPackageAtomic.h\"\n"; source += "using namespace Atomic;\n"; } // enum includes PODVector<JSBHeader*> enumHeaders; for (unsigned i = 0; i < package_->modules_.Size(); i++) { Vector<SharedPtr<JSBEnum>> enums = package_->modules_[i]->GetEnums(); for (unsigned j = 0; j < enums.Size(); j++) { JSBHeader* header = enums[j]->GetHeader(); if (!enumHeaders.Contains(header)) enumHeaders.Push(header); } } for (unsigned i = 0; i < enumHeaders.Size(); i++) { JSBHeader* header = enumHeaders[i]; String headerPath = GetPath(header->GetFilePath()); String headerfile = GetFileNameAndExtension(header->GetFilePath()); JSBind* jsbind = header->GetSubsystem<JSBind>(); headerPath.Replace(jsbind->GetSourceRootFolder() + "Source/", ""); source.AppendWithFormat("#include <%s%s>\n", headerPath.CString(), headerfile.CString()); } // forward declarations of package classes source += ToString("namespace %s\n{\n\n", package_->GetNamespace().CString()); Indent(); PODVector<JSBClass*>& allClasses = package_->GetAllClasses(); for (unsigned i = 0; i < allClasses.Size(); i++) { JSBClass* cls = allClasses[i]; source += IndentLine(ToString("class %s;\n", cls->GetNativeName().CString())); } Dedent(); source += "\n}\n"; */ JSBind* jsbind = package_->GetSubsystem<JSBind>(); String filepath = jsbind->GetDestNativeFolder() + "/CSPackage" + package_->name_ + ".h"; File file(package_->GetContext()); file.Open(filepath, FILE_WRITE); file.Write(source.CString(), source.Length()); file.Close(); }
void Run(const Vector<String>& arguments) { if (arguments.Size() < 2) { ErrorExit( "Usage: OgreImporter <input file> <output file> [options]\n\n" "Options:\n" "-l Output a material list file\n" "-na Do not output animations\n" "-nm Do not output morphs\n" "-r Output only rotations from animations\n" "-s Split each submesh into own vertex buffer\n" "-t Generate tangents\n" ); } bool generateTangents = false; bool splitSubMeshes = false; bool exportAnimations = true; bool exportMorphs = true; bool rotationsOnly = false; bool saveMaterialList = false; if (arguments.Size() > 2) { for (unsigned i = 2; i < arguments.Size(); ++i) { if (arguments[i].Length() > 1 && arguments[i][0] == '-') { String argument = arguments[i].Substring(1).ToLower(); if (argument == "l") saveMaterialList = true; else if (argument == "r") rotationsOnly = true; else if (argument == "s") splitSubMeshes = true; else if (argument == "t") generateTangents = true; else if (argument.Length() == 2 && argument[0] == 'n') { switch (tolower(argument[1])) { case 'a': exportAnimations = false; break; case 'm': exportMorphs = false; break; } break; } } } } LoadMesh(arguments[0], generateTangents, splitSubMeshes, exportMorphs); WriteOutput(arguments[1], exportAnimations, rotationsOnly, saveMaterialList); PrintLine("Finished"); }
int WriteRegion::execute(int argc, char **argv) { // Extract command line arguments. String inFile = ""; String outFile = ""; String indexFile = ""; String readName = ""; String bed = ""; myStart = UNSPECIFIED_INT; myEnd = UNSPECIFIED_INT; myPrevStart = UNSPECIFIED_INT; myPrevEnd = UNSPECIFIED_INT; myRefID = UNSET_REF; myRefName.Clear(); myPrevRefName.Clear(); myBedRefID = SamReferenceInfo::NO_REF_ID; bool lshift = false; bool noeof = false; bool params = false; myWithinReg = false; myWroteReg = false; ParameterList inputParameters; BEGIN_LONG_PARAMETERS(longParameterList) LONG_PARAMETER_GROUP("Required Parameters") LONG_STRINGPARAMETER("in", &inFile) LONG_STRINGPARAMETER("out", &outFile) LONG_PARAMETER_GROUP("Optional Region Parameters") LONG_STRINGPARAMETER("bamIndex", &indexFile) LONG_STRINGPARAMETER("refName", &myRefName) LONG_INTPARAMETER("refID", &myRefID) LONG_INTPARAMETER("start", &myStart) LONG_INTPARAMETER("end", &myEnd) LONG_STRINGPARAMETER("bed", &bed) LONG_PARAMETER("withinReg", &myWithinReg) LONG_STRINGPARAMETER("readName", &readName) LONG_PARAMETER_GROUP("Optional Other Parameters") LONG_PARAMETER("lshift", &lshift) LONG_PARAMETER("noeof", &noeof) LONG_PARAMETER("params", ¶ms) END_LONG_PARAMETERS(); inputParameters.Add(new LongParameters ("Input Parameters", longParameterList)); inputParameters.Read(argc-1, &(argv[1])); // If no eof block is required for a bgzf file, set the bgzf file type to // not look for it. if(noeof) { // Set that the eof block is not required. BgzfFileType::setRequireEofBlock(false); } // Check to see if the in file was specified, if not, report an error. if(inFile == "") { usage(); // mandatory argument was not specified. inputParameters.Status(); std::cerr << "Missing mandatory argument: --in" << std::endl; return(-1); } if(outFile == "") { usage(); // mandatory argument was not specified. inputParameters.Status(); std::cerr << "Missing mandatory argument: --out" << std::endl; return(-1); } if(indexFile == "") { // In file was not specified, so set it to the in file // + ".bai" indexFile = inFile + ".bai"; } if(myRefID != UNSET_REF && myRefName.Length() != 0) { std::cerr << "Can't specify both refID and refName" << std::endl; inputParameters.Status(); return(-1); } if(myRefID != UNSET_REF && bed.Length() != 0) { std::cerr << "Can't specify both refID and bed" << std::endl; inputParameters.Status(); return(-1); } if(myRefName.Length() != 0 && bed.Length() != 0) { std::cerr << "Can't specify both refName and bed" << std::endl; inputParameters.Status(); return(-1); } if(!bed.IsEmpty()) { myBedFile = ifopen(bed, "r"); } if(params) { inputParameters.Status(); } // Open the file for reading. mySamIn.OpenForRead(inFile); // Open the output file for writing. SamFile samOut; samOut.OpenForWrite(outFile); // Open the bam index file for reading if a region was specified. if((myRefName.Length() != 0) || (myRefID != UNSET_REF) || (myBedFile != NULL)) { mySamIn.ReadBamIndex(indexFile); } // Read & write the sam header. mySamIn.ReadHeader(mySamHeader); samOut.WriteHeader(mySamHeader); // Read the sam records. SamRecord samRecord; // Track the status. int numSectionRecords = 0; // Set returnStatus to success. It will be changed // to the failure reason if any of the writes fail. SamStatus::Status returnStatus = SamStatus::SUCCESS; while(getNextSection()) { // Keep reading records until they aren't anymore. while(mySamIn.ReadRecord(mySamHeader, samRecord)) { if(!readName.IsEmpty()) { // Check for readname. if(strcmp(samRecord.getReadName(), readName.c_str()) != 0) { // not a matching read name, so continue to the next record. continue; } } // Check to see if the read has already been processed. if(myPrevEnd != UNSPECIFIED_INT) { // Because we already know that the bed was sorted, // we know that the previous section started before // this one, so if the previous end is greater than // this record's end position we know that it // was already written in the previous section. // Note: can't be equal to the previous end since // the end range was exclusive, while // get0BasedAlignmentEnd is inclusive. // myPrevEnd is reset by getNextSection when a new // chromosome is hit. if(samRecord.get0BasedAlignmentEnd() < myPrevEnd) { // This record was already written. continue; } } // Shift left if applicable. if(lshift) { samRecord.shiftIndelsLeft(); } // Successfully read a record from the file, so write it. samOut.WriteRecord(mySamHeader, samRecord); ++numSectionRecords; } myWroteReg = true; } if(myBedFile != NULL) { ifclose(myBedFile); } std::cerr << "Wrote " << outFile << " with " << numSectionRecords << " records.\n"; return(returnStatus); }
void NETBuildSystem::HandleToolUpdate(StringHash eventType, VariantMap& eventData) { if (curBuild_.Null() && !builds_.Size()) return; if (curBuild_.Null()) { // kick off a new build curBuild_ = builds_.Front(); builds_.PopFront(); FileSystem* fileSystem = GetSubsystem<FileSystem>(); // Ensure solution still exists if (!fileSystem->FileExists(curBuild_->solutionPath_)) { CurrentBuildError(ToString("Solution does not exist(%s)", curBuild_->solutionPath_.CString())); return; } String solutionPath = curBuild_->solutionPath_; String ext = GetExtension(solutionPath); bool requiresNuGet = true; if (ext == ".sln") { // TODO: handle projects that require nuget requiresNuGet = false; if (!fileSystem->FileExists(solutionPath)) { CurrentBuildError(ToString("Generated solution does not exist (%s : %s)", curBuild_->solutionPath_.CString(), solutionPath.CString())); return; } } else if (ext == ".json") { SharedPtr<NETProjectGen> gen(new NETProjectGen(context_)); gen->SetSupportedPlatforms(curBuild_->platforms_); gen->SetRewriteSolution(true); if (!gen->LoadJSONProject(solutionPath)) { CurrentBuildError(ToString("Error loading project (%s)", solutionPath.CString())); return; } if (!gen->Generate()) { CurrentBuildError(ToString("Error generating project (%s)", solutionPath.CString())); return; } solutionPath = gen->GetSolution()->GetOutputFilename(); requiresNuGet = gen->GetRequiresNuGet(); if (!fileSystem->FileExists(solutionPath)) { CurrentBuildError(ToString("Generated solution does not exist (%s : %s)", curBuild_->solutionPath_.CString(), solutionPath.CString())); return; } } ToolEnvironment* tenv = GetSubsystem<ToolEnvironment>(); const String& nugetBinary = tenv->GetAtomicNETNuGetBinary(); if (requiresNuGet && !fileSystem->FileExists(nugetBinary)) { CurrentBuildError(ToString("NuGet binary is missing (%s)", nugetBinary.CString())); return; } StringVector stringVector; String platforms; StringVector processedPlatforms; String configs; for (unsigned i = 0; i < curBuild_->configurations_.Size(); i++) { stringVector.Push(ToString("/p:Configuration=%s", curBuild_->configurations_[i].CString())); } configs = String::Joined(stringVector, " "); stringVector.Clear(); for (unsigned i = 0; i < curBuild_->platforms_.Size(); i++) { // map platform String platform = curBuild_->platforms_[i]; if (platform == "windows" || platform == "macosx" || platform == "linux") { ATOMIC_LOGINFOF("Platform \"%s\" mapped to \"desktop\"", platform.CString()); platform = "desktop"; } if (processedPlatforms.Contains(platform)) { ATOMIC_LOGWARNINGF("Platform \"%s\" is duplicated, skipping", platform.CString()); continue; } processedPlatforms.Push(platform); if (platform == "desktop" || platform == "android") { platform = "\"Any CPU\""; } else if (platform == "ios") { platform = "\"Any CPU\""; // TODO // platform = "iPhone"; } else { ATOMIC_LOGERRORF("Unknown platform: %s, skipping", platform.CString()); continue; } platform = ToString("/p:Platform=%s", platform.CString()); if (stringVector.Contains(platform)) { // This can happen when specifying Desktop + Android for example continue; } stringVector.Push(platform); } platforms = String::Joined(stringVector, " "); stringVector.Clear(); Vector<String> args; #ifdef ATOMIC_PLATFORM_WINDOWS String cmdToolsPath = Poco::Environment::get("VS140COMNTOOLS", "").c_str(); if (!cmdToolsPath.Length()) { CurrentBuildError("VS140COMNTOOLS environment variable not found, cannot proceed"); return; } if (!cmdToolsPath.EndsWith("\\")) { cmdToolsPath += "\\"; } String msbuildcmd = ToString("%sVsMSBuildCmd.bat", cmdToolsPath.CString()); String cmd = "cmd"; args.Push("/A"); args.Push("/C"); // vcvars bat String compile = ToString("\"\"%s\" ", msbuildcmd.CString()); if (requiresNuGet) { compile += ToString("&& \"%s\" restore \"%s\" ", nugetBinary.CString(), solutionPath.CString()); } compile += ToString("&& msbuild \"%s\" %s %s", solutionPath.CString(), platforms.CString(), configs.CString()); if (curBuild_->targets_.Size()) { StringVector targets; for (unsigned i = 0; i < curBuild_->targets_.Size(); i++) { const char* tname = curBuild_->targets_[i].CString(); targets.Push(ToString("/t:\"%s:Rebuild\"", tname)); } compile += " " + String::Joined(targets, " "); } // close out quote compile += "\""; args.Push(compile); #else String compile; String cmd = "bash"; args.Push("-c"); String xbuildBinary = tenv->GetMonoExecutableDir() + "xbuild"; if (requiresNuGet) { #ifdef ATOMIC_PLATFORM_OSX compile += ToString("\"%s\" restore \"%s\" && ", nugetBinary.CString(), solutionPath.CString()); #else compile += ToString("mono \"%s\" restore \"%s\" && ", nugetBinary.CString(), solutionPath.CString()); #endif } compile += ToString("\"%s\" \"%s\" %s %s", xbuildBinary.CString(), solutionPath.CString(), platforms.CString(), configs.CString()); if (curBuild_->targets_.Size()) { StringVector targets; for (unsigned i = 0; i < curBuild_->targets_.Size(); i++) { const char* tname = curBuild_->targets_[i].CString(); targets.Push(ToString("%s:Rebuild", tname)); } compile += " /target:\"" + String::Joined(targets, ";") + "\""; } args.Push(compile); #endif curBuild_->allArgs_.Join(args, " "); SubprocessSystem* subs = GetSubsystem<SubprocessSystem>(); Subprocess* subprocess = nullptr; ATOMIC_LOGINFOF("%s : %s", cmd.CString(), curBuild_->allArgs_.CString()); try { subprocess = subs->Launch(cmd, args, ""); } catch (Poco::SystemException) { subprocess = nullptr; } if (!subprocess) { CurrentBuildError(ToString("NETCompile::Compile - Unable to launch MSBuild subprocess\n%s", curBuild_->allArgs_.CString())); return; } VariantMap buildBeginEventData; buildBeginEventData[NETBuildBegin::P_BUILD] = curBuild_; SendEvent(E_NETBUILDBEGIN, buildBeginEventData); SubscribeToEvent(subprocess, E_SUBPROCESSCOMPLETE, ATOMIC_HANDLER(NETBuildSystem, HandleCompileProcessComplete)); SubscribeToEvent(subprocess, E_SUBPROCESSOUTPUT, ATOMIC_HANDLER(NETBuildSystem, HandleSubprocessOutput)); curBuild_->status_ = NETBUILD_BUILDING; } }
void URLEncoderTest::EncodeDecodeTest() { StartTrace(URLEncoderTest.EncodeDecodeTest); URLEncoder encoder("encoder"); int i; String EmptySt, expected; String EncodedString; String DecodedString; String OriginalString; // Test 1: // checkif all HEX-values can be en-/decoded // check for identity of original and decoded string // check the lengths // setup original for ( i = 0; i < 256; i++ ) { OriginalString.Append( (char)i ); } // encode decode with URLEncoder // and changes '+' to ' ' in decoded string encoder.DoEncode( EncodedString, OriginalString); encoder.DoDecode( DecodedString, EncodedString); expected = OriginalString; // '+' gets converted to a space also expected.PutAt(long('+'), ' '); // assert strings are equal assertEqualRaw(expected, DecodedString); assertEqual( expected.Length(), DecodedString.Length() ); assertEqual( expected, DecodedString ); assertEqual( expected.Length(), DecodedString.Length() ); // Test 3 // reset strings OriginalString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; EncodedString = EmptySt; DecodedString = EmptySt; // encode decode with URLEncoder encoder.DoEncode( EncodedString, OriginalString); encoder.DoDecode( DecodedString, EncodedString ); // check whether the Strings are identical assertCharPtrEqual( OriginalString, DecodedString ); t_assert( OriginalString == DecodedString ); assertCharPtrEqual( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", EncodedString ); //Test 4 // Only Unprintable Chars OriginalString = EmptySt; EncodedString = EmptySt; DecodedString = EmptySt; for ( i = 0; i < 10; i++ ) { OriginalString.Append( (char)i ); } // encode decode with URLEncoder encoder.DoEncode( EncodedString, OriginalString); encoder.DoDecode( DecodedString, EncodedString ); // check whether the Strings are identical t_assert( (memcmp( (const char *)OriginalString, (const char *)DecodedString, OriginalString.Length() ) == 0) ); t_assert( OriginalString.Length() == DecodedString.Length() ); assertCharPtrEqual( OriginalString, DecodedString ); t_assert( OriginalString == DecodedString ); assertCharPtrEqual( "%00%01%02%03%04%05%06%07%08%09", EncodedString ); // One Printable Char, unscrambled OriginalString = "M"; EncodedString = EmptySt; DecodedString = EmptySt; // check whether the Strings are identical encoder.DoEncode( EncodedString, OriginalString); encoder.DoDecode( DecodedString, EncodedString ); assertCharPtrEqual( OriginalString, DecodedString ); t_assert( OriginalString == DecodedString ); assertCharPtrEqual( "M", EncodedString ); // One Unprintable Char, unscrambled OriginalString = EmptySt; OriginalString.Append( (char)5 ); OriginalString = OriginalString; EncodedString = EmptySt; DecodedString = EmptySt; encoder.DoEncode( EncodedString, OriginalString); encoder.DoDecode( DecodedString, EncodedString ); assertCharPtrEqual( OriginalString, DecodedString ); t_assert( OriginalString == DecodedString ); // String::IntPrintOn: 05 -> \x05 // coast::urlutils::urlEncode: \x05 -> %5Cx05 // coast::urlutils::urlEncode: %5Cx05 -> %255Cx05 assertCharPtrEqual( "%05", EncodedString ); // Only Printable Chars, scrambled OriginalString = "ABC"; EncodedString = EmptySt; DecodedString = EmptySt; encoder.DoEncode( EncodedString, OriginalString); encoder.DoDecode( DecodedString, EncodedString ); assertCharPtrEqual( OriginalString, DecodedString ); t_assert( OriginalString == DecodedString ); // w\"ABC\" assertCharPtrEqual( "ABC", EncodedString ); // a particularly nasty sequence of non-printables and printables OriginalString = "Anfang%252B+%2BEnde"; EncodedString = EmptySt; DecodedString = EmptySt; encoder.DoEncode( EncodedString, OriginalString); assertEqual( "Anfang%25252B+%252BEnde", EncodedString); encoder.DoDecode( DecodedString, EncodedString ); assertEqual( "Anfang%252B %2BEnde", DecodedString); // Only Unprintable Chars, scrambled OriginalString = EmptySt; for ( i = 0; i < 3; i++ ) { OriginalString.Append( (char)i ); } EncodedString = EmptySt; DecodedString = EmptySt; encoder.DoEncode( EncodedString, OriginalString); encoder.DoDecode( DecodedString, EncodedString ); assertCharPtrEqual( OriginalString, DecodedString ); t_assert( OriginalString == DecodedString ); assertCharPtrEqual( "%00%01%02", EncodedString ); // One Printable Char, scrambled OriginalString = "M"; OriginalString = OriginalString; EncodedString = EmptySt; DecodedString = EmptySt; encoder.DoEncode( EncodedString, OriginalString); encoder.DoDecode( DecodedString, EncodedString ); assertCharPtrEqual( OriginalString, DecodedString ); t_assert( OriginalString == DecodedString ); assertCharPtrEqual( "M", EncodedString ); // 1 2 3 4 5 6 // 0123456789012345678901234567890123456789012345678901234567890123456789 // ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-$ // One Unprintable Char, scrambled OriginalString = EmptySt; OriginalString.Append( (char)5 ); OriginalString = OriginalString; EncodedString = EmptySt; DecodedString = EmptySt; encoder.DoEncode( EncodedString, OriginalString); encoder.DoDecode( DecodedString, EncodedString ); assertCharPtrEqual( OriginalString, DecodedString ); t_assert( OriginalString == DecodedString ); assertCharPtrEqual( "%05", EncodedString ); }
void WriteString(const String& value) { std::uint32_t len = value.Length(); WriteBuffer(&len, sizeof(len)); WriteBuffer((void*)value.Data(), len*sizeof(wchar_t)); }
void OBS::StartRecording() { if(bRecording) return; int networkMode = AppConfig->GetInt(TEXT("Publish"), TEXT("Mode"), 2); bWriteToFile = networkMode == 1 || AppConfig->GetInt(TEXT("Publish"), TEXT("SaveToFile")) != 0; String strOutputFile = AppConfig->GetString(TEXT("Publish"), TEXT("SavePath")); strOutputFile.FindReplace(TEXT("\\"), TEXT("/")); // Don't request a keyframe while everything is starting up for the first time if(!bStartingUp) videoEncoder->RequestKeyframe(); if (bWriteToFile) { OSFindData ofd; HANDLE hFind = NULL; bool bUseDateTimeName = true; bool bOverwrite = GlobalConfig->GetInt(L"General", L"OverwriteRecordings", false) != 0; if(!bOverwrite && (hFind = OSFindFirstFile(strOutputFile, ofd))) { String strFileExtension = GetPathExtension(strOutputFile); String strFileWithoutExtension = GetPathWithoutExtension(strOutputFile); if(strFileExtension.IsValid() && !ofd.bDirectory) { String strNewFilePath; UINT curFile = 0; do { strNewFilePath.Clear() << strFileWithoutExtension << TEXT(" (") << FormattedString(TEXT("%02u"), ++curFile) << TEXT(").") << strFileExtension; } while(OSFileExists(strNewFilePath)); strOutputFile = strNewFilePath; bUseDateTimeName = false; } if(ofd.bDirectory) strOutputFile.AppendChar('/'); OSFindClose(hFind); } if(bUseDateTimeName) { String strFileName = GetPathFileName(strOutputFile); if(!strFileName.IsValid() || !IsSafeFilename(strFileName)) { SYSTEMTIME st; GetLocalTime(&st); String strDirectory = GetPathDirectory(strOutputFile); String file = strOutputFile.Right(strOutputFile.Length() - strDirectory.Length()); String extension; if (!file.IsEmpty()) extension = GetPathExtension(file.Array()); if(extension.IsEmpty()) extension = TEXT("mp4"); strOutputFile = FormattedString(TEXT("%s/%u-%02u-%02u-%02u%02u-%02u.%s"), strDirectory.Array(), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, extension.Array()); } } } if(!bTestStream && bWriteToFile && strOutputFile.IsValid()) { String strFileExtension = GetPathExtension(strOutputFile); if(strFileExtension.CompareI(TEXT("flv"))) fileStream = CreateFLVFileStream(strOutputFile); else if(strFileExtension.CompareI(TEXT("mp4"))) fileStream = CreateMP4FileStream(strOutputFile); if(!fileStream) { Log(TEXT("Warning - OBSCapture::Start: Unable to create the file stream. Check the file path in Broadcast Settings.")); MessageBox(hwndMain, Str("Capture.Start.FileStream.Warning"), Str("Capture.Start.FileStream.WarningCaption"), MB_OK | MB_ICONWARNING); bRecording = false; } else { EnableWindow(GetDlgItem(hwndMain, ID_TOGGLERECORDING), TRUE); SetWindowText(GetDlgItem(hwndMain, ID_TOGGLERECORDING), Str("MainWindow.StopRecording")); bRecording = true; } } }
/// Actual thread function void GameEconomicServerClientConsole::ThreadFunction() { /// Get network subsystem Network* network = GetSubsystem<Network>(); bool success=false; bool lineEntered=false; /// turn on inteface bool isActiveFlag=true; /// Urho related variables String PromptInput; String ConsoleInputLine; Connection* serverConnection; /// Show prompt ShowPrompt(); /// Clear prompt input PromptInput.Clear(); ConsoleInputLine.Clear(); /// loop do { ConsoleInputLine.Clear(); /// Get input from the user ConsoleInputLine = GetConsoleInput(); /// append if its not empty if(ConsoleInputLine.Length()>0) { /// prompt PromptInput.Append(ConsoleInputLine); lineEntered=true; } /// test if there was input if(lineEntered==true&&PromptInput.Empty()) { cout << "Invalid command.." << endl; /// Clear prompt input PromptInput.Clear(); ///Display new prompt ShowPrompt(); lineEntered=false; } else if (lineEntered==true) { /// Trim input to clean up String CleanedPromptInput = PromptInput.Trimmed(); /// Test Commands if(CleanedPromptInput==String("connect")) { Connect(NetworkConfiguration); } else if(CleanedPromptInput==String("quit")) { /// Terminate program forced exit(0); } else { /// if server connection and serverConnection if(serverconnection&&serverconnection) { /// Clean SendMessage(CleanedPromptInput); } } /// Clear prompt input PromptInput.Clear(); ///Display new prompt ShowPrompt(); lineEntered=false; } } while(isActiveFlag); return; }
//--------------------------------------------------------------------------- int TMYIniFile::Find(String Section, String Ident, int from) { if( Section.Length() == 0 ) return -1; // Секция та-же ? if( MySameText(CurSection, Section) && from==0 ) { // Да - текущая секция CurSectionIndex if( Ident.Length() > 0 ) { if( CurParamIndex<0 ) CurParamIndex = CurSectionIndex + 1; // Предполагаем, что требуется следующий параметр else CurParamIndex++; // Предполагаем, что требуется следующий параметр } } else { CurSection = ""; CurSectionIndex = -1; CurParamIndex = -1; // Нет: ищем секцию... for(int i=from; i<list->Count; i++) { if( ! IsSectionName(list->Strings[i]) ) continue; if( MySameText( String("[" + Section + "]"), list->Strings[i]) ) { CurSection = Section; CurSectionIndex = i; if( Ident.Length() > 0 ) CurParamIndex = CurSectionIndex + 1; // Предполагаем, что требуется следующий параметр break; } } } // Секция не найдена или не надо искать параметр if( CurSectionIndex<0 || Ident.Length() == 0 ) return CurSectionIndex; // Ищем название переменной... (если это требуется) if( Ident.Length() > 0 ) { // Попробуем... if( CurParamIndex>=0 && CurParamIndex<list->Count ) if( MySameText(Ident, list->Names[CurParamIndex]) ) // == return CurParamIndex; CurParamIndex = -1; for(int i=CurSectionIndex+1; i<list->Count; i++) { // Если следующая секция - значит не нашли переменную: if( IsSectionName(list->Strings[i]) ) break; if( MySameText(Ident, list->Names[i]) ) // == { CurParamIndex = i; break; } } } return CurParamIndex; }
bool String::EndsWith(const String& str, bool caseSensitive) const { unsigned pos = FindLast(str, Length() - 1, caseSensitive); return pos != NPOS && pos == Length() - str.Length(); }
bool PropertySpecification::ParsePropertyValues(StringList& values_list, const String& values, bool split_values) const { String value; enum ParseState { VALUE, VALUE_PARENTHESIS, VALUE_QUOTE }; ParseState state = VALUE; int open_parentheses = 0; size_t character_index = 0; char previous_character = 0; while (character_index < values.Length()) { char character = values[character_index]; character_index++; switch (state) { case VALUE: { if (character == ';') { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) { values_list.push_back(value); value.Clear(); } } else if (StringUtilities::IsWhitespace(character)) { if (split_values) { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) { values_list.push_back(value); value.Clear(); } } else value.Append(character); } else if (character == '"') { if (split_values) { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) { values_list.push_back(value); value.Clear(); } state = VALUE_QUOTE; } else { value.Append(' '); state = VALUE_QUOTE; } } else if (character == '(') { open_parentheses = 1; value.Append(character); state = VALUE_PARENTHESIS; } else { value.Append(character); } } break; case VALUE_PARENTHESIS: { if (previous_character == '/') { if (character == ')' || character == '(') value.Append(character); else { value.Append('/'); value.Append(character); } } else { if (character == '(') { open_parentheses++; value.Append(character); } else if (character == ')') { open_parentheses--; value.Append(character); if (open_parentheses == 0) state = VALUE; } else if (character != '/') { value.Append(character); } } } break; case VALUE_QUOTE: { if (previous_character == '/') { if (character == '"') value.Append(character); else { value.Append('/'); value.Append(character); } } else { if (character == '"') { if (split_values) { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) { values_list.push_back(value); value.Clear(); } } else value.Append(' '); state = VALUE; } else if (character != '/') { value.Append(character); } } } } previous_character = character; } if (state == VALUE) { value = StringUtilities::StripWhitespace(value); if (value.Length() > 0) values_list.push_back(value); } return true; }
void __fastcall TMDIChild::actSendToPluginTestExecute(TObject *Sender) { TMenuItem * curItem = (TMenuItem *)Sender; tagExePlugins * exePlug = m_Plugins->At(curItem->Tag); if(exePlug == NULL) { ShowMessage("actOpenPluginExecute index Error"); return; } void * handle = FindWindow(exePlug->ClassName.c_str(), NULL); if(handle == NULL) { ShowMessage(FormatStr("没有开启%s!", exePlug->Name)); return; } if(exePlug->RecvType == 0 || exePlug->RecvType == 2) { String hexStr; if(m_HexEditor->SelCount != 0) { hexStr = m_HexEditor->SelectionAsHex; for(int i=2; i<hexStr.Length(); i+=2) { hexStr.Insert(" ", i+1); i++; } } else { tagSelRect selRect; if(GetTreeSelRect(selRect) == false) return; char *pointer = m_HexEditor->GetFastPointer(0, m_HexEditor->DataSize); int pos = selRect.SelStart; int selSize = selRect.SelLength; hexStr = BinToStr(pointer+pos, selSize); } /////////////////// COPYDATASTRUCT cds; cds.dwData = 0; cds.cbData = hexStr.Length(); cds.lpData = (void *)hexStr.c_str(); SendMessage(handle, WM_COPYDATA, 0, (long)&cds); } if(exePlug->RecvType == 1 || exePlug->RecvType == 2) { String info; if(m_ActiveFileStruct) { info = m_ActiveFileStruct->GetRemark(); } else { info = "没有描述! 干!!"; } COPYDATASTRUCT cds; cds.dwData = 1; cds.cbData = info.Length(); cds.lpData = (void *)info.c_str(); SendMessage(handle, WM_COPYDATA, 0, (long)&cds); } }
bool AliasInstaller::DoInstall(const ROAnything installerSpec, Registry *r) { StartTrace1(AliasInstaller.DoInstall, "Category: " << GetCategory()); bool installationSuccess = true; long isSz = 0L; TraceAny(installerSpec, "alias config"); // allow empty category definitions if ((installerSpec.GetType() == AnyArrayType) && ((isSz = installerSpec.GetSize()) >= 0L)) { // loop over RegisterableObjects to install aliases for (long l = 0; l < isSz; ++l) { const char *pcRegObjectName = installerSpec.SlotName(l); Trace("Installing aliases for RegisterableObject <" << NotNull(pcRegObjectName) << ">"); ROAnything a = installerSpec[l]; long sz = 0L; // we allow pre-definitions of /RegisterableObject slots without having aliases defined already if ((sz = a.GetSize()) >= 0L) { ROAnything k; for (long j = 0; j < sz && installationSuccess; ++j) { k = a[j]; // only process pure value entries, no sub-anythings // if there is a slotname given, or the type is an anything, we dont process it if ((a.SlotName(j) == NULL) && (k.GetType() != AnyArrayType)) { RegisterableObject *t = (RegisterableObject *) r->Find(pcRegObjectName); if (t) { String alias = k.AsString(); if (alias.Length()) { // clone the object with the correct name String origName; t->GetName(origName); t->SetName(alias); // installs a clone or a simple alias // depending on subclass of Registerable RegisterableObject *reg = (RegisterableObject *) t->Clone(coast::storage::Global()); Trace("\talias <" << alias << ">"); reg->Register(alias, GetCategory()); reg->Initialize(GetCategory()); t->SetName(origName); SystemLog::WriteToStderr(".", 1); } else { SYSERROR("Alias configuration error in category: " << GetCategory() << " for RegisterableObject <" << NotNull(pcRegObjectName) << ">, empty alias name!"); installationSuccess = false; } } else { SYSERROR("Alias configuration error in category: " << GetCategory() << ", can't find base RegisterableObject " << pcRegObjectName); installationSuccess = false; } } else { SYSERROR("Alias configuration error in category: " << GetCategory() << " for RegisterableObject <" << NotNull(pcRegObjectName) << ">, alias name must be a string!"); installationSuccess = false; } } } else { SYSERROR("Alias configuration error in category: " << GetCategory() << " for RegisterableObject <" << NotNull(pcRegObjectName) << ">, expected Anything!"); installationSuccess = false; } } } else { SYSERROR("Alias configuration error for category: " << GetCategory()); installationSuccess = false; } return installationSuccess; }
void HttpRequest::ThreadFunction() { String protocol = "http"; String host; String path = "/"; int port = 80; unsigned protocolEnd = url_.Find("://"); if (protocolEnd != String::NPOS) { protocol = url_.Substring(0, protocolEnd); host = url_.Substring(protocolEnd + 3); } else host = url_; unsigned pathStart = host.Find('/'); if (pathStart != String::NPOS) { path = host.Substring(pathStart); host = host.Substring(0, pathStart); } unsigned portStart = host.Find(':'); if (portStart != String::NPOS) { port = ToInt(host.Substring(portStart + 1)); host = host.Substring(0, portStart); } char errorBuffer[ERROR_BUFFER_SIZE]; memset(errorBuffer, 0, sizeof(errorBuffer)); String headersStr; for (unsigned i = 0; i < headers_.Size(); ++i) { // Trim and only add non-empty header strings String header = headers_[i].Trimmed(); if (header.Length()) headersStr += header + "\r\n"; } // Initiate the connection. This may block due to DNS query /// \todo SSL mode will not actually work unless Civetweb's SSL mode is initialized with an external SSL DLL mg_connection* connection = 0; if (postData_.Empty()) { connection = mg_download(host.CString(), port, protocol.Compare("https", false) ? 0 : 1, errorBuffer, sizeof(errorBuffer), "%s %s HTTP/1.0\r\n" "Host: %s\r\n" "%s" "\r\n", verb_.CString(), path.CString(), host.CString(), headersStr.CString()); } else { connection = mg_download(host.CString(), port, protocol.Compare("https", false) ? 0 : 1, errorBuffer, sizeof(errorBuffer), "%s %s HTTP/1.0\r\n" "Host: %s\r\n" "%s" "Content-Length: %d\r\n" "\r\n" "%s", verb_.CString(), path.CString(), host.CString(), headersStr.CString(), postData_.Length(), postData_.CString()); } { MutexLock lock(mutex_); state_ = connection ? HTTP_OPEN : HTTP_ERROR; // If no connection could be made, store the error and exit if (state_ == HTTP_ERROR) { error_ = String(&errorBuffer[0]); return; } } // Loop while should run, read data from the connection, copy to the main thread buffer if there is space while (shouldRun_) { // Read less than full buffer to be able to distinguish between full and empty ring buffer. Reading may block int bytesRead = mg_read(connection, httpReadBuffer_.Get(), READ_BUFFER_SIZE / 4); if (bytesRead <= 0) break; mutex_.Acquire(); // Wait until enough space in the main thread's ring buffer for (;;) { unsigned spaceInBuffer = READ_BUFFER_SIZE - ((writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1)); if ((int)spaceInBuffer > bytesRead || !shouldRun_) break; mutex_.Release(); Time::Sleep(5); mutex_.Acquire(); } if (!shouldRun_) { mutex_.Release(); break; } if (writePosition_ + bytesRead <= READ_BUFFER_SIZE) memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), (size_t)bytesRead); else { // Handle ring buffer wrap unsigned part1 = READ_BUFFER_SIZE - writePosition_; unsigned part2 = bytesRead - part1; memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), part1); memcpy(readBuffer_.Get(), httpReadBuffer_.Get() + part1, part2); } writePosition_ += bytesRead; writePosition_ &= READ_BUFFER_SIZE - 1; mutex_.Release(); } // Close the connection mg_close_connection(connection); { MutexLock lock(mutex_); state_ = HTTP_CLOSED; } }
void RefreshWindowList(HWND hwndCombobox, ConfigDialogData &configData) { SendMessage(hwndCombobox, CB_RESETCONTENT, 0, 0); configData.ClearData(); HWND hwndCurrent = GetWindow(GetDesktopWindow(), GW_CHILD); do { if(IsWindowVisible(hwndCurrent)) { RECT clientRect; GetClientRect(hwndCurrent, &clientRect); HWND hwndParent = GetParent(hwndCurrent); DWORD exStyles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_EXSTYLE); DWORD styles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_STYLE); if( (exStyles & WS_EX_TOOLWINDOW) == 0 && (styles & WS_CHILD) == 0 /*&& hwndParent == NULL*/) { String strWindowName; strWindowName.SetLength(GetWindowTextLength(hwndCurrent)); GetWindowText(hwndCurrent, strWindowName, strWindowName.Length()+1); bool b64bit = false; //------- DWORD processID; GetWindowThreadProcessId(hwndCurrent, &processID); if(processID == GetCurrentProcessId()) continue; TCHAR fileName[MAX_PATH+1]; scpy(fileName, TEXT("unknown")); HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if(hProcess) { DWORD dwSize = MAX_PATH; QueryFullProcessImageName(hProcess, 0, fileName, &dwSize); } else { hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if(hProcess) { CloseHandle(hProcess); } continue; } //------- String strFileName = fileName; strFileName.FindReplace(TEXT("\\"), TEXT("/")); String strText; strText << TEXT("[") << GetPathFileName(strFileName); strText << (b64bit ? TEXT("*64") : TEXT("*32")); strText << TEXT("]: ") << strWindowName; int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strText.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)hwndCurrent); String strClassName; strClassName.SetLength(256); GetClassName(hwndCurrent, strClassName.Array(), 255); strClassName.SetLength(slen(strClassName)); WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = strClassName; info.strProcess = fileName; } } } while (hwndCurrent = GetNextWindow(hwndCurrent, GW_HWNDNEXT)); }
Uri::Uri(const String& UriString, const UriKind::Type UriKind) :m_OriginalString(UriString) ,m_HostNameType(UriHostNameType::Unknown) ,m_Port(0) ,m_IsAbsolute(false) ,m_IsDefaultPort(true) ,m_IsDefaultUser(true) ,m_UserEscaped(true) ,m_IsOpaque(false) { String str; // check if the uri is completly escaped for (UInt32 i=0;i<m_OriginalString.Length();++i) if (NeedToEscapeUriChar[static_cast<UInt8>(m_OriginalString[i])]) { m_UserEscaped=false; str=Uri::EscapeUriString(UriString); break; } if (m_UserEscaped) str=m_OriginalString; // check if it's a absolute URI // absolute URI==schemename:.... if (CheckSchemeName(str)) m_IsAbsolute=true; Int32 lastEnd=0; // get scheme name if available if (m_IsAbsolute) { lastEnd=str.IndexOf(Uri::SchemeDelimiter); m_Scheme=str.SubString(0,lastEnd); } // get the scheme specific part Int32 fragmentStart=str.IndexOf(String("#",lastEnd+1)); if (fragmentStart<0) m_SchemeSpecificPart=str.SubString(lastEnd+1,str.Length()-lastEnd-1); else m_SchemeSpecificPart=str.SubString(lastEnd+1,fragmentStart-lastEnd-1); // get the fragment part if available if (fragmentStart>=0) m_Fragment=str.SubString(fragmentStart+1,str.Length()-fragmentStart-1); // check if it's a opaque URI // opaque==absolute+no '/' at start of scheme specific part if (m_IsAbsolute) if (m_SchemeSpecificPart.IndexOf("/") == -1) m_IsOpaque=true; // non opaque uri's need more parsing if (!m_IsOpaque) { // [scheme:][//authority][path][?query][#fragment] // |_________________________| lastEnd=0; // authority // The authority component is preceded by a double slash ("//") and is // terminated by the next slash ("/"), question mark ("?"), or number // sign ("#") character, or by the end of the URI. if (m_SchemeSpecificPart.StartsWith("//")) { Int32 authorityEnd=m_SchemeSpecificPart.IndexOf("/", 2); if (authorityEnd<0) authorityEnd=m_SchemeSpecificPart.IndexOf("?",2); if (authorityEnd<0) authorityEnd=m_SchemeSpecificPart.IndexOf("#",2); if (authorityEnd<0) authorityEnd=m_SchemeSpecificPart.Length(); m_Authority=m_SchemeSpecificPart.SubString(2,authorityEnd-2); lastEnd=authorityEnd; } // path // If the lastEnd point to a "/" then there is a path. if (m_SchemeSpecificPart[lastEnd]=='/' || !m_IsAbsolute) { // The path is terminated by the first question mark ("?") or // number sign ("#") character, or by the end of the URI. Int32 pathEnd=m_SchemeSpecificPart.IndexOf("?",lastEnd); if (pathEnd<0) pathEnd=m_SchemeSpecificPart.IndexOf("#",lastEnd); if (pathEnd<0) pathEnd=m_SchemeSpecificPart.Length(); m_Path=m_SchemeSpecificPart.SubString(lastEnd + 1, pathEnd - lastEnd - 1); lastEnd=pathEnd; } // query // If the lastEnd point to a "?" then there is a query. if (m_SchemeSpecificPart[lastEnd] == '?') { // The path is terminated by the first question mark ("?") or // number sign ("#") character, or by the end of the URI. Int32 queryEnd=m_SchemeSpecificPart.IndexOf("#", lastEnd); if (queryEnd<0) queryEnd=m_SchemeSpecificPart.Length(); m_Query=m_SchemeSpecificPart.SubString(lastEnd + 1, queryEnd - lastEnd - 1); lastEnd=queryEnd; } } // parse authority if (0==m_Authority.Length())//if authority is empty then it's localhost and default port { m_Host="localhost"; m_IsDefaultPort=true; m_IsDefaultUser=true; m_HostNameType=UriHostNameType::DomainName; } else { // get user info Int32 userinfoEnd=m_Authority.IndexOf("@"); if (userinfoEnd>=0) { m_IsDefaultUser=false; m_UserInfo=m_Authority.SubString(0,userinfoEnd); } else { m_IsDefaultUser=true; userinfoEnd=0; } // get hostname // If there is a ']' which indicate that there is a IPv6 then check if // the hostnameEnd don't point to a ':' of the IPv6. // Check also if hostnameEnd point to a ':' of the user info. Int32 hostnameEnd=m_Authority.LastIndexOf(":"); Int32 IPliteral=m_Authority.IndexOf("]"); if (hostnameEnd<0 || hostnameEnd<IPliteral || hostnameEnd<userinfoEnd) hostnameEnd=m_Authority.Length(); m_HostNameType=HostNameType(m_Authority.SubString(userinfoEnd+1,hostnameEnd-userinfoEnd-1)); m_Host=m_Authority.SubString(userinfoEnd + 1,hostnameEnd-userinfoEnd - 1); // get port if (static_cast<UInt32>(hostnameEnd)<m_Authority.Length()) { m_IsDefaultPort=false; Convert::ToInt32(m_Authority.SubString(hostnameEnd+1,m_Authority.Length()-hostnameEnd-1), m_Port); } } }
ColorSelector( const String &tag, const XMLAttributes &attr ) : ElementFormControl( tag ), cvar( 0 ) { String cvarName = attr.Get<String>( "cvar", "" ); if( cvarName.Length() ) cvar = trap::Cvar_Get( cvarName.CString(), "", 0 ); }
uint32 Font::GetTextWidth(const String& text) const { return this->GetHeight() * text.Length(); }
void LuaScriptInstance::OnGetAttribute(const AttributeInfo& attr, Variant& dest) const { if (attr.ptr_ != (void*)0xffffffff) { Serializable::OnGetAttribute(attr, dest); return; } if (scriptObjectRef_ == LUA_REFNIL) return; String name = attr.name_; unsigned length = name.Length(); if (name.Back() == '_') length -= 1; int top = lua_gettop(luaState_); String functionName = String("Get") + name.Substring(0, 1).ToUpper() + name.Substring(1, length - 1); WeakPtr<LuaFunction> function = GetScriptObjectFunction(functionName); // If get function exist if (function) { if (function->BeginCall(this)) function->EndCall(1); } else { lua_rawgeti(luaState_, LUA_REGISTRYINDEX, scriptObjectRef_); lua_pushstring(luaState_, name.CString()); lua_gettable(luaState_, -2); } switch (attr.type_) { case VAR_BOOL: dest = lua_toboolean(luaState_, -1) != 0; break; case VAR_FLOAT: dest = (float)lua_tonumber(luaState_, -1); break; case VAR_STRING: dest = tolua_tourho3dstring(luaState_, -1, ""); break; case VAR_VECTOR2: dest = *((Vector2*)tolua_tousertype(luaState_, -1, 0)); break; case VAR_VECTOR3: dest = *((Vector3*)tolua_tousertype(luaState_, -1, 0)); break; case VAR_VECTOR4: dest = *((Vector4*)tolua_tousertype(luaState_, -1, 0)); break; case VAR_QUATERNION: dest = *((Quaternion*)tolua_tousertype(luaState_, -1, 0)); break; case VAR_COLOR: dest = *((Color*)tolua_tousertype(luaState_, -1, 0)); break; case VAR_INTRECT: dest = *((IntRect*)tolua_tousertype(luaState_, -1, 0)); break; case VAR_INTVECTOR2: dest = *((IntVector2*)tolua_tousertype(luaState_, -1, 0)); break; default: LOGERROR("Unsupported data type"); return; } lua_settop(luaState_, top); }
void CSFunctionWriter::WriteNativeFunction(String& source) { JSBClass* klass = function_->GetClass(); JSBPackage* package = klass->GetPackage(); String fname = function_->IsConstructor() ? "Constructor" : function_->GetName(); String returnType; String functionSig = CSTypeHelper::GetNativeFunctionSignature(function_, returnType); String line; line = ToString("ATOMIC_EXPORT_API %s %s\n", returnType.CString(), functionSig.CString()); source += IndentLine(line); source += IndentLine("{\n"); Indent(); source += "\n"; // vector marshal bool hasVectorMarshal = false; const Vector<JSBFunctionType*>& fparams = function_->GetParameters(); for (unsigned i = 0; i < fparams.Size(); i++) { JSBFunctionType* ftype = fparams[i]; // Interface JSBClass* interface = 0; if (ftype->type_->asClassType() && ftype->type_->asClassType()->class_->IsInterface()) { // We need to downcast to the interface // TODO: this assumes Object* is in hierarchy, how do we validate this? interface = ftype->type_->asClassType()->class_; line = ToString("%s = dynamic_cast<%s*>((Object*)%s);\n", ftype->name_.CString(), interface->GetNativeName().CString(), ftype->name_.CString()); source += IndentLine(line); } // Vector JSBVectorType* vtype = ftype->type_->asVectorType(); if (!vtype) continue; JSBClassType* classType = vtype->vectorType_->asClassType(); if (!classType) continue; String className = classType->class_->GetName(); String vectorMarshal; hasVectorMarshal = true; if (vtype->isPODVector_) { const String& pname = ftype->name_; source += IndentLine(ToString("PODVector<%s*> %s__vector;\n", className.CString(), pname.CString())); source += IndentLine(ToString("if (%s) %s->AdaptToVector<%s*>(%s__vector);\n", pname.CString(), pname.CString(), className.CString(), pname.CString())); } else { // vectorMarshal = ToString("PODVector<%s*> %s__vector", className.CString(), ftype->name_.CString()); } if (vectorMarshal.Length()) { source += IndentLine(vectorMarshal); vectorMarshal = String::EMPTY; } } bool returnValue = false; bool sharedPtrReturn = false; String returnStatement; if (returnType == "const char*") { returnValue = true; source += IndentLine("static String returnValue;\n"); returnStatement = "returnValue = "; } else if (function_->GetReturnClass() && function_->GetReturnClass()->IsNumberArray()) { returnStatement = "*returnValue = "; } else if (function_->GetReturnClass() && function_->GetReturnType()->isSharedPtr_) { returnStatement = ToString("SharedPtr<%s> returnValue = ", function_->GetReturnClass()->GetNativeName().CString()); sharedPtrReturn = true; } else if (function_->GetReturnType() && function_->GetReturnType()->type_->asVectorType()) { // we have an out parameter JSBVectorType* vtype = function_->GetReturnType()->type_->asVectorType(); if (!vtype->vectorTypeIsSharedPtr_ && !vtype->vectorTypeIsWeakPtr_) { returnStatement = ToString("%sVector<%s*> returnValue__vector = ", vtype->isPODVector_ ? "POD" : "", vtype->vectorType_->asClassType()->class_->GetName().CString()); } else { returnStatement = ToString("%sVector<%s<%s>> returnValue__vector = ", vtype->isPODVector_ ? "POD" : "", vtype->vectorTypeIsSharedPtr_ ? "SharedPtr" : "WeakPtr", vtype->vectorType_->asClassType()->class_->GetName().CString()); } } else { if (returnType != "void" && !hasVectorMarshal) { returnStatement = "return "; } else if (returnType != "void") { returnStatement = ToString("%s returnValue = ", returnType.CString()); } } String callSig; GenNativeCallParameters(callSig); if (!function_->isConstructor_) { if (function_->IsStatic()) { line = ToString("%s%s::%s(%s);\n", returnStatement.CString(), klass->GetNativeName().CString(), function_->GetName().CString(), callSig.CString()); } else { line = ToString("%sself->%s(%s);\n", returnStatement.CString(), function_->GetName().CString(), callSig.CString()); } } else { if (klass->IsAbstract()) { line = "return 0; // Abstract Class\n"; } else if (klass->IsObject()) { if (callSig.Length()) line = ToString("return new %s(NETCore::GetContext(), %s);\n", klass->GetNativeName().CString(), callSig.CString()); else line = ToString("return new %s(NETCore::GetContext());\n", klass->GetNativeName().CString()); } else { line = ToString("return new %s(%s);\n", klass->GetNativeName().CString(), callSig.CString()); } } source += IndentLine(line); // Vector marshaling for (unsigned i = 0; i < fparams.Size(); i++) { JSBFunctionType* ftype = fparams[i]; JSBVectorType* vtype = ftype->type_->asVectorType(); if (!vtype) continue; JSBClassType* classType = vtype->vectorType_->asClassType(); if (!classType) continue; String className = classType->class_->GetName(); String vectorMarshal; if (vtype->isPODVector_) { const String& pname = ftype->name_; source += IndentLine(ToString("if (%s) %s->AdaptFromVector<%s*>(%s__vector);\n", pname.CString(), pname.CString(), className.CString(), pname.CString())); } else { // vectorMarshal = ToString("PODVector<%s*> %s__vector", className.CString(), ftype->name_.CString()); } if (vectorMarshal.Length()) { source += IndentLine(vectorMarshal); vectorMarshal = String::EMPTY; } } if (sharedPtrReturn) { source += IndentLine("if (returnValue.NotNull()) returnValue->AddRef();\n"); source += IndentLine("return returnValue;\n"); } else if (returnType == "const char*") { source += IndentLine("return returnValue.CString();\n"); } else if (function_->GetReturnType() && function_->GetReturnType()->type_->asVectorType()) { // we have an out parameter JSBVectorType* vtype = function_->GetReturnType()->type_->asVectorType(); source += IndentLine("if (returnValue) returnValue->AdaptFromVector(returnValue__vector);\n"); } else if (returnType != "void" && hasVectorMarshal) { source += IndentLine("return returnValue;\n"); } Dedent(); source += IndentLine("}\n"); source += "\n"; }
void LuaScriptInstance::OnSetAttribute(const AttributeInfo& attr, const Variant& src) { if (attr.ptr_ != (void*)0xffffffff) { Serializable::OnSetAttribute(attr, src); return; } if (scriptObjectRef_ == LUA_REFNIL) return; String name = attr.name_; unsigned length = name.Length(); if (name.Back() == '_') length -= 1; int top = lua_gettop(luaState_); String functionName = String("Set") + name.Substring(0, 1).ToUpper() + name.Substring(1, length - 1); WeakPtr<LuaFunction> function = GetScriptObjectFunction(functionName); // If set function exist if (function) { if (function->BeginCall(this)) { function->PushVariant(src); function->EndCall(); } } else { lua_rawgeti(luaState_, LUA_REGISTRYINDEX, scriptObjectRef_); lua_pushstring(luaState_, name.CString()); switch (attr.type_) { case VAR_BOOL: lua_pushboolean(luaState_, src.GetBool()); break; case VAR_FLOAT: lua_pushnumber(luaState_, src.GetFloat()); break; case VAR_STRING: tolua_pushurho3dstring(luaState_, src.GetString()); break; case VAR_VECTOR2: { Vector2* value = new Vector2(src.GetVector2()); tolua_pushusertype(luaState_, value, "Vector2"); tolua_register_gc(luaState_, lua_gettop(luaState_)); } break; case VAR_VECTOR3: { Vector3* value = new Vector3(src.GetVector3()); tolua_pushusertype(luaState_, value, "Vector3"); tolua_register_gc(luaState_, lua_gettop(luaState_)); } break; case VAR_VECTOR4: { Vector4* value = new Vector4(src.GetVector4()); tolua_pushusertype(luaState_, value, "Vector4"); tolua_register_gc(luaState_, lua_gettop(luaState_)); } break; case VAR_QUATERNION: { Quaternion* value = new Quaternion(src.GetQuaternion()); tolua_pushusertype(luaState_, value, "Quaternion"); tolua_register_gc(luaState_, lua_gettop(luaState_)); } break; case VAR_COLOR: { Color* value = new Color(src.GetColor()); tolua_pushusertype(luaState_, value, "Color"); tolua_register_gc(luaState_, lua_gettop(luaState_)); } break; case VAR_INTRECT: { IntRect* value = new IntRect(src.GetIntRect()); tolua_pushusertype(luaState_, value, "IntRect"); tolua_register_gc(luaState_, lua_gettop(luaState_)); } break; case VAR_INTVECTOR2: { IntVector2* value = new IntVector2(src.GetIntVector2()); tolua_pushusertype(luaState_, value, "IntVector2"); tolua_register_gc(luaState_, lua_gettop(luaState_)); } break; default: LOGERROR("Unsupported data type"); lua_settop(luaState_, top); return; } lua_settable(luaState_, -3); } lua_settop(luaState_, top); }
void TProfileToGui::_listToTreeView(std::vector<String> &list, const TNodeStateIndex state, TTreeNode* rootnode, String rootdir) { rootdir = IncludeTrailingPathDelimiter(rootdir); TTreeNode *node, *nod; _removeNonExistentDirsFromList(list); int pos; bool node_exists; String dir, subdir; for (unsigned int i = 0; i < list.size(); i++) { dir = list[i]; // Ab.0075 Change charactercase for dir into 'real' case on disk: // Do not call ActualPathName() if dir is a drive (like 'C:\'): if (dir != IncludeTrailingPathDelimiter(ExtractFileDrive(dir))) dir = IncludeTrailingPathDelimiter(ecc::ActualPathName(dir)); // Skip directories that are not below current Root Source Dir: if (dir.LowerCase().Pos(rootdir.LowerCase()) != 1) continue; // Strip rootdir from dir: dir = dir.Delete(1, rootdir.Length()); // Add unselected subdir: node = rootnode; while (dir.Length()) { pos = dir.Pos("\\"); subdir = dir.SubString(1, pos-1); node_exists = false; nod = node->getFirstChild(); while (nod) { if (nod->Text.AnsiCompareIC(subdir) == 0) { node_exists = true; break; } nod = nod->getNextSibling(); } /* 092RC2: Incorrect code, replaced by code below this comment block (SE 27-mar-2006) if (!node_exists) { if (DirectoryExists(list[i])) { node = f_Main->fr_Source->tv_Dirs->Items->AddChild(node, subdir); node->StateIndex = state; } } dir = dir.Delete(1, pos); if (nod) node = nod; } node->StateIndex = state; */ if (!node_exists) { if (DirectoryExists(list[i])) { node = f_Main->fr_Source->tv_Dirs->Items->AddChild(node, subdir); node->StateIndex = state; } else { node = NULL; } } else { node = nod; } if (!node) break; dir = dir.Delete(1, pos); } if (node) node->StateIndex = state; } }
//--------------------------------------------------------------------------- String TEntryOptionsForm::doFileSave( ) { SaveDialog->InitialDir = ExtractFilePath( ct->cfileName.c_str() ); String expName; String fname = ExtractFileName( ct->cfileName.c_str() ); String ext = ExtractFileExt( ct->cfileName.c_str() ); fname = fname.SubString( 1, fname.Length() - ext.Length() ); //enum ExportType {EREG1TEST, EADIF, EG0GJV, EMINOS, EKML, EPRINTFILE }; String defext; String filter; switch ( expformat ) { case EG0GJV: defext = "GJV"; filter = "GJV ContestLog files (*.gjv)|*.GJV|All Files (*.*)|*.*" ; break; case EMINOS: defext = "Minos"; filter = "Minos ContestLog files (*.minos)|*.MINOS|All Files (*.*)|*.*" ; break; case EADIF: defext = "ADI"; filter = "ADIF files (*.adi)|*.ADI|All Files (*.*)|*.*" ; break; case EKML: defext = "KML"; filter = "KML(GoogleEarth) files (*.kml)|*.KML|All Files (*.*)|*.*" ; break; case EREG1TEST: { defext = "EDI"; ct->mycall.valRes = CS_NOT_VALIDATED; ct->mycall.validate( ); filter = "Region 1 EDI files (*.edi)|*.EDI|All Files (*.*)|*.*" ; } break; case EPRINTFILE: { defext = "TXT"; filter = "Text output (*.txt)|*.TXT|All Files (*.*)|*.*" ; } break; } SaveDialog->FileName = fname; SaveDialog->DefaultExt = defext; SaveDialog->Filter = filter; while ( SaveDialog->Execute() ) { TWaitCursor fred; expName = SaveDialog->FileName; // open the export file struct stat sbuf; if ( stat( expName.c_str(), &sbuf ) == 0 ) { if ( !( sbuf.st_mode & S_IWRITE ) ) { MinosParameters::getMinosParameters() ->mshowMessage( "File is Read Only" ); return ""; } } if ( MinosParameters::getMinosParameters() ->isContestOpen( expName.c_str() ) ) { // then try again... continue; } HANDLE expfd = CreateFile( expName.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, // security CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 ); // template handle if ( expfd == INVALID_HANDLE_VALUE ) { char * emess = _strerror( "Failed to create export file" ); MinosParameters::getMinosParameters() ->mshowMessage( emess ); return ""; } int ret = ct->export_contest( expfd, expformat ); CloseHandle( expfd ); if ( ret == -1 ) { unlink( expName.c_str() ); // failure response, so delete file again expName = ""; } break; } return expName; }