void CommandData::ReadConfig() { StringList List; if (ReadTextFile(DefConfigName,NULL,&List,true)) { char *Str; while ((Str=List.GetString())!=NULL) { while (IsSpace(*Str)) Str++; if (strnicomp(Str,"switches=",9)==0) ProcessSwitchesString(Str+9); } } }
BOOL CTextFile::Load( CString& filename, CListBox* list ) /* ============================================================ Function : CTextFile::Load Description : Loads a text file from filename to the CListBox list. If filename is empty, the standard file dialog will be displayed, and - if OK is selected - filename will contain the selected filename on return. Return : BOOL - FALSE if failure. GetErrorMessage will return the error. Parameters : CString& filename - name of file to load CListBox* list - pointer to CListBox to set text to ============================================================*/ { BOOL result = FALSE; // Error checking if( ValidParam( list ) ) { // Read the file CStringArray contents; if( ReadTextFile( filename, contents ) ) { // Set to listbox int max = contents.GetSize(); for( int t = 0 ; t < max ; t++ ) if( contents[ t ].GetLength() ) list->AddString( contents[ t ] ); result = TRUE; } } return result; }
int CGenethonDoc::GetTextFile( CString PathName, int Append, const CString& SeqName, double SeqWeight, DWORD TextStart, const CString& Descr, int IUPAC ) { CPtrList CommentList; CPtrList SequenceList; gMaxStrSize = 0L; if ( !ReadTextFile ( &CommentList, &SequenceList, PathName, SeqName, SeqWeight, TextStart, Descr, IUPAC ) ) { while ( !SequenceList.IsEmpty() ) { delete (SeqNameStruct *)SequenceList.RemoveHead(); } return 0; } return ProcessRows( CommentList, SequenceList, Append ); }
Genome::Genome(std::string file) { filename = file; CfgList* d = CfgList::LoadFile(file); // read sequence data const char* seqfile = d->GetLiteral("SequenceFile"); std::string seqPath = GetDirPath(file) + seqfile; sequence = ReadTextFile(seqPath); std::transform(sequence.begin(), sequence.end(), sequence.begin(), ::tolower); // load global properties name = d->GetLiteral("LocusName"); topology = d->GetLiteral("LocusTopology"); modificationDate = d->GetLiteral("LocusModificationDate"); definition = d->GetLiteral("Definition"); source = d->GetLiteral("Source"); // load features CfgList* features = d->GetList("features"); mvec<FeatureProtein*> proteins = LoadFeatureList<FeatureProtein>(features->GetList("CDS")); members_ptr(proteins, &FeatureProtein::type) |= FeatureProtein::Type_Protein; mvec<Feature*> tRNA = LoadFeatureList<Feature>(features->GetList("tRNA")); members_ptr(tRNA, &Feature::type) |= Feature::Type_tRNA; mvec<Feature*> rRNA = LoadFeatureList<Feature>(features->GetList("rRNA")); members_ptr(rRNA, &Feature::type) |= Feature::Type_rRNA; mvec<Feature*> misc_RNA = LoadFeatureList<Feature>(features->GetList("misc_RNA")); members_ptr(misc_RNA, &Feature::type) |= Feature::Type_MiscRNA; mvec<Feature*> misc_feature = LoadFeatureList<Feature>(features->GetList("misc_feature")); members_ptr(misc_feature, &Feature::type) |= Feature::Type_MiscFeature; genes = tRNA & rRNA & misc_RNA & misc_feature & proteins; // sort genes std::sort(genes.begin(), genes.end(), GeneComparer); delete d; }
void Configuration::LoadConfigFile() { // Open the config file, if possible, and load in configurable variables. if (ConfigFile != NULL) { vector<string*>* varVector = ReadTextFile(*ConfigFile); if(varVector!=NULL) { vector<string*>::iterator itr; for(itr=varVector->begin();itr!=varVector->end();itr++) { string* pS = *itr; string::size_type index = pS->find('='); if (index!=string::npos) { string* key = new string(pS->substr(0, index)); ++index; string* val = new string((index<pS->size()) ? pS->substr(index) : ""); SetProperty(*key,(void*)val,true); delete key; delete val; } delete pS; } delete varVector; } } // Update the config values from the model arguments. CommandLine::HashMap& hm = ModelParameters->GetCommandLineOptions(); CommandLine::HashMap::iterator itr; for(itr=hm.begin();itr!=hm.end();itr++) { const string* pS = itr->first; const string* pV = itr->second; try { SetProperty(*pS, (const void*)pV,true); } catch (...) { Trace::WriteLine(1, "Configuration.LoadConfigFile: setting property: %s, exception ignored.", pS->c_str()); } } // Check the property values are valid and in range. CheckOptionValues(false); }
bool CClientFXDB::ReadFXGroups( bool bText, ILTStream* pFxFile, CLinkList<FX_GROUP *> &collGroupFx ) { // Read in the number of FX groups in this file uint32 dwNumGroups; if( bText ) { ReadTextFile( pFxFile, "%s %lu", &dwNumGroups ); } else { pFxFile->Read(&dwNumGroups, sizeof(uint32)); } //allocate a working buffer that keys can read properties into static const uint32 knMaxKeyProps = 512; FX_PROP* pPropBuffer = debug_newa(FX_PROP, knMaxKeyProps); if(!pPropBuffer) return false; for( uint32 i = 0; i < dwNumGroups; i ++ ) { // Create a new group. FX_GROUP *pFxGroup = debug_new( FX_GROUP ); if( !ReadFXGroup( bText, pFxFile, pFxGroup, pPropBuffer, knMaxKeyProps )) { debug_deletea(pPropBuffer); return false; } collGroupFx.AddTail(pFxGroup); } //free our working buffer debug_deletea(pPropBuffer); return true; }
void ShaderProgram::CreateShader(ShaderType _type, std::string _fileName) { GLuint type; switch (_type) { case ShaderProgram::VERTEX: type = GL_VERTEX_SHADER; break; case ShaderProgram::FRAGMENT: type = GL_FRAGMENT_SHADER; break; default: std::cout << "Error: Shader type invalid\n"; exit(1); } std::cout << "Creating shader. Filename: " << _fileName << "\n"; unsigned int shaderHandle = glCreateShader(type); if (glIsShader(shaderHandle) == GL_FALSE) { std::cout << "Error: Failed to create shader\n" << "OpenGL error code: " << glGetError() << "\n"; } char *source = ReadTextFile(_fileName); // Convert source to const because the OpgenGL call requires it const char *constSource = source; //std::cout << "\nShader source to read from:\n" << constSource << "\n\n"; glShaderSource(shaderHandle, 1, &constSource, NULL); // Compile and verify result glCompileShader(shaderHandle); int shaderCompiled; glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &shaderCompiled); if (shaderCompiled == GL_FALSE) { std::cout << "Error: Shader compilation failed\n" << "OpenGL error code: " << glGetError() << "\n"; PrintLog(shaderHandle); exit(1); } shaderHandles_.push_back(shaderHandle); free(source); }
char *LoadEntities(char *mapname, char *entities) { char entfilename[MAX_QPATH] = ""; char *newentities; int i; //, islefn; cvar_t *game_dir; game_dir = gi.cvar ("game", "", 0); sprintf(entfilename, "%s/maps/%s.ent", game_dir->string, mapname); // convert string to all lowercase (for Linux) for (i = 0; entfilename[i]; i++) entfilename[i] = tolower(entfilename[i]); newentities = ReadTextFile(entfilename); if (newentities) return(newentities); // reassign the ents else return(entities); }
BOOL CTextFile::Load( CString& filename, CEdit* edit ) /* ============================================================ Function : CTextFile::Load Description : Loads a text file from filename to the CEdit edit. If filename is empty, the standard file dialog will be displayed, and - if OK is selected - filename will contain the selected filename on return. No translation of eols will be made. Return : BOOL - FALSE if failure. GetErrorMessage will return the error. Parameters : CString& filename - name of file to load CEdit* edit - pointer to CEdit to set text to ============================================================*/ { BOOL result = FALSE; // Error checking if( ValidParam( edit ) ) { CString contents; if( ReadTextFile( filename, contents ) ) { edit->SetWindowText( contents ); result = TRUE; } } return result; }
int main() { std::string str; char tmp[101]; while (true) { printf("\nAre you want to filter?(input 1 to YES, 0(or other symbol) for NO)\n"); scanf("%100s", tmp); std::string str = tmp; if (str != "1") break; else { // Функция чтения ReadTextFile(); } } system("pause"); return 0; }
/** * Opens the file given by the filepath and returns the main node. * (Includes error handling) * @param filename Filepath to the XML file to parse * @param tag (?) * @param pResults Pointer to the XML::Results object to fill on error or success * @return The main XMLNode or an empty node on error */ XMLNode * XML::ParseFile(Path filename, Results *pResults) { // Open the file for reading tstring buffer; // If file can't be read if (!ReadTextFile(filename, buffer)) { // If XML::Results object exists if (pResults) { // -> Save the error type into it pResults->error = eXMLErrorFileNotFound; pResults->line = 0; pResults->column = 0; } // -> Return empty XMLNode return nullptr; } // Parse the string and get the main XMLNode return ParseString(buffer.c_str(), pResults); }
/* * Process Response files on the command line * Returns true if it allocated a new argv array that must be freed later */ void ConsoleArgs::ProcessResponseArgs() { HRESULT hr; b_tree *response_files = NULL; WCHAR szFilename[MAX_PATH]; WCAllocBuffer textBuffer; for (WStrList * listCurArg = m_listArgs; listCurArg != NULL && !m_output->HadFatalError(); listCurArg = listCurArg->next) { WCHAR * szArg = listCurArg->arg; // Skip everything except Response files if (szArg == NULL || szArg[0] != '@') continue; if (wcslen(szArg) == 1) { m_output->ShowErrorIdString( ERR_NoFileSpec, ERROR_ERROR, szArg); goto CONTINUE; } // Check for duplicates if (!GetFullFileName( RemoveQuotes(WCBuffer::CreateFrom(&szArg[1])), szFilename, false)) continue; hr = TreeAdd(&response_files, szFilename); if (hr == E_OUTOFMEMORY) { m_output->ShowErrorId(FTL_NoMemory, ERROR_FATAL); goto CONTINUE; } else if (hr == S_FALSE) { m_output->ShowErrorIdString(ERR_DuplicateResponseFile, ERROR_ERROR, szFilename); goto CONTINUE; } FileType fileType; textBuffer.Clear(); if (FAILED(hr = ReadTextFile(szFilename, NULL, textBuffer, &fileType)) || hr == S_FALSE) { if (hr == E_OUTOFMEMORY) { m_output->ShowErrorId(FTL_NoMemory, ERROR_FATAL); } else if (FAILED(hr)) { if (fileType == ftBinary) m_output->ShowErrorIdString(ERR_BinaryFile, ERROR_ERROR, szFilename); else m_output->ShowErrorIdString(ERR_OpenResponseFile, ERROR_ERROR, szFilename, m_output->ErrorHR(hr)); } goto CONTINUE; } TextToArgs( textBuffer, &listCurArg->next); CONTINUE: // remove the response file argument, and continue to the next. listCurArg->arg = NULL; VSFree(szArg); } CleanupTree(response_files); }
void CommandData::ParseArg(char *Arg,wchar *ArgW) { if (IsSwitch(*Arg) && !NoMoreSwitches) if (Arg[1]=='-') NoMoreSwitches=true; else ProcessSwitch(Arg+1,(ArgW!=NULL && *ArgW!=0 ? ArgW+1:NULL)); else if (*Command==0) { strncpyz(Command,Arg,ASIZE(Command)); if (ArgW!=NULL) wcsncpy(CommandW,ArgW,ASIZE(CommandW)); #ifndef GUI *Command=etoupper(*Command); // 'I' and 'S' commands can contain case sensitive strings after // the first character, so we must not modify their case. // 'S' can contain SFX name, which case is important in Unix. if (*Command!='I' && *Command!='S') strupper(Command); #endif } else if (*ArcName==0 && *ArcNameW==0) { strncpyz(ArcName,Arg,ASIZE(ArcName)); if (ArgW!=NULL) wcsncpyz(ArcNameW,ArgW,ASIZE(ArcNameW)); } else { bool EndSeparator; // If last character is the path separator. if (ArgW!=NULL) { size_t Length=wcslen(ArgW); wchar EndChar=Length==0 ? 0:ArgW[Length-1]; EndSeparator=IsDriveDiv(EndChar) || IsPathDiv(EndChar); } else { size_t Length=strlen(Arg); char EndChar=Length==0 ? 0:Arg[Length-1]; EndSeparator=IsDriveDiv(EndChar) || IsPathDiv(EndChar); } char CmdChar=etoupper(*Command); bool Add=strchr("AFUM",CmdChar)!=NULL; bool Extract=CmdChar=='X' || CmdChar=='E'; if (EndSeparator && !Add) { strncpyz(ExtrPath,Arg,ASIZE(ExtrPath)); if (ArgW!=NULL) wcsncpyz(ExtrPathW,ArgW,ASIZE(ExtrPathW)); } else if ((Add || CmdChar=='T') && *Arg!='@') FileArgs->AddString(Arg,ArgW); else { FindData FileData; bool Found=FindFile::FastFind(Arg,ArgW,&FileData); if (!Found && *Arg=='@' && !IsWildcard(Arg,ArgW)) { FileLists=true; RAR_CHARSET Charset=FilelistCharset; #if defined(_WIN_ALL) && !defined(GUI) // for compatibility reasons we use OEM encoding // in Win32 console version by default if (Charset==RCH_DEFAULT) Charset=RCH_OEM; #endif wchar *WideArgName=(ArgW!=NULL && *ArgW!=0 ? ArgW+1:NULL); ReadTextFile(Arg+1,WideArgName,FileArgs.get(),false,true,Charset,true,true,true); } else if (Found && FileData.IsDir && Extract && *ExtrPath==0 && *ExtrPathW==0) { strncpyz(ExtrPath,Arg,ASIZE(ExtrPath)-1); AddEndSlash(ExtrPath); if (ArgW!=NULL) { wcsncpyz(ExtrPathW,ArgW,ASIZE(ExtrPathW)-1); AddEndSlash(ExtrPathW); } } else FileArgs->AddString(Arg,ArgW); } } }
void CommandData::ProcessSwitch(char *Switch,wchar *SwitchW) { bool WidePresent=SwitchW!=NULL && *SwitchW!=0; // If 'true', SwitchW is not empty. switch(etoupper(Switch[0])) { case 'I': if (strnicomp(&Switch[1],"LOG",3)==0) { strncpyz(LogName,Switch[4] ? Switch+4:DefLogName,ASIZE(LogName)); break; } if (stricomp(&Switch[1],"SND")==0) { Sound=true; break; } if (stricomp(&Switch[1],"ERR")==0) { MsgStream=MSG_STDERR; break; } if (strnicomp(&Switch[1],"EML",3)==0) { strncpyz(EmailTo,Switch[4] ? Switch+4:"@",ASIZE(EmailTo)); EmailTo[sizeof(EmailTo)-1]=0; break; } if (stricomp(&Switch[1],"NUL")==0) { MsgStream=MSG_NULL; break; } if (etoupper(Switch[1])=='D') { for (int I=2;Switch[I]!=0;I++) switch(etoupper(Switch[I])) { case 'Q': MsgStream=MSG_ERRONLY; break; case 'C': DisableCopyright=true; break; case 'D': DisableDone=true; break; case 'P': DisablePercentage=true; break; } break; } if (stricomp(&Switch[1],"OFF")==0) { Shutdown=true; break; } break; case 'T': switch(etoupper(Switch[1])) { case 'K': ArcTime=ARCTIME_KEEP; break; case 'L': ArcTime=ARCTIME_LATEST; break; case 'O': FileTimeBefore.SetAgeText(Switch+2); break; case 'N': FileTimeAfter.SetAgeText(Switch+2); break; case 'B': FileTimeBefore.SetIsoText(Switch+2); break; case 'A': FileTimeAfter.SetIsoText(Switch+2); break; case 'S': { EXTTIME_MODE Mode=EXTTIME_HIGH3; bool CommonMode=Switch[2]>='0' && Switch[2]<='4'; if (CommonMode) Mode=(EXTTIME_MODE)(Switch[2]-'0'); if (Switch[2]=='-') Mode=EXTTIME_NONE; if (CommonMode || Switch[2]=='-' || Switch[2]=='+' || Switch[2]==0) xmtime=xctime=xatime=Mode; else { if (Switch[3]>='0' && Switch[3]<='4') Mode=(EXTTIME_MODE)(Switch[3]-'0'); if (Switch[3]=='-') Mode=EXTTIME_NONE; switch(etoupper(Switch[2])) { case 'M': xmtime=Mode; break; case 'C': xctime=Mode; break; case 'A': xatime=Mode; break; case 'R': xarctime=Mode; break; } } } break; case '-': Test=false; break; case 0: Test=true; break; default: BadSwitch(Switch); break; } break; case 'A': switch(etoupper(Switch[1])) { case 'C': ClearArc=true; break; case 'D': AppendArcNameToPath=true; break; case 'I': IgnoreGeneralAttr=true; break; case 'N': //reserved for archive name break; case 'O': AddArcOnly=true; break; case 'P': strcpy(ArcPath,Switch+2); if (WidePresent) wcscpy(ArcPathW,SwitchW+2); break; case 'S': SyncFiles=true; break; default: BadSwitch(Switch); break; } break; case 'D': if (Switch[2]==0) switch(etoupper(Switch[1])) { case 'S': DisableSortSolid=true; break; case 'H': OpenShared=true; break; case 'F': DeleteFiles=true; break; } break; case 'O': switch(etoupper(Switch[1])) { case '+': Overwrite=OVERWRITE_ALL; break; case '-': Overwrite=OVERWRITE_NONE; break; case 0: Overwrite=OVERWRITE_FORCE_ASK; break; case 'R': Overwrite=OVERWRITE_AUTORENAME; break; case 'W': ProcessOwners=true; break; #ifdef SAVE_LINKS case 'L': SaveLinks=true; break; #endif #ifdef _WIN_ALL case 'S': SaveStreams=true; break; case 'C': SetCompressedAttr=true; break; #endif default : BadSwitch(Switch); break; } break; case 'R': switch(etoupper(Switch[1])) { case 0: Recurse=RECURSE_ALWAYS; break; case '-': Recurse=RECURSE_DISABLE; break; case '0': Recurse=RECURSE_WILDCARDS; break; #ifndef _WIN_CE case 'I': { Priority=atoi(Switch+2); char *ChPtr=strchr(Switch+2,':'); if (ChPtr!=NULL) { SleepTime=atoi(ChPtr+1); InitSystemOptions(SleepTime); } SetPriority(Priority); } break; #endif } break; case 'Y': AllYes=true; break; case 'N': case 'X': if (Switch[1]!=0) { StringList *Args=etoupper(Switch[0])=='N' ? InclArgs.get():ExclArgs.get(); if (Switch[1]=='@' && !IsWildcard(Switch)) { RAR_CHARSET Charset=FilelistCharset; #if defined(_WIN_ALL) && !defined(GUI) // for compatibility reasons we use OEM encoding // in Win32 console version by default if (Charset==RCH_DEFAULT) Charset=RCH_OEM; #endif ReadTextFile(Switch+2,NULL,Args,false,true,Charset,true,true,true); } else Args->AddString(Switch+1); } break; case 'E': switch(etoupper(Switch[1])) { case 'P': switch(Switch[2]) { case 0: ExclPath=EXCL_SKIPWHOLEPATH; break; case '1': ExclPath=EXCL_BASEPATH; break; case '2': ExclPath=EXCL_SAVEFULLPATH; break; case '3': ExclPath=EXCL_ABSPATH; break; } break; case 'E': ProcessEA=false; break; case 'N': NoEndBlock=true; break; default: if (Switch[1]=='+') { InclFileAttr=GetExclAttr(&Switch[2]); InclAttrSet=true; } else ExclFileAttr=GetExclAttr(&Switch[1]); break; } break; case 'P': if (Switch[1]==0) { GetPassword(PASSWORD_GLOBAL,NULL,NULL,Password,ASIZE(Password)); eprintf("\n"); } else { CharToWide(Switch+1,Password,ASIZE(Password)); Password[ASIZE(Password)-1]=0; } break; case 'H': if (etoupper(Switch[1])=='P') { EncryptHeaders=true; if (Switch[2]!=0) { CharToWide(Switch+2,Password,ASIZE(Password)); Password[ASIZE(Password)-1]=0; } else if (*Password==0) { GetPassword(PASSWORD_GLOBAL,NULL,NULL,Password,ASIZE(Password)); eprintf("\n"); } } break; case 'Z': if (Switch[1]==0 && (!WidePresent || SwitchW[1]==0)) { // If comment file is not specified, we read data from stdin. strcpy(CommentFile,"stdin"); } strncpyz(CommentFile,Switch+1,ASIZE(CommentFile)); if (WidePresent) wcsncpyz(CommentFileW,SwitchW+1,ASIZE(CommentFileW)); break; case 'M': switch(etoupper(Switch[1])) { case 'C': { char *Str=Switch+2; if (*Str=='-') for (int I=0;I<sizeof(FilterModes)/sizeof(FilterModes[0]);I++) FilterModes[I].State=FILTER_DISABLE; else while (*Str) { int Param1=0,Param2=0; FilterState State=FILTER_AUTO; FilterType Type=FILTER_NONE; if (IsDigit(*Str)) { Param1=atoi(Str); while (IsDigit(*Str)) Str++; } if (*Str==':' && IsDigit(Str[1])) { Param2=atoi(++Str); while (IsDigit(*Str)) Str++; } switch(etoupper(*(Str++))) { case 'T': Type=FILTER_PPM; break; case 'E': Type=FILTER_E8; break; case 'D': Type=FILTER_DELTA; break; case 'A': Type=FILTER_AUDIO; break; case 'C': Type=FILTER_RGB; break; case 'I': Type=FILTER_ITANIUM; break; case 'L': Type=FILTER_UPCASETOLOW; break; } if (*Str=='+' || *Str=='-') State=*(Str++)=='+' ? FILTER_FORCE:FILTER_DISABLE; FilterModes[Type].State=State; FilterModes[Type].Param1=Param1; FilterModes[Type].Param2=Param2; } } break; case 'M': break; case 'D': { if ((WinSize=atoi(&Switch[2]))==0) WinSize=0x10000<<(etoupper(Switch[2])-'A'); else WinSize*=1024; if (!CheckWinSize()) BadSwitch(Switch); } break; case 'S': { char *Names=Switch+2,DefNames[512]; if (*Names==0) { strcpy(DefNames,DefaultStoreList); Names=DefNames; } while (*Names!=0) { char *End=strchr(Names,';'); if (End!=NULL) *End=0; if (*Names=='.') Names++; char Mask[NM]; if (strpbrk(Names,"*?.")==NULL) sprintf(Mask,"*.%s",Names); else strcpy(Mask,Names); StoreArgs->AddString(Mask); if (End==NULL) break; Names=End+1; } } break; #ifdef PACK_SMP case 'T': Threads=atoi(Switch+2); if (Threads>16) BadSwitch(Switch); else { } break; #endif default: Method=Switch[1]-'0'; if (Method>5 || Method<0) BadSwitch(Switch); break; } break; case 'V': switch(etoupper(Switch[1])) { case 'N': OldNumbering=true; break; case 'P': VolumePause=true; break; case 'E': if (etoupper(Switch[2])=='R') VersionControl=atoi(Switch+3)+1; break; case '-': VolSize=0; break; default: { int64 NewVolSize=atoil(&Switch[1]); if (NewVolSize==0) NewVolSize=INT64NDF; // Autodetecting volume size. else switch (Switch[strlen(Switch)-1]) { case 'f': case 'F': switch(NewVolSize) { case 360: NewVolSize=362496; break; case 720: NewVolSize=730112; break; case 1200: NewVolSize=1213952; break; case 1440: NewVolSize=1457664; break; case 2880: NewVolSize=2915328; break; } break; case 'k': NewVolSize*=1024; break; case 'm': NewVolSize*=1024*1024; break; case 'M': NewVolSize*=1000*1000; break; case 'g': NewVolSize*=1024*1024; NewVolSize*=1024; break; case 'G': NewVolSize*=1000*1000; NewVolSize*=1000; break; case 'b': case 'B': break; default: NewVolSize*=1000; break; } if (VolSize==0) VolSize=NewVolSize; else NextVolSizes.Push(NewVolSize); } break; } break; case 'F': if (Switch[1]==0) FreshFiles=true; else BadSwitch(Switch); break; case 'U': if (Switch[1]==0) UpdateFiles=true; else BadSwitch(Switch); break; case 'W': strncpyz(TempPath,&Switch[1],ASIZE(TempPath)); AddEndSlash(TempPath); break; case 'S': if (IsDigit(Switch[1])) { Solid|=SOLID_COUNT; SolidCount=atoi(&Switch[1]); } else switch(etoupper(Switch[1])) { case 0: Solid|=SOLID_NORMAL; break; case '-': Solid=SOLID_NONE; break; case 'E': Solid|=SOLID_FILEEXT; break; case 'V': Solid|=Switch[2]=='-' ? SOLID_VOLUME_DEPENDENT:SOLID_VOLUME_INDEPENDENT; break; case 'D': Solid|=SOLID_VOLUME_DEPENDENT; break; case 'L': if (IsDigit(Switch[2])) FileSizeLess=atoil(Switch+2); break; case 'M': if (IsDigit(Switch[2])) FileSizeMore=atoil(Switch+2); break; case 'C': { // Switch is already found bad, avoid reporting it several times. bool AlreadyBad=false; RAR_CHARSET rch=RCH_DEFAULT; switch(etoupper(Switch[2])) { case 'A': rch=RCH_ANSI; break; case 'O': rch=RCH_OEM; break; case 'U': rch=RCH_UNICODE; break; default : BadSwitch(Switch); AlreadyBad=true; break; }; if (!AlreadyBad) if (Switch[3]==0) CommentCharset=FilelistCharset=rch; else for (int I=3;Switch[I]!=0 && !AlreadyBad;I++) switch(etoupper(Switch[I])) { case 'C': CommentCharset=rch; break; case 'L': FilelistCharset=rch; break; default: BadSwitch(Switch); AlreadyBad=true; break; } } break; } break; case 'C': if (Switch[2]==0) switch(etoupper(Switch[1])) { case '-': DisableComment=true; break; case 'U': ConvertNames=NAMES_UPPERCASE; break; case 'L': ConvertNames=NAMES_LOWERCASE; break; } break; case 'K': switch(etoupper(Switch[1])) { case 'B': KeepBroken=true; break; case 0: Lock=true; break; } break; #ifndef GUI case '?' : OutHelp(); break; #endif default : BadSwitch(Switch); break; } }
void ReadMaterialComp() { char *input, fname[MAX_STR], word[MAX_STR], pname[MAX_STR], **params; long loc0, loc1, mat, mat0, iso, iso0, nuc, i0, i, np, j, n, line, r, g, b; double val, sum; FILE *fp; /* Get pointer to file list */ if ((loc0 = (long)RDB[DATA_PTR_COMP_FILE]) < VALID_PTR) return; fprintf(out, "Overriding initial material compositions...\n"); /* Reset previous pointer */ mat0 = -1; /* Reset counters for line number calculation */ WDB[DATA_LINE_NUM_N0] = 0.0; WDB[DATA_LINE_NUM_NL0] = 1.0; /* Loop over list */ while (RDB[loc0] > VALID_PTR) { /* Get file name */ sprintf(fname, "%s", GetText(loc0)); /* Check that file exists */ if ((fp = fopen(fname, "r")) != NULL) fclose(fp); else { /* File not found */ Error(0, "Material composition file \"%s\" does not exist", fname); } /* Read input file */ input = ReadTextFile(fname); /* Avoid compiler warning */ params = NULL; /* Loop over file */ i0 = 0; while ((i = NextWord(&input[i0], word)) > 0) { /* update pointer */ i0 = i0 + i; /* Get line number for error messages */ line = GetLineNumber(input, i0); /* Look for material definition */ if (!strcasecmp(word, "mat")) { /* Copy parameter name */ strcpy (pname, word); /* Read parameters */ params = GetParams(word, input, &np, &i0, 4, 4*MAX_ISOTOPES + 8, fname); /* Read data */ j = 0; /* Find material (try starting from previous) */ mat = mat0; while (mat > VALID_PTR) { /* Compare */ if (!strcmp(params[j], GetText(mat + MATERIAL_PTR_NAME))) break; /* Next */ mat = NextItem(mat); } /* Find material (start from beginning) */ if (mat < VALID_PTR) { mat = (long)RDB[DATA_PTR_M0]; while (mat > VALID_PTR) { /* Compare */ if (!strcmp(params[j], GetText(mat + MATERIAL_PTR_NAME))) break; /* Next */ mat = NextItem(mat); } } /* Check */ if (mat < VALID_PTR) Error(-1, pname, fname, line, "Material %s is not defined", params[j]); else j++; /* Remember previous */ mat0 = NextItem(mat); /* Material density */ if (!strcmp(params[j], "sum")) { /* Set value to -inf to calculate sum from composition */ WDB[mat + MATERIAL_ADENS] = -INFTY; j++; } else { /* Read value */ WDB[mat + MATERIAL_ADENS] = TestParam(pname, fname, line, params[j++], PTYPE_REAL, -1000.0, 1000.0); } /* Reset sum */ sum = 0.0; /* Reset previous pointer */ iso0 = -1; /* Loop over parameters */ while (j < np) { /* Check parameter */ if (!strcmp(params[j], "tmp")) { /***** Temperature for Doppler-breadening **************/ j++; /* Get temperature */ WDB[mat + MATERIAL_DOPPLER_TEMP] = TestParam(pname, fname, line, params[j++], PTYPE_REAL, 0.0, 100000.0); /* Set option */ WDB[DATA_USE_DOPPLER_PREPROCESSOR] = (double)YES; /*******************************************************/ } if (!strcmp(params[j], "tms") || !strcmp(params[j], "ettm")) { /***** Temperature for TMS *****************************/ j++; /* Get temperature */ WDB[mat + MATERIAL_TMS_TMIN] = TestParam(pname, fname, line, params[j++], PTYPE_REAL, 0.0, 100000.0); /* Copy to maximum */ WDB[mat + MATERIAL_TMS_TMAX] = RDB[mat + MATERIAL_TMS_TMIN]; /* Set mode */ WDB[DATA_TMS_MODE] = (double)TMS_MODE_CE; WDB[mat + MATERIAL_TMS_MODE] = (double)YES; /*******************************************************/ } else if (!strcmp(params[j], "rgb")) { /***** Material colour *********************************/ j++; /* Get r, b and g */ r = TestParam(pname, fname, line, params[j++], PTYPE_INT, 0, 255); g = TestParam(pname, fname, line, params[j++], PTYPE_INT, 0, 255); b = TestParam(pname, fname, line, params[j++], PTYPE_INT, 0, 255); /* Set color */ WDB[mat + MATERIAL_RGB] = b + 1000.0*g + 1000000.0*r; /*******************************************************/ } else if (!strcmp(params[j], "vol")) { /***** Material volume *********************************/ j++; /* Get volume */ WDB[mat + MATERIAL_VOLUME_GIVEN] = TestParam(pname, fname, line, params[j++], PTYPE_REAL, 0.0, INFTY); /*******************************************************/ } else if (!strcmp(params[j], "fix")) { /***** Default library ID and temperature***************/ j++; /* Get default ID and temperature */ WDB[mat + MATERIAL_DEFAULT_PTR_LIB_ID] = PutText(params[j++]); WDB[mat + MATERIAL_DEFAULT_TMP] = TestParam(pname, fname, line, params[j++], PTYPE_REAL, 0.0, INFTY); /*******************************************************/ } else if (!strcmp(params[j], "mass")) { /***** Material mass ***********************************/ j++; /* Get mass */ WDB[mat + MATERIAL_MASS_GIVEN] = TestParam(pname, fname, line, params[j++], PTYPE_REAL, 0.0, INFTY); /*******************************************************/ } else if (!strcmp(params[j], "burn")) { /***** Burnable material *******************************/ j++; /* Set burn flag */ SetOption(mat + MATERIAL_OPTIONS, OPT_BURN_MAT); /* Set burn sort flag and materials flag */ WDB[mat + MATERIAL_BURN_SORT_FLAG] = 1.0; WDB[DATA_BURN_MATERIALS_FLAG] = (double)YES; /* Get number of rings */ WDB[mat + MATERIAL_BURN_RINGS] = (double)TestParam(pname, fname, line, params[j++], PTYPE_INT, 0, 10000000); /*******************************************************/ } else if (!strcmp(params[j], "moder")) { /***** Thermal scattering data *************************/ j++; /* Check number of parameters */ if (j > np - 3) Error(mat, "Invalid number of parameters"); /* Create new item (use the same structure as with */ /* the therm card) */ WDB[mat + MATERIAL_PTR_SAB] = NULLPTR; loc1 = NewItem(mat + MATERIAL_PTR_SAB, THERM_BLOCK_SIZE); /* Read name */ WDB[loc1 + THERM_PTR_ALIAS] = (double)PutText(params[j++]); /* Read ZA */ WDB[loc1 + THERM_ZA] = (double)TestParam(pname, fname, line, params[j++], PTYPE_INT, 1001, 120000); /*******************************************************/ } else if (!strcmp(params[j], "tft")) { /***** Minimum and maximum temperatures for TMS ********/ j++; /* Get minimum temperature */ WDB[mat + MATERIAL_TMS_TMIN] = TestParam(pname, fname, line, params[j++], PTYPE_REAL, 0.0, 100000.0); /* Get maximum temperature */ WDB[mat + MATERIAL_TMS_TMAX] = TestParam(pname, fname, line, params[j++], PTYPE_REAL, RDB[mat + MATERIAL_TMS_TMIN], 100000.0); /* Set mode */ WDB[DATA_TMS_MODE] = (double)TMS_MODE_CE; WDB[mat + MATERIAL_TMS_MODE] = (double)YES; /*******************************************************/ } else { /***** Composition *************************************/ /* Find nuclide in composition (start from previous) */ iso = iso0; while (iso > VALID_PTR) { /* Pointer to nuclide data */ nuc = (long)RDB[iso + COMPOSITION_PTR_NUCLIDE]; CheckPointer(FUNCTION_NAME, "(nuc)", DATA_ARRAY,nuc); /* Compare */ if (!strcmp(GetText(nuc + NUCLIDE_PTR_NAME), params[j])) break; /* Next */ iso = NextItem(iso); } /* Find nuclide in composition (start from beginning) */ if (iso < VALID_PTR) { iso = (long)RDB[mat + MATERIAL_PTR_COMP]; while (iso > VALID_PTR) { /* Pointer to nuclide data */ nuc = (long)RDB[iso + COMPOSITION_PTR_NUCLIDE]; CheckPointer(FUNCTION_NAME, "(nuc)", DATA_ARRAY,nuc); /* Compare */ if (!strcmp(GetText(nuc + NUCLIDE_PTR_NAME), params[j])) break; /* Next */ iso = NextItem(iso); } } /* Check pointer */ if (iso < VALID_PTR) Error(-1, pname, fname, line, "Material %s has no nuclide %s in composition", GetText(mat + MATERIAL_PTR_NAME), params[j]); else j++; /* Remember pointer */ iso0 = iso; /* Read fraction */ val = TestParam(pname, fname, line, params[j++], PTYPE_REAL, -100.0, 1E+25); /* Put value */ WDB[iso + COMPOSITION_ADENS] = val; /* Add to sum */ sum = sum + val; /*******************************************************/ } } /* Set density if sum */ if (RDB[mat + MATERIAL_ADENS] == -INFTY) WDB[mat + MATERIAL_ADENS] = sum; /* Calculate normalized fractions */ IsotopeFractions(mat); } /* Free parameter list */ if (np > 0) for (n = 0; n < np + 1; n++) Mem(MEM_FREE, params[n]); } /* Free memory */ Mem(MEM_FREE, input); /* Next file */ loc0++; } /* This must be called to get the divided compositions into material */ /* structures */ SumDivCompositions(); fprintf(out, "OK.\n\n"); }
void CommandData::ParseArg(wchar *Arg) { if (IsSwitch(*Arg) && !NoMoreSwitches) if (Arg[1]=='-' && Arg[2]==0) NoMoreSwitches=true; else ProcessSwitch(Arg+1); else if (*Command==0) { wcsncpyz(Command,Arg,ASIZE(Command)); *Command=toupperw(*Command); // 'I' and 'S' commands can contain case sensitive strings after // the first character, so we must not modify their case. // 'S' can contain SFX name, which case is important in Unix. if (*Command!='I' && *Command!='S') wcsupper(Command); } else if (*ArcName==0) wcsncpyz(ArcName,Arg,ASIZE(ArcName)); else { // Check if last character is the path separator. size_t Length=wcslen(Arg); wchar EndChar=Length==0 ? 0:Arg[Length-1]; bool EndSeparator=IsDriveDiv(EndChar) || IsPathDiv(EndChar); wchar CmdChar=toupperw(*Command); bool Add=wcschr(L"AFUM",CmdChar)!=NULL; bool Extract=CmdChar=='X' || CmdChar=='E'; if (EndSeparator && !Add) wcsncpyz(ExtrPath,Arg,ASIZE(ExtrPath)); else if ((Add || CmdChar=='T') && (*Arg!='@' || ListMode==RCLM_REJECT_LISTS)) FileArgs.AddString(Arg); else { FindData FileData; bool Found=FindFile::FastFind(Arg,&FileData); if ((!Found || ListMode==RCLM_ACCEPT_LISTS) && ListMode!=RCLM_REJECT_LISTS && *Arg=='@' && !IsWildcard(Arg)) { FileLists=true; ReadTextFile(Arg+1,&FileArgs,false,true,FilelistCharset,true,true,true); } else if (Found && FileData.IsDir && Extract && *ExtrPath==0) { wcsncpyz(ExtrPath,Arg,ASIZE(ExtrPath)); AddEndSlash(ExtrPath,ASIZE(ExtrPath)); } else FileArgs.AddString(Arg); } } }
void CommandData::ProcessSwitch(const wchar *Switch) { switch(toupperw(Switch[0])) { case '@': ListMode=Switch[1]=='+' ? RCLM_ACCEPT_LISTS:RCLM_REJECT_LISTS; break; case 'A': switch(toupperw(Switch[1])) { case 'C': ClearArc=true; break; case 'D': AppendArcNameToPath=true; break; #ifndef SFX_MODULE case 'G': if (Switch[2]=='-' && Switch[3]==0) GenerateArcName=0; else { GenerateArcName=true; wcsncpyz(GenerateMask,Switch+2,ASIZE(GenerateMask)); } break; #endif case 'I': IgnoreGeneralAttr=true; break; case 'N': // Reserved for archive name. break; case 'O': AddArcOnly=true; break; case 'P': wcscpy(ArcPath,Switch+2); break; case 'S': SyncFiles=true; break; default: BadSwitch(Switch); break; } break; case 'C': if (Switch[2]==0) switch(toupperw(Switch[1])) { case '-': DisableComment=true; break; case 'U': ConvertNames=NAMES_UPPERCASE; break; case 'L': ConvertNames=NAMES_LOWERCASE; break; } break; case 'D': if (Switch[2]==0) switch(toupperw(Switch[1])) { case 'S': DisableSortSolid=true; break; case 'H': OpenShared=true; break; case 'F': DeleteFiles=true; break; } break; case 'E': switch(toupperw(Switch[1])) { case 'P': switch(Switch[2]) { case 0: ExclPath=EXCL_SKIPWHOLEPATH; break; case '1': ExclPath=EXCL_BASEPATH; break; case '2': ExclPath=EXCL_SAVEFULLPATH; break; case '3': ExclPath=EXCL_ABSPATH; break; } break; default: if (Switch[1]=='+') { InclFileAttr|=GetExclAttr(Switch+2); InclAttrSet=true; } else ExclFileAttr|=GetExclAttr(Switch+1); break; } break; case 'F': if (Switch[1]==0) FreshFiles=true; else BadSwitch(Switch); break; case 'H': switch (toupperw(Switch[1])) { case 'P': EncryptHeaders=true; if (Switch[2]!=0) { Password.Set(Switch+2); cleandata((void *)Switch,wcslen(Switch)*sizeof(Switch[0])); } else if (!Password.IsSet()) { uiGetPassword(UIPASSWORD_GLOBAL,NULL,&Password); eprintf(L"\n"); } break; default : BadSwitch(Switch); break; } break; case 'I': if (wcsnicomp(Switch+1,L"LOG",3)==0) { wcsncpyz(LogName,Switch[4]!=0 ? Switch+4:DefLogName,ASIZE(LogName)); break; } if (wcsicomp(Switch+1,L"SND")==0) { Sound=true; break; } if (wcsicomp(Switch+1,L"ERR")==0) { MsgStream=MSG_STDERR; // Set it immediately when parsing the command line, so it also // affects messages issued while parsing the command line. SetConsoleMsgStream(MSG_STDERR); break; } if (wcsnicomp(Switch+1,L"EML",3)==0) { wcsncpyz(EmailTo,Switch[4]!=0 ? Switch+4:L"@",ASIZE(EmailTo)); break; } if (wcsicomp(Switch+1,L"M")==0) { MoreInfo=true; break; } if (wcsicomp(Switch+1,L"NUL")==0) { MsgStream=MSG_NULL; SetConsoleMsgStream(MSG_NULL); break; } if (toupperw(Switch[1])=='D') { for (uint I=2;Switch[I]!=0;I++) switch(toupperw(Switch[I])) { case 'Q': MsgStream=MSG_ERRONLY; SetConsoleMsgStream(MSG_ERRONLY); break; case 'C': DisableCopyright=true; break; case 'D': DisableDone=true; break; case 'P': DisablePercentage=true; break; } break; } if (wcsnicomp(Switch+1,L"OFF",3)==0) { switch(Switch[4]) { case 0: case '1': Shutdown=POWERMODE_OFF; break; case '2': Shutdown=POWERMODE_HIBERNATE; break; case '3': Shutdown=POWERMODE_SLEEP; break; case '4': Shutdown=POWERMODE_RESTART; break; } break; } if (wcsicomp(Switch+1,L"VER")==0) { PrintVersion=true; break; } break; case 'K': switch(toupperw(Switch[1])) { case 'B': KeepBroken=true; break; case 0: Lock=true; break; } break; case 'M': switch(toupperw(Switch[1])) { case 'C': { const wchar *Str=Switch+2; if (*Str=='-') for (uint I=0;I<ASIZE(FilterModes);I++) FilterModes[I].State=FILTER_DISABLE; else while (*Str!=0) { int Param1=0,Param2=0; FilterState State=FILTER_AUTO; FilterType Type=FILTER_NONE; if (IsDigit(*Str)) { Param1=atoiw(Str); while (IsDigit(*Str)) Str++; } if (*Str==':' && IsDigit(Str[1])) { Param2=atoiw(++Str); while (IsDigit(*Str)) Str++; } switch(toupperw(*(Str++))) { case 'T': Type=FILTER_PPM; break; case 'E': Type=FILTER_E8; break; case 'D': Type=FILTER_DELTA; break; case 'A': Type=FILTER_AUDIO; break; case 'C': Type=FILTER_RGB; break; case 'I': Type=FILTER_ITANIUM; break; case 'R': Type=FILTER_ARM; break; } if (*Str=='+' || *Str=='-') State=*(Str++)=='+' ? FILTER_FORCE:FILTER_DISABLE; FilterModes[Type].State=State; FilterModes[Type].Param1=Param1; FilterModes[Type].Param2=Param2; } } break; case 'M': break; case 'D': break; case 'S': { wchar StoreNames[1024]; wcsncpyz(StoreNames,(Switch[2]==0 ? DefaultStoreList:Switch+2),ASIZE(StoreNames)); wchar *Names=StoreNames; while (*Names!=0) { wchar *End=wcschr(Names,';'); if (End!=NULL) *End=0; if (*Names=='.') Names++; wchar Mask[NM]; if (wcspbrk(Names,L"*?.")==NULL) swprintf(Mask,ASIZE(Mask),L"*.%ls",Names); else wcsncpyz(Mask,Names,ASIZE(Mask)); StoreArgs.AddString(Mask); if (End==NULL) break; Names=End+1; } } break; #ifdef RAR_SMP case 'T': Threads=atoiw(Switch+2); if (Threads>MaxPoolThreads || Threads<1) BadSwitch(Switch); else { } break; #endif default: Method=Switch[1]-'0'; if (Method>5 || Method<0) BadSwitch(Switch); break; } break; case 'N': case 'X': if (Switch[1]!=0) { StringList *Args=toupperw(Switch[0])=='N' ? &InclArgs:&ExclArgs; if (Switch[1]=='@' && !IsWildcard(Switch)) ReadTextFile(Switch+2,Args,false,true,FilelistCharset,true,true,true); else Args->AddString(Switch+1); } break; case 'O': switch(toupperw(Switch[1])) { case '+': Overwrite=OVERWRITE_ALL; break; case '-': Overwrite=OVERWRITE_NONE; break; case 0: Overwrite=OVERWRITE_FORCE_ASK; break; #ifdef _WIN_ALL case 'C': SetCompressedAttr=true; break; #endif case 'H': SaveHardLinks=true; break; #ifdef SAVE_LINKS case 'L': SaveSymLinks=true; if (toupperw(Switch[2])=='A') AbsoluteLinks=true; break; #endif #ifdef _WIN_ALL case 'N': if (toupperw(Switch[2])=='I') AllowIncompatNames=true; break; #endif case 'R': Overwrite=OVERWRITE_AUTORENAME; break; #ifdef _WIN_ALL case 'S': SaveStreams=true; break; #endif case 'W': ProcessOwners=true; break; default : BadSwitch(Switch); break; } break; case 'P': if (Switch[1]==0) { uiGetPassword(UIPASSWORD_GLOBAL,NULL,&Password); eprintf(L"\n"); } else { Password.Set(Switch+1); cleandata((void *)Switch,wcslen(Switch)*sizeof(Switch[0])); } break; #ifndef SFX_MODULE case 'Q': if (toupperw(Switch[1])=='O') switch(toupperw(Switch[2])) { case 0: QOpenMode=QOPEN_AUTO; break; case '-': QOpenMode=QOPEN_NONE; break; case '+': QOpenMode=QOPEN_ALWAYS; break; default: BadSwitch(Switch); break; } else BadSwitch(Switch); break; #endif case 'R': switch(toupperw(Switch[1])) { case 0: Recurse=RECURSE_ALWAYS; break; case '-': Recurse=RECURSE_DISABLE; break; case '0': Recurse=RECURSE_WILDCARDS; break; case 'I': { Priority=atoiw(Switch+2); if (Priority<0 || Priority>15) BadSwitch(Switch); const wchar *ChPtr=wcschr(Switch+2,':'); if (ChPtr!=NULL) { SleepTime=atoiw(ChPtr+1); if (SleepTime>1000) BadSwitch(Switch); InitSystemOptions(SleepTime); } SetPriority(Priority); } break; } break; case 'S': if (IsDigit(Switch[1])) { Solid|=SOLID_COUNT; SolidCount=atoiw(&Switch[1]); } else switch(toupperw(Switch[1])) { case 0: Solid|=SOLID_NORMAL; break; case '-': Solid=SOLID_NONE; break; case 'E': Solid|=SOLID_FILEEXT; break; case 'V': Solid|=Switch[2]=='-' ? SOLID_VOLUME_DEPENDENT:SOLID_VOLUME_INDEPENDENT; break; case 'D': Solid|=SOLID_VOLUME_DEPENDENT; break; case 'L': if (IsDigit(Switch[2])) FileSizeLess=atoilw(Switch+2); break; case 'M': if (IsDigit(Switch[2])) FileSizeMore=atoilw(Switch+2); break; case 'C': { bool AlreadyBad=false; // Avoid reporting "bad switch" several times. RAR_CHARSET rch=RCH_DEFAULT; switch(toupperw(Switch[2])) { case 'A': rch=RCH_ANSI; break; case 'O': rch=RCH_OEM; break; case 'U': rch=RCH_UNICODE; break; case 'F': rch=RCH_UTF8; break; default : BadSwitch(Switch); AlreadyBad=true; break; }; if (!AlreadyBad) if (Switch[3]==0) CommentCharset=FilelistCharset=ErrlogCharset=RedirectCharset=rch; else for (uint I=3;Switch[I]!=0 && !AlreadyBad;I++) switch(toupperw(Switch[I])) { case 'C': CommentCharset=rch; break; case 'L': FilelistCharset=rch; break; case 'R': RedirectCharset=rch; break; default: BadSwitch(Switch); AlreadyBad=true; break; } // Set it immediately when parsing the command line, so it also // affects messages issued while parsing the command line. SetConsoleRedirectCharset(RedirectCharset); } break; } break; case 'T': switch(toupperw(Switch[1])) { case 'K': ArcTime=ARCTIME_KEEP; break; case 'L': ArcTime=ARCTIME_LATEST; break; case 'O': FileTimeBefore.SetAgeText(Switch+2); break; case 'N': FileTimeAfter.SetAgeText(Switch+2); break; case 'B': FileTimeBefore.SetIsoText(Switch+2); break; case 'A': FileTimeAfter.SetIsoText(Switch+2); break; case 'S': { EXTTIME_MODE Mode=EXTTIME_HIGH3; bool CommonMode=Switch[2]>='0' && Switch[2]<='4'; if (CommonMode) Mode=(EXTTIME_MODE)(Switch[2]-'0'); if (Mode==EXTTIME_HIGH1 || Mode==EXTTIME_HIGH2) // '2' and '3' not supported anymore. Mode=EXTTIME_HIGH3; if (Switch[2]=='-') Mode=EXTTIME_NONE; if (CommonMode || Switch[2]=='-' || Switch[2]=='+' || Switch[2]==0) xmtime=xctime=xatime=Mode; else { if (Switch[3]>='0' && Switch[3]<='4') Mode=(EXTTIME_MODE)(Switch[3]-'0'); if (Mode==EXTTIME_HIGH1 || Mode==EXTTIME_HIGH2) // '2' and '3' not supported anymore. Mode=EXTTIME_HIGH3; if (Switch[3]=='-') Mode=EXTTIME_NONE; switch(toupperw(Switch[2])) { case 'M': xmtime=Mode; break; case 'C': xctime=Mode; break; case 'A': xatime=Mode; break; } } } break; case '-': Test=false; break; case 0: Test=true; break; default: BadSwitch(Switch); break; } break; case 'U': if (Switch[1]==0) UpdateFiles=true; else BadSwitch(Switch); break; case 'V': switch(toupperw(Switch[1])) { case 'P': VolumePause=true; break; case 'E': if (toupperw(Switch[2])=='R') VersionControl=atoiw(Switch+3)+1; break; case '-': VolSize=0; break; default: VolSize=VOLSIZE_AUTO; // UnRAR -v switch for list command. break; } break; case 'W': wcsncpyz(TempPath,Switch+1,ASIZE(TempPath)); AddEndSlash(TempPath,ASIZE(TempPath)); break; case 'Y': AllYes=true; break; case 'Z': if (Switch[1]==0) { // If comment file is not specified, we read data from stdin. wcscpy(CommentFile,L"stdin"); } else wcsncpyz(CommentFile,Switch+1,ASIZE(CommentFile)); break; case '?' : OutHelp(RARX_SUCCESS); break; default : BadSwitch(Switch); break; } }
void CommandData::ParseArg(char *Arg,wchar *ArgW) { if (IsSwitch(*Arg) && !NoMoreSwitches) if (Arg[1]=='-') NoMoreSwitches=true; else ProcessSwitch(&Arg[1],(ArgW!=NULL && *ArgW!=0 ? &ArgW[1]:NULL)); else if (*Command==0) { strncpyz(Command,Arg,ASIZE(Command)); if (ArgW!=NULL) strncpyw(CommandW,ArgW,sizeof(CommandW)/sizeof(CommandW[0])); if (etoupper(*Command)=='S') { const char *SFXName=Command[1] ? Command+1:DefSFXName; if (PointToName(SFXName)!=SFXName || FileExist(SFXName)) strcpy(SFXModule,SFXName); else GetConfigName(SFXName,SFXModule,true); } #ifndef GUI *Command=etoupper(*Command); if (*Command!='I' && *Command!='S') strupper(Command); #endif } else if (*ArcName==0) { strncpyz(ArcName,Arg,ASIZE(ArcName)); if (ArgW!=NULL) strncpyzw(ArcNameW,ArgW,ASIZE(ArcNameW)); } else { size_t Length=strlen(Arg); char EndChar=Length==0 ? 0:Arg[Length-1]; char CmdChar=etoupper(*Command); bool Add=strchr("AFUM",CmdChar)!=NULL; bool Extract=CmdChar=='X' || CmdChar=='E'; if ((IsDriveDiv(EndChar) || IsPathDiv(EndChar)) && !Add) { strncpyz(ExtrPath,Arg,ASIZE(ExtrPath)); if (ArgW!=NULL) strncpyzw(ExtrPathW,ArgW,ASIZE(ExtrPathW)); } else if ((Add || CmdChar=='T') && *Arg!='@') FileArgs->AddString(Arg); else { struct FindData FileData; bool Found=FindFile::FastFind(Arg,NULL,&FileData); if (!Found && *Arg=='@' && !IsWildcard(Arg)) { FileLists=true; RAR_CHARSET Charset=FilelistCharset; #if defined(_WIN_32) && !defined(GUI) // for compatibility reasons we use OEM encoding // in Win32 console version by default if (Charset==RCH_DEFAULT) Charset=RCH_OEM; #endif ReadTextFile(Arg+1,FileArgs,false,true,Charset,true,true,true); } else if (Found && FileData.IsDir && Extract && *ExtrPath==0) { strcpy(ExtrPath,Arg); AddEndSlash(ExtrPath); } else FileArgs->AddString(Arg); } } }
tstring ReadTextFile(const tstring & file, DirectoryMode directory) { tstring text; ReadTextFile(file, text, directory); return text; }
bool CClientFXDB::ReadFXProp( bool bText, ILTStream* pFxFile, FX_PROP& fxProp ) { if( bText ) { // Read in the name ReadTextFile( pFxFile, "%s %s", fxProp.m_sName ); // Read the type ReadTextFile( pFxFile, "%s %i", &fxProp.m_nType ); // Read the data switch (fxProp.m_nType) { case FX_PROP::STRING : ReadTextFile( pFxFile, "%s %s", fxProp.m_data.m_sVal ); break; case FX_PROP::INTEGER : ReadTextFile( pFxFile, "%s %i", &fxProp.m_data.m_nVal ); break; case FX_PROP::FLOAT : ReadTextFile( pFxFile, "%s %f", &fxProp.m_data.m_fVal ); break; case FX_PROP::COMBO : ReadTextFile( pFxFile, "%s %s", fxProp.m_data.m_sVal ); break; case FX_PROP::VECTOR : ReadTextFile( pFxFile, "%s %f %f %f", &fxProp.m_data.m_fVec[0], &fxProp.m_data.m_fVec[1], &fxProp.m_data.m_fVec[2] ); break; case FX_PROP::VECTOR4 : ReadTextFile( pFxFile, "%s %f %f %f %f", &fxProp.m_data.m_fVec4[0], &fxProp.m_data.m_fVec4[1], &fxProp.m_data.m_fVec4[2], &fxProp.m_data.m_fVec4[3] ); break; case FX_PROP::CLRKEY : { LTFLOAT r, g, b, a; ReadTextFile( pFxFile, "%s %f %f %f %f %f", &fxProp.m_data.m_clrKey.m_tmKey, &r, &g, &b, &a ); DWORD dwRed = (int)(r * 255.0f); DWORD dwGreen = (int)(g * 255.0f); DWORD dwBlue = (int)(b * 255.0f); DWORD dwAlpha = (int)(a * 255.0f); fxProp.m_data.m_clrKey.m_dwCol = dwRed | (dwGreen << 8) | (dwBlue << 16) | (dwAlpha << 24); } break; case FX_PROP::PATH : ReadTextFile( pFxFile, "%s %s", fxProp.m_data.m_sVal ); break; } } else { BYTE nameLen; pFxFile->Read(&nameLen, 1); // Read in the name pFxFile->Read(&fxProp.m_sName, nameLen); // Read the type pFxFile->Read(&fxProp.m_nType, sizeof(FX_PROP::eDataType)); // Read the data switch (fxProp.m_nType) { case FX_PROP::STRING : pFxFile->Read(&fxProp.m_data.m_sVal, 128); break; case FX_PROP::INTEGER : pFxFile->Read(&fxProp.m_data.m_nVal, sizeof(int)); break; case FX_PROP::FLOAT : pFxFile->Read(&fxProp.m_data.m_fVal, sizeof(float)); break; case FX_PROP::COMBO : pFxFile->Read(&fxProp.m_data.m_sVal, 128); break; case FX_PROP::VECTOR : pFxFile->Read(&fxProp.m_data.m_fVec, sizeof(float) * 3); break; case FX_PROP::VECTOR4 : pFxFile->Read(&fxProp.m_data.m_fVec4, sizeof(float) * 4); break; case FX_PROP::CLRKEY : pFxFile->Read(&fxProp.m_data.m_clrKey, sizeof(FX_PROP::FX_CLRKEY) ); break; case FX_PROP::PATH : pFxFile->Read(&fxProp.m_data.m_sVal, 128); break; } } return true; }
void ParseDirective(TokenVector tokens, TokenVector* fileTokens, int index, PrepocContext* context){ if(tokens.length < 2 || !TOKEN_IS(tokens.vals[0], "#")){ printf("\n\nError: malformed preproc directive (length %d): \n", tokens.length); for(int i = 0; i < tokens.length; i++){ printf("'%.*s', ", tokens.vals[i].length, tokens.vals[i].start); } printf("\n"); } Token directiveType = tokens.vals[1]; //printf("Directive type: '%.*s'\n", tokens.vals[1].length, tokens.vals[1].start); if(context->ifLevels > 0){ if(TOKEN_IS(directiveType, "if")){ context->ifLevels++; } else if(TOKEN_IS(directiveType, "ifdef")){ context->ifLevels++; } else if(TOKEN_IS(directiveType, "ifndef")){ context->ifLevels++; } else if(TOKEN_IS(directiveType, "endif")){ context->ifLevels--; } } else{ if(TOKEN_IS(directiveType, "include")){ Token data = tokens.vals[2]; if(TOKEN_IS(data, "<")){ //TODO: Fix up issues } else{ int fileOpenIdx = -1; for(int i = 0; i < openFiles.length; i++){ if(data.start > openFiles.vals[i].start && data.start < (openFiles.vals[i].start + openFiles.vals[i].length)){ fileOpenIdx = i; break; } } Token currentFileName = openFiles.vals[fileOpenIdx].fileName; while(currentFileName.length > 0 && currentFileName.start[currentFileName.length] != '/'){ currentFileName.length--; } char path[256] = {0}; snprintf(path, 256, "%.*s/%.*s", currentFileName.length, currentFileName.start, data.length - 2, data.start + 1); int fileSize; char* fileBuffer = ReadTextFile(path, &fileSize); OpenFileInfo fileOp = {fileBuffer, fileSize, {data.start+1, data.length-2}}; VectorAddOpenFileInfo(&openFiles, fileOp); printf("About to process included file.\n"); TokenVector lexedIncludedFile = PreprocessString(fileBuffer); printf("Processed included file.\n"); VectorInsertVectorToken(fileTokens, index, lexedIncludedFile); printf("Added included tokens.\n"); } } else if(TOKEN_IS(directiveType, "define")){ Token macroName = tokens.vals[2]; if(tokens.length > 3 && TOKEN_IS(tokens.vals[3], "(") && tokens.vals[2].start + tokens.vals[2].length == tokens.vals[3].start){ //printf("Preproc func\n"); PreprocDefFunc defFunc = {0}; defFunc.name = macroName; int i = 4; for( ; i < tokens.length; i++){ if(TOKEN_IS(tokens.vals[i], ")")){ i++; break; } else if(!TOKEN_IS(tokens.vals[i], ",")){ VectorAddToken(&defFunc.args, tokens.vals[i]); } } for( ; i < tokens.length; i++){ VectorAddToken(&defFunc.result, tokens.vals[i]); } VectorAddPreprocDefFunc(&context->funcDefs, defFunc); } else{ //printf("Preproc subst def.\n"); PreprocDef def = {0}; def.name = macroName; for(int i = 3; i < tokens.length; i++){ VectorAddToken(&def.val, tokens.vals[i]); } //printf("Preproc define '%.*s' && '%.*s'\n", def.name.length, def.name.start, def.val.vals[0].length, def.val.vals[0].start); VectorAddPreprocDef(&context->simpleDefs, def); } } else if(TOKEN_IS(directiveType, "if")){ } else if(TOKEN_IS(directiveType, "ifdef")){ int isDefined = 0; for(int i = 0; i < context->simpleDefs.length; i++){ if(TokenEqual(context->simpleDefs.vals[i].name, tokens.vals[2])){ isDefined = 1; break; } } for(int i = 0; i < context->funcDefs.length; i++){ if(TokenEqual(context->funcDefs.vals[i].name, tokens.vals[2])){ isDefined = 1; break; } } if(!isDefined){ printf("Found ifdef that is not defined.\n"); context->ifLevels = 1; } } else if(TOKEN_IS(directiveType, "ifndef")){ int isDefined = 0; for(int i = 0; i < context->simpleDefs.length; i++){ if(TokenEqual(context->simpleDefs.vals[i].name, tokens.vals[2])){ isDefined = 1; break; } } for(int i = 0; i < context->funcDefs.length; i++){ if(TokenEqual(context->funcDefs.vals[i].name, tokens.vals[2])){ isDefined = 1; break; } } if(isDefined){ context->ifLevels = 1; } } else if(TOKEN_IS(directiveType, "line")){ //TODO } else if(TOKEN_IS(directiveType, "undef")){ for(int i = 0; i < context->simpleDefs.length; i++){ if(TokenEqual(context->simpleDefs.vals[i].name, tokens.vals[2])){ VectorRemovePreprocDef(&context->simpleDefs, i); break; } } for(int i = 0; i < context->funcDefs.length; i++){ if(TokenEqual(context->funcDefs.vals[i].name, tokens.vals[2])){ VectorRemovePreprocDefFunc(&context->funcDefs, i); break; } } } else if(TOKEN_IS(directiveType, "endif")){ //Do nothing, we're closing off an active if block } } }
void CommandData::ParseArg(char *Arg,wchar *ArgW) { if (IsSwitch(*Arg) && !NoMoreSwitches) if (Arg[1]=='-') NoMoreSwitches=true; else ProcessSwitch(&Arg[1]); else if (*Command==0) { strncpy(Command,Arg,sizeof(Command)); if (ArgW!=NULL) strncpyw(CommandW,ArgW,sizeof(CommandW)/sizeof(CommandW[0])); if (toupper(*Command)=='S') { const char *SFXName=Command[1] ? Command+1:DefSFXName; if (PointToName(SFXName)!=SFXName || FileExist(SFXName)) strcpy(SFXModule,SFXName); else GetConfigName(SFXName,SFXModule,true); } #ifndef GUI *Command=toupper(*Command); if (*Command!='I' && *Command!='S') strupper(Command); #endif } else if (*ArcName==0) { strncpy(ArcName,Arg,sizeof(ArcName)); if (ArgW!=NULL) strncpyw(ArcNameW,ArgW,sizeof(ArcNameW)/sizeof(ArcNameW[0])); } else { int Length=strlen(Arg); char EndChar=Arg[Length-1]; char CmdChar=toupper(*Command); bool Add=strchr("AFUM",CmdChar)!=NULL; bool Extract=CmdChar=='X' || CmdChar=='E'; if ((IsDriveDiv(EndChar) || IsPathDiv(EndChar)) && !Add) strcpy(ExtrPath,Arg); else if ((Add || CmdChar=='T') && *Arg!='@') FileArgs->AddString(Arg); else { struct FindData FileData; bool Found=FindFile::FastFind(Arg,NULL,&FileData); if (!Found && *Arg=='@' && !IsWildcard(Arg)) { ReadTextFile(Arg+1,FileArgs,false,true,true,true,true); FileLists=true; } else if (Found && FileData.IsDir && Extract && *ExtrPath==0) { strcpy(ExtrPath,Arg); AddEndSlash(ExtrPath); } else FileArgs->AddString(Arg); } } }
int main(int argc, const char * argv[]) { if (argc < 5) { printf("!!!Error: Not enough arguments. <first_long_number_filename> [ + | - | * | / | % | ^ ] <second_long_number_filename> <result_long_number_filename>!!!\n"); return 0; } if (argc > 7) { printf("!!!Error: Many arguments. <first_long_number_filename> [ + | - | * | / | % | ^ ] <second_long_number_filename> <result_long_number_filename> <module_long_number_filename> <-b>!!!\n"); return 0; } FILE* firstLongNumFile = fopen(argv[1], "r"); if (!firstLongNumFile) //проверка открытия первого файла с числом { printf("!!!Error: Unable to open file: %s !!!\n", argv[1]); return 0; } fclose(firstLongNumFile); const char* operation = argv[2]; if ((strlen(operation) > 1 || operation[0] == '\0') || operation[0] != '+' && operation[0] != '-' && operation[0] != '*' && operation[0] != '/' && operation[0] != '%' && operation[0] != '^') //проверка оператора { printf("!!!Error: Wrong operation: %s !!!\n", operation); return 0; } FILE* secondLongNumFile = fopen(argv[3], "r"); //проверка открытия второго файла с числом if (!secondLongNumFile) { printf("!!!Error: Unable to open file: %s !!!\n", argv[3]); return 0; } fclose(secondLongNumFile); FILE* resultLongNumFile = fopen(argv[4], "r"); if (!resultLongNumFile) //проверка открытия файла для результата { printf("!!!Error: Unable to open file: %s !!!\n", argv[4]); return 0; } fclose(resultLongNumFile); //////////////////////////////////////////////////////////////////////////////// int bin = 0; //флаг для бинарного файла if (argc == 5) if (argv[2][0] == '^') { printf("!!!Error: Input module file!!!\n"); return 0; } if (argc == 6) { if (argv[2][0] == '^') { FILE* moduleLongNumFile = fopen(argv[5], "r"); if (!moduleLongNumFile) { printf("!!!Error: Unable to open file: %s !!!\n", argv[5]); return 0; } fclose(moduleLongNumFile); } else { if (strcmp(argv[5], "-b")) { printf("!!!Error: Invalid flag: %s !!!\n", argv[5]); return 0; } bin = 1; } } if (argc == 7) { FILE* moduleLongNumFile = fopen(argv[5], "r"); if (!moduleLongNumFile) { printf("!!!Error: Unable to open file: %s !!!\n", argv[5]); return 0; } fclose(moduleLongNumFile); if (strcmp(argv[6], "-b")) { printf("!!!Error: Invalid flag: %s !!!\n", argv[6]); return 0; } bin = 1; } struct LongNumber a, b; //загружаем первое число из бинарного файла if (bin == 1) a = ReadBinFile(argv[1]); else a = ReadTextFile(argv[1]); //загружаем второе число из бинарного файла if (bin == 1) b = ReadBinFile(argv[3]); else b = ReadTextFile(argv[3]); //выполняем операцию struct LongNumber result; switch (operation[0]) { case '+': { result = ADD(a, b); break; } case '-': { result = SUB(a, b); break; } case '*': { result = MUL(a, b); break; } case '/': { result = DIV(a, b, 1); break; } case '%': { result = DIV(a, b, 2); break; } case '^': { struct LongNumber c; if (bin == 1) c = ReadBinFile(argv[5]); else c = ReadTextFile(argv[5]); result = DEGREE(a, b, c); c = clear(c); break; } default: break; } //записываем в файл результат if (bin == 1) WriteBinFile(argv[4], result); else WriteTextFile(argv[4], result); a = clear(a); b = clear(b); result = clear(result); return 0; }
// --------------------------------------------------------------------------- // CWinMenubar::AboutProc() // Dialog Window proc for About dialog // --------------------------------------------------------------------------- BOOL CALLBACK CWinMenubar::AboutProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); // unless SDK_REGISTRATION is defined switch (message) { case WM_INITDIALOG: { TCHAR text[128]; CWinMenubar* menubar = (CWinMenubar*)lParam; HINSTANCE hMod = menubar->ModuleHandle(); GetWindowText(GetParent(hDlg), text, sizeof(text)/sizeof(text[0])); SetWindowText(hDlg, text); HBITMAP hBitmap = NULL; UINT textScrollID = IDC_ABOUT_TEXT_SCROLL; UINT textNoScrollID = IDC_ABOUT_TEXT_NO_SCROLL; UINT setTextMsg = WM_SETTEXT; WPARAM setTextParam = 0; SETTEXTEX setText; setText.flags = ST_SELECTION; setText.codepage = CP_ACP; char* aboutText = NULL; if (menubar->iRichEdit) { aboutText = ReadTextFile(ABOUTBOX_RTF_FILE); } if (aboutText) { setTextMsg = EM_SETTEXTEX; textScrollID = textNoScrollID = IDC_ABOUT_RICHTEXT; setTextParam = (WPARAM)&setText; hBitmap = LoadBitmap(hMod,MAKEINTRESOURCE(IDB_JAVA_POWERED)); #ifdef HAVE_WLIB HWND hText = GetDlgItem(hDlg, IDC_ABOUT_RICHTEXT); SendMessage(hText, EM_SETEVENTMASK, 0, SendMessage(hText, EM_GETEVENTMASK, 0,0) | ENM_LINK); SendMessage(hText, EM_AUTOURLDETECT, TRUE, 0); #endif // HAVE_WLIB } if (!aboutText && menubar->iRichEdit) { // Load default about text from the resource void* ptr = NULL; UINT size = 0; HGLOBAL hg = 0; HRSRC hr = FindResourceA(hMod,MAKEINTRESOURCEA(IDR_ABOUT_RTF),"RTF"); if (hr) { size = SizeofResource(ModuleHandle(), hr); hg = LoadResource(ModuleHandle(), hr); ptr = LockResource(hg); } if (ptr) { aboutText = (char*)Alloc(size+1); if (aboutText) { memcpy(aboutText, ptr, size); aboutText[size] = 0; setTextMsg = EM_SETTEXTEX; textScrollID = IDC_ABOUT_RICHTEXT; textNoScrollID = IDC_ABOUT_RICHTEXT; hBitmap = LoadBitmap(hMod,MAKEINTRESOURCE(IDB_JAVA_POWERED)); setTextParam = (WPARAM)&setText; } UnlockResource(hg); } } if (aboutText) { // Check if we need the scrollbar. 12 lines of text // will fit into the edit control. HWND hText = GetDlgItem(hDlg, textNoScrollID); SendMessageA(hText,setTextMsg,setTextParam,(LPARAM)aboutText); if (SendMessageA(hText, EM_GETLINECOUNT,0,0) <= 12) { // No need for the scrollbar, show the edit // control without the WS_VSCROLL style ShowWindow(hText, SW_SHOWNORMAL); } else { // We need the vertical scrollbar, show the edit control // with the WS_VSCROLL style. Note that textScrollID and // textNoScrollID may point to the same window, so reset // the text in the control (bug #DPEV-6JUJSQ) hText = GetDlgItem(hDlg, textScrollID); SendMessageA(hText,WM_SETTEXT,0,(LPARAM)""); SendMessageA(hText,setTextMsg,setTextParam,(LPARAM)aboutText); ShowWindow(hText, SW_SHOWNORMAL); } // Add full SDK name to the RichEdit control by replacing <sdk_name> tag with the // name defined in SdkProductInfo.h. Note that decision between MIDP and C++ SDK // product names is made using CWinMenubar iMidpSdk member. static const TCHAR keywordHeading[] = TEXT("<sdk_name>"); static const UINT keywordHeadingLen = COUNT(keywordHeading)-1; FINDTEXT findHeading; ZeroMemory(&findHeading, sizeof(findHeading)); findHeading.chrg.cpMax = -1; findHeading.lpstrText = (LPTSTR)keywordHeading; // Select whole content SendMessage(hText, EM_SETSEL, 0, 0); // Find from selection int pos = SendMessage(hText,EM_FINDTEXT, FR_MATCHCASE|FR_DOWN, (LPARAM)&findHeading); if (pos >= 0) { // Sdk name tag found IRichEditOle* re = NULL; SendMessage(hText, EM_GETOLEINTERFACE, 0, (LPARAM)&re); if (re) { // Select SDK name tag and replace it with the full SDK name SendMessage(hText, EM_SETSEL, pos, pos+keywordHeadingLen); if(menubar->iMidpSDK) SendMessage(hText, EM_REPLACESEL, true, (LPARAM)TEXT(SDK_FULL_PRODUCT_NAME_MIDP)); else SendMessage(hText, EM_REPLACESEL, true, (LPARAM)TEXT(SDK_FULL_PRODUCT_NAME_CPP)); re->Release(); } } if (hBitmap) { static const TCHAR keyword[] = TEXT("<java logo>"); static const UINT keywordLen = COUNT(keyword)-1; FINDTEXT find; ZeroMemory(&find, sizeof(find)); find.chrg.cpMax = -1; find.lpstrText = (LPTSTR)keyword; SendMessage(hText, EM_SETSEL, 0, 0); int pos = SendMessage(hText,EM_FINDTEXT, FR_MATCHCASE|FR_DOWN, (LPARAM)&find); if (pos >= 0) { IRichEditOle* re = NULL; SendMessage(hText, EM_GETOLEINTERFACE, 0, (LPARAM)&re); if (re) { CImageDataObject* bmp = new CImageDataObject(hBitmap); if (bmp) { SendMessage(hText,EM_SETSEL,pos,pos+keywordLen); bmp->Insert(re); bmp->Release(); } re->Release(); } } } Free(aboutText); } #ifdef SDK_REGISTRATION // Show product key if (gRegProductContext) { HWND hProductKey = GetDlgItem(hDlg, IDC_PRODUCT_KEY); const char* szKey = REG_ProductKey(gRegProductContext); SetWindowTextA(hProductKey, szKey); // The control is created invisible, show it ShowWindow(hProductKey, SW_SHOWNORMAL); if (REG_ProductStatus(gRegProductContext) != RegRegistered) { // Show the Register button ShowWindow(GetDlgItem(hDlg, IDC_REGISTER), SW_SHOWNORMAL); } } #endif // SDK_REGISTRATION // Subclass the product name control HWND hName = GetDlgItem(hDlg, IDC_PRODUCT_NAME); HINSTANCE hInst = (HINSTANCE)GetWindowLong(hDlg,GWL_HINSTANCE); if (hName) { // Allocate TitleData structure. It will be deallocated // by TitleWndProc when it receives WM_DESTROY message TitleData* data = (TitleData*)malloc(sizeof(TitleData)); if (data) { LOGFONTA logFont; ZeroMemory(data, sizeof(*data)); ZeroMemory(&logFont, sizeof(logFont)); logFont.lfHeight = 24; logFont.lfWeight = FW_BOLD; logFont.lfCharSet = ANSI_CHARSET; logFont.lfOutPrecision = OUT_DEFAULT_PRECIS; logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS; logFont.lfQuality = ANTIALIASED_QUALITY; logFont.lfPitchAndFamily = VARIABLE_PITCH; // Try Nokia font first strcpy(logFont.lfFaceName, "Nokia Sans"); data->hFont = CreateFontIndirectA(&logFont); if (!data->hFont) { // No Nokia font, try Arial then strcpy(logFont.lfFaceName, "Arial"); data->hFont = CreateFontIndirectA(&logFont); } // Load bitmaps data->hBitmap = LoadBitmapA(hInst, MAKEINTRESOURCEA(IDB_ABOUT_TOP)); // load product name from the file data->productName = ReadTextFile(PRODUCTNAME_FILE); data->productId = menubar->GetProductId(); // Request initial bitmap data->bRepaint = TRUE; #ifdef SDK_REGISTRATION data->hGradientBitmap = LoadBitmapA(hInst, MAKEINTRESOURCEA(IDB_ABOUT_GRADIENT)); if (gRegProductContext) { data->scrollText = TitleCreateScrollData(hName, gRegProductContext); if (data->scrollText) { // Initial delay SetTimer(hName, SCROLL_DELAY_TIMER, SCROLL_TIMER_DELAY, NULL); } } #endif // SDK_REGISTRATION // Subclass the window data->superProc = (WNDPROC)GetWindowLong(hName,GWL_WNDPROC); SetWindowLong(hName, GWL_USERDATA, (LONG)data); SetWindowLong(hName, GWL_WNDPROC, (LONG)TitleWndProc); } } #ifdef HAVE_WLIB WIN32_CenterWindow(hDlg, NULL); #endif // HAVE_WLIB return TRUE; } case WM_COMMAND: switch (wParam) { #ifdef SDK_REGISTRATION case IDC_REGISTER: if (REG_RegisterNow(gRegProductContext, hDlg)) { TitleStopScroller(hDlg); // Update the scroller HWND hTitle = GetDlgItem(hDlg, IDC_PRODUCT_NAME); ScrollTextData* scroll = TitleCreateScrollData( hTitle, gRegProductContext); if (scroll) { TitleData* data; data = (TitleData*)GetWindowLong(hTitle,GWL_USERDATA); TitleDeleteScrollData(data->scrollText); data->scrollText = scroll; } } if (REG_ProductStatus(gRegProductContext) == RegRegistered) { // The button has served its purpose. Hide it ShowWindow(GetDlgItem(hDlg, IDC_REGISTER), SW_HIDE); } return TRUE; #endif // SDK_REGISTRATION case IDOK: case IDCANCEL: EndDialog(hDlg, wParam); return TRUE; default: return FALSE; } #ifdef HAVE_WLIB // Need wlib to use WIN32_BrowseURL case WM_NOTIFY: if (((LPNMHDR)lParam)->idFrom == IDC_ABOUT_RICHTEXT) { char url[256]; ENLINK* link = (ENLINK*)lParam; if (link->msg == WM_LBUTTONDOWN && (link->chrg.cpMax - link->chrg.cpMin) < (COUNT(url)/2-1)) // EM_GETTEXTRANGE may think it's in WCHARs { // Visual effect HWND hText = link->nmhdr.hwndFrom; SendMessage(hText,EM_SETSEL,link->chrg.cpMin,link->chrg.cpMax); // It's not very clear what EM_GETTEXTRANGE message writes // into the buffer. Since we use SendMessageA (ANSI API), // I would expect that it returns ANSI string as most other // text-related messages do. Yet, at least some versions of // RichEdit control seem to return UCS-2 characters. Internet // search produces conflicting results. Let's be prepared for // anything. After all, there are only two possiblities. It's // either UCS-2 or ASCII. TEXTRANGEA range; range.chrg = link->chrg; range.lpstrText = url; url[0] = url[1] = 0; SendMessageA(hText, EM_GETTEXTRANGE, 0, (LPARAM)&range); url[COUNT(url)-1] = url[COUNT(url)-2] = 0; if (!_wcsnicmp((WCHAR*)url,L"http://",7)) { // Looks like UCS-2 string to me. Convert it to ASCII LPWSTR w = (WCHAR*)url; LPSTR p = url; do { *p++ = (char)*w++; } while (*w); *p = 0; } // Start the default browser WIN32_BrowseURL(url); } } // Usually, the return value is ignored return FALSE; #endif // HAVE_WLIB #ifdef SDK_REGISTRATION case WM_CTLCOLORSTATIC: // We don't want the product key edit control to erase its // background because it's drawn on top of the product name // bitmap (white cloud). { int nDlgCtrlID = GetDlgCtrlID((HWND)lParam); switch (nDlgCtrlID) { case IDC_PRODUCT_KEY: // Return transparent brush for the product key control return (BOOL)GetStockObject(HOLLOW_BRUSH); } } return FALSE; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: // Stop scrolling on mouse click TitleStopScroller(hDlg); return FALSE; #endif // SDK_REGISTRATION default: return FALSE; } }
bool CClientFXDB::ReadFXKey( bool bText, ILTStream* pFxFile, float fTotalTime, FX_KEY* pKey, FX_PROP* pPropBuffer, uint32 nBuffLen ) { // Read in the reference name char sTmp[128]; if( bText ) { ReadTextFile( pFxFile, "%s %s", sTmp ); } else { pFxFile->Read(sTmp, 128); } pKey->m_pFxRef = FindFX( strtok(sTmp, ";" )); // Read in the key ID if( bText ) { ReadTextFile( pFxFile, "%s %lu", &pKey->m_dwID ); } else { pFxFile->Read(&pKey->m_dwID, sizeof(uint32)); } // Read in the link status LINK_STATUS ls; if( bText ) { ReadTextFile( pFxFile, "%s %i", &ls.m_bLinked ); ReadTextFile( pFxFile, "%s %lu", &ls.m_dwLinkedID ); //read in the linked node name but make sure that it is cleared out first ls.m_sLinkedNodeName[0] = '\0'; ReadTextFile( pFxFile, "%s %s", ls.m_sLinkedNodeName ); } else { pFxFile->Read(&ls, sizeof(LINK_STATUS)); } pKey->m_bLinked = ls.m_bLinked; pKey->m_dwLinkedID = ls.m_dwLinkedID; strcpy(pKey->m_sLinkedNodeName, ls.m_sLinkedNodeName); //check to make sure that the key is not motion linked to itself though if(pKey->m_bLinked && (pKey->m_dwLinkedID == pKey->m_dwID)) { pKey->m_bLinked = false; } // Read in the start time if( bText ) { ReadTextFile( pFxFile, "%s %f", &pKey->m_tmStart ); } else { pFxFile->Read(&pKey->m_tmStart, sizeof(float)); } // Read in the end time if( bText ) { ReadTextFile( pFxFile, "%s %f", &pKey->m_tmEnd ); } else { pFxFile->Read(&pKey->m_tmEnd, sizeof(float)); } // Read in the key repeat uint32 nKeyRepeats = 0; if( bText ) { ReadTextFile( pFxFile, "%s %lu", &nKeyRepeats ); } else { pFxFile->Read(&nKeyRepeats, sizeof(uint32)); } // Read in dummy values uint32 dwDummy; LTFLOAT fDummy; if( bText ) { ReadTextFile( pFxFile, "%s %lu", &dwDummy ); ReadTextFile( pFxFile, "%s %f", &fDummy ); ReadTextFile( pFxFile, "%s %f", &fDummy ); } else { pFxFile->Read(&dwDummy, sizeof(uint32)); pFxFile->Read(&dwDummy, sizeof(uint32)); pFxFile->Read(&dwDummy, sizeof(uint32)); } // Read in the number of properties uint32 dwNumProps; if( bText ) { ReadTextFile( pFxFile, "%s %lu", &dwNumProps ); } else { pFxFile->Read(&dwNumProps, sizeof(uint32)); } for (uint32 k = 0; k < dwNumProps; k ++) { if(k >= nBuffLen) { assert(!"Error: Found a key with too many properties, truncating additional properties"); break; } else { ReadFXProp( bText, pFxFile, pPropBuffer[k] ); } } //ok, we can now convert our properties over to the appropriate form int32 nFXID = FindFXID(pKey->m_pFxRef->m_sName); if(nFXID < 0) return false; //alright, get our property object pKey->m_pProps = m_pfnCreatePropList(nFXID); if(!pKey->m_pProps) return false; //make sure to clamp the times to always be between 0 and the length of the group, //otherwise numerical accuracy problems will arise pKey->m_tmStart = LTCLAMP(pKey->m_tmStart, 0.0f, fTotalTime); pKey->m_tmEnd = LTCLAMP(pKey->m_tmEnd, 0.0f, fTotalTime); //now setup the lifespan of the key pKey->m_pProps->SetLifetime(pKey->m_tmEnd - pKey->m_tmStart, nKeyRepeats); //and let it convert its properties if(!pKey->m_pProps->ParseProperties(pPropBuffer, k)) { m_pfnFreePropList(pKey->m_pProps); pKey->m_pProps = NULL; return false; } //setup this key (read out our keys and base properties) SetupKey(pKey, pPropBuffer, k); return true; }
bool CClientFXDB::ReadFXGroup( bool bText, ILTStream* pFxFile, FX_GROUP* pFxGroup, FX_PROP* pPropBuffer, uint32 nBuffLen ) { assert(pFxGroup); //make sure to clear out any data already in the effect group pFxGroup->Term(); // Read in the number of FX in this group uint32 dwNumFx = 0; uint32 dwPhaseLen = 0; if( bText ) { // Read in the name of this FX group ReadTextFile( pFxFile, "%s %s", pFxGroup->m_sName ); ReadTextFile( pFxFile, "%s %lu", &dwNumFx ); // Read in the phase length ReadTextFile( pFxFile, "%s %lu", &dwPhaseLen ); } else { pFxFile->Read(&dwNumFx, sizeof(uint32)); // Read in the name of this FX group pFxFile->Read(pFxGroup->m_sName, 128); // Read in the phase length pFxFile->Read(&dwPhaseLen, sizeof(dwPhaseLen)); } // Initialize total time to zero, then find the total time // as we read in the keys. pFxGroup->m_tmTotalTime = dwPhaseLen / 1000.0f; //allocate room for the FX pFxGroup->m_pKeys = debug_newa(FX_KEY, dwNumFx); if(!pFxGroup->m_pKeys) return false; //save the number of keys pFxGroup->m_nNumKeys = dwNumFx; // Read in the FXKey for( uint32 nCurrEffect = 0; nCurrEffect < dwNumFx; nCurrEffect ++ ) { ReadFXKey( bText, pFxFile, pFxGroup->m_tmTotalTime, &pFxGroup->m_pKeys[nCurrEffect], pPropBuffer, nBuffLen ); } //we need to sort the effects based upon the order that they need to be created in. The creation //order needs to have any effects that are motion linked come last so that they can have the //effects that they are linked to created before them //This sort is a sort of bubble sort where it will go through and if it finds any effects //that violate this property, it will correct them. It needs to take care to properly handle //cyclic graphs though, which are invalid for(uint32 nCurrPass = 0; nCurrPass < dwNumFx; nCurrPass++) { bool bDoneSorting = true; //take a pass through to sort... for(uint32 nCurrKey = 0; nCurrKey < dwNumFx; nCurrKey++) { //see if this effect is motion linked, if not we don't need to worry if(!pFxGroup->m_pKeys[nCurrKey].m_bLinked) continue; //get the ID of the node we are linked to uint32 nLinkID = pFxGroup->m_pKeys[nCurrKey].m_dwLinkedID; //it is linked, we need to see if the effect that it is linked to comes after for(uint32 nCurrLink = nCurrKey + 1; nCurrLink < dwNumFx; nCurrLink++) { if(pFxGroup->m_pKeys[nCurrLink].m_dwID == nLinkID) { //this is the effect and it does come after, so we need to swap it FX_KEY TempKey = pFxGroup->m_pKeys[nCurrKey]; pFxGroup->m_pKeys[nCurrKey] = pFxGroup->m_pKeys[nCurrLink]; pFxGroup->m_pKeys[nCurrLink] = TempKey; //we have to take another pass again just to make sure bDoneSorting = false; break; } } } //see if we are done sorting if(bDoneSorting) break; } //alright, by this time either we are in order, or there is a cyclic dependency return true; }
void CommandData::ProcessSwitch(char *Switch) { switch(toupper(Switch[0])) { case 'I': if (strnicomp(&Switch[1],"LOG",3)==0) { strncpy(LogName,Switch[4] ? Switch+4:DefLogName,sizeof(LogName)); break; } if (stricomp(&Switch[1],"SND")==0) { Sound=true; break; } if (stricomp(&Switch[1],"ERR")==0) { MsgStream=MSG_STDERR; break; } if (strnicomp(&Switch[1],"EML",3)==0) { strncpy(EmailTo,Switch[4] ? Switch+4:"@",sizeof(EmailTo)); EmailTo[sizeof(EmailTo)-1]=0; break; } if (stricomp(&Switch[1],"NUL")==0) { MsgStream=MSG_NULL; break; } if (toupper(Switch[1])=='D') { for (int I=2;Switch[I]!=0;I++) switch(toupper(Switch[I])) { case 'Q': MsgStream=MSG_ERRONLY; break; case 'C': DisableCopyright=true; break; case 'D': DisableDone=true; break; case 'P': DisablePercentage=true; break; } break; } if (stricomp(&Switch[1],"OFF")==0) { Shutdown=true; break; } break; case 'T': switch(toupper(Switch[1])) { case 'K': ArcTime=ARCTIME_KEEP; break; case 'L': ArcTime=ARCTIME_LATEST; break; case 'O': FileTimeBefore.SetAgeText(Switch+2); break; case 'N': FileTimeAfter.SetAgeText(Switch+2); break; case 'B': FileTimeBefore.SetIsoText(Switch+2); break; case 'A': FileTimeAfter.SetIsoText(Switch+2); break; case 'S': { EXTTIME_MODE Mode=EXTTIME_HIGH3; bool CommonMode=Switch[2]>='0' && Switch[2]<='4'; if (CommonMode) Mode=(EXTTIME_MODE)(Switch[2]-'0'); if (Switch[2]=='-') Mode=EXTTIME_NONE; if (CommonMode || Switch[2]=='-' || Switch[2]=='+' || Switch[2]==0) xmtime=xctime=xatime=Mode; else { if (Switch[3]>='0' && Switch[3]<='4') Mode=(EXTTIME_MODE)(Switch[3]-'0'); if (Switch[3]=='-') Mode=EXTTIME_NONE; switch(toupper(Switch[2])) { case 'M': xmtime=Mode; break; case 'C': xctime=Mode; break; case 'A': xatime=Mode; break; case 'R': xarctime=Mode; break; } } } break; case '-': Test=false; break; case 0: Test=true; break; default: BadSwitch(Switch); break; } break; case 'A': switch(toupper(Switch[1])) { case 'C': ClearArc=true; break; case 'D': AppendArcNameToPath=true; break; case 'G': if (Switch[2]=='-' && Switch[3]==0) GenerateArcName=0; else { GenerateArcName=true; strncpy(GenerateMask,Switch+2,sizeof(GenerateMask)); } break; case 'N': //reserved for archive name break; case 'O': AddArcOnly=true; break; case 'P': strcpy(ArcPath,Switch+2); break; case 'S': SyncFiles=true; break; } break; case 'D': if (Switch[2]==0) switch(toupper(Switch[1])) { case 'S': DisableSortSolid=true; break; case 'H': OpenShared=true; break; case 'F': DeleteFiles=true; break; } break; case 'O': switch(toupper(Switch[1])) { case '+': Overwrite=OVERWRITE_ALL; break; case '-': Overwrite=OVERWRITE_NONE; break; case 'W': ProcessOwners=true; break; #ifdef SAVE_LINKS case 'L': SaveLinks=true; break; #endif #ifdef _WIN_32 case 'S': SaveStreams=true; break; case 'C': SetCompressedAttr=true; break; #endif default : BadSwitch(Switch); break; } break; case 'R': switch(toupper(Switch[1])) { case 0: Recurse=RECURSE_ALWAYS; break; case '-': Recurse=0; break; case '0': Recurse=RECURSE_WILDCARDS; break; case 'I': { Priority=atoi(Switch+2); char *ChPtr=strchr(Switch+2,':'); if (ChPtr!=NULL) { SleepTime=atoi(ChPtr+1); InitSystemOptions(SleepTime); } SetPriority(Priority); } break; } break; case 'Y': AllYes=true; break; case 'N': case 'X': if (Switch[1]!=0) { StringList *Args=toupper(Switch[0])=='N' ? InclArgs:ExclArgs; if (Switch[1]=='@' && !IsWildcard(Switch)) ReadTextFile(Switch+2,Args,false,true,true,true,true); else Args->AddString(Switch+1); } break; case 'E': switch(toupper(Switch[1])) { case 'P': switch(Switch[2]) { case 0: ExclPath=EXCL_SKIPWHOLEPATH; break; case '1': ExclPath=EXCL_BASEPATH; break; case '2': ExclPath=EXCL_SAVEFULLPATH; break; case '3': ExclPath=EXCL_ABSPATH; break; } break; case 'D': ExclEmptyDir=true; break; case 'E': ProcessEA=false; break; case 'N': NoEndBlock=true; break; default: if (Switch[1]=='+') { InclFileAttr=GetExclAttr(&Switch[2]); InclAttrSet=true; } else ExclFileAttr=GetExclAttr(&Switch[1]); break; } break; case 'P': if (Switch[1]==0) { GetPassword(PASSWORD_GLOBAL,NULL,Password,sizeof(Password)); eprintf("\n"); } else strncpy(Password,Switch+1,sizeof(Password)); break; case 'H': if (toupper(Switch[1])=='P') { EncryptHeaders=true; if (Switch[2]!=0) strncpy(Password,Switch+2,sizeof(Password)); else if (*Password==0) { GetPassword(PASSWORD_GLOBAL,NULL,Password,sizeof(Password)); eprintf("\n"); } } break; case 'Z': strncpy(CommentFile,Switch[1]!=0 ? Switch+1:"stdin",sizeof(CommentFile)); break; case 'M': switch(toupper(Switch[1])) { case 'C': { char *Str=Switch+2; if (*Str=='-') for (int I=0;I<sizeof(FilterModes)/sizeof(FilterModes[0]);I++) FilterModes[I].State=FILTER_DISABLE; else while (*Str) { int Param1=0,Param2=0; FilterState State=FILTER_AUTO; FilterType Type=FILTER_NONE; if (isdigit(*Str)) { Param1=atoi(Str); while (isdigit(*Str)) Str++; } if (*Str==':' && isdigit(Str[1])) { Param2=atoi(++Str); while (isdigit(*Str)) Str++; } switch(toupper(*(Str++))) { case 'T': Type=FILTER_PPM; break; case 'E': Type=FILTER_E8; break; case 'D': Type=FILTER_DELTA; break; case 'A': Type=FILTER_AUDIO; break; case 'C': Type=FILTER_RGB; break; case 'I': Type=FILTER_ITANIUM; break; case 'L': Type=FILTER_UPCASETOLOW; break; } if (*Str=='+' || *Str=='-') State=*(Str++)=='+' ? FILTER_FORCE:FILTER_DISABLE; FilterModes[Type].State=State; FilterModes[Type].Param1=Param1; FilterModes[Type].Param2=Param2; } } break; case 'M': break; case 'D': { if ((WinSize=atoi(&Switch[2]))==0) WinSize=0x10000<<(toupper(Switch[2])-'A'); else WinSize*=1024; if (!CheckWinSize()) BadSwitch(Switch); } break; case 'S': { char *Names=Switch+2,DefNames[512]; if (*Names==0) { strcpy(DefNames,DefaultStoreList); Names=DefNames; } while (*Names!=0) { char *End=strchr(Names,';'); if (End!=NULL) *End=0; if (*Names=='.') Names++; char Mask[NM]; if (strpbrk(Names,"*?.")==NULL) sprintf(Mask,"*.%s",Names); else strcpy(Mask,Names); StoreArgs->AddString(Mask); if (End==NULL) break; Names=End+1; } } break; default: Method=Switch[1]-'0'; if (Method>5 || Method<0) BadSwitch(Switch); break; } break; case 'V': switch(toupper(Switch[1])) { #ifdef _WIN_32 case 'D': EraseDisk=true; break; #endif case 'N': OldNumbering=true; break; case 'P': VolumePause=true; break; case 'E': if (toupper(Switch[2])=='R') VersionControl=atoi(Switch+3)+1; break; case '-': VolSize=0; break; default: { Int64 NewVolSize=atoil(&Switch[1]); if (NewVolSize==0) NewVolSize=INT64ERR; else switch (Switch[strlen(Switch)-1]) { case 'f': case 'F': switch(int64to32(NewVolSize)) { case 360: NewVolSize=362496; break; case 720: NewVolSize=730112; break; case 1200: NewVolSize=1213952; break; case 1440: NewVolSize=1457664; break; case 2880: NewVolSize=2915328; break; } break; case 'k': NewVolSize*=1024; break; case 'm': NewVolSize*=1024*1024; break; case 'M': NewVolSize*=1000*1000; break; case 'g': NewVolSize*=1024*1024; NewVolSize*=1024; break; case 'G': NewVolSize*=1000*1000; NewVolSize*=1000; break; case 'b': case 'B': break; default: NewVolSize*=1000; break; } if (VolSize==0) VolSize=NewVolSize; else NextVolSizes.Push(NewVolSize); } break; } break; case 'F': if (Switch[1]==0) FreshFiles=true; break; case 'U': if (Switch[1]==0) UpdateFiles=true; break; case 'W': strncpy(TempPath,&Switch[1],sizeof(TempPath)-1); AddEndSlash(TempPath); break; case 'S': if (strnicomp(Switch,"SFX",3)==0) { const char *SFXName=Switch[3] ? Switch+3:DefSFXName; if (PointToName(SFXName)!=SFXName || FileExist(SFXName)) strcpy(SFXModule,SFXName); else GetConfigName(SFXName,SFXModule,true); } if (isdigit(Switch[1])) { Solid|=SOLID_COUNT; SolidCount=atoi(&Switch[1]); } else switch(toupper(Switch[1])) { case 0: Solid|=SOLID_NORMAL; break; case '-': Solid=SOLID_NONE; break; case 'E': Solid|=SOLID_FILEEXT; break; case 'V': Solid|=Switch[2]=='-' ? SOLID_VOLUME_DEPENDENT:SOLID_VOLUME_INDEPENDENT; break; case 'D': Solid|=SOLID_VOLUME_DEPENDENT; break; } break; case 'C': if (Switch[2]==0) switch(toupper(Switch[1])) { case '-': DisableComment=true; break; case 'U': ConvertNames=NAMES_UPPERCASE; break; case 'L': ConvertNames=NAMES_LOWERCASE; break; } break; case 'K': switch(toupper(Switch[1])) { case 'B': KeepBroken=true; break; case 0: Lock=true; break; } break; #ifndef GUI case '?' : OutHelp(); break; #endif default : BadSwitch(Switch); break; } }
void ClassLN::ReadText(const char* filename) { ClassLN res; res.num = ReadTextFile(filename); *this = res; }
bool CLngRc::LoadResouces(LPCWSTR asLanguage, LPCWSTR asFile) { bool bOk = false; CEStr lsJsonData; DWORD jsonDataSize = 0, nErrCode = 0; MJsonValue* jsonFile = NULL; MJsonValue jsonSection; DWORD nStartTick = 0, nLoadTick = 0, nFinTick = 0, nDelTick = 0; int iRc; wchar_t szLog[120]; struct { LPCWSTR pszSection; MArray<LngRcItem>* arr; int idDiff; } sections[] = { { L"cmnhints", &m_CmnHints, 0 }, { L"mnuhints", &m_MnuHints, IDM__MIN_MNU_ITEM_ID }, { L"controls", &m_Controls, 0 }, { L"strings", &m_Strings, 0 }, }; iRc = ReadTextFile(asFile, 1<<24 /*16Mb max*/, lsJsonData.ms_Val, jsonDataSize, nErrCode); if (iRc != 0) { // TODO: Log error goto wrap; } nStartTick = GetTickCount(); jsonFile = new MJsonValue(); if (!jsonFile->ParseJson(lsJsonData)) { // TODO: Log error CEStr lsErrMsg = lstrmerge( L"Language resources loading failed!\r\n" L"File: ", asFile, L"\r\n" L"Error: ", jsonFile->GetParseError()); gpConEmu->LogString(lsErrMsg.ms_Val); DisplayLastError(lsErrMsg.ms_Val, (DWORD)-1, MB_ICONSTOP); goto wrap; } nLoadTick = GetTickCount(); // Remember language parameters ms_Lng.Set(asLanguage); ms_l10n.Set(asFile); // Allocate intial array size m_CmnHints.alloc(4096); m_MnuHints.alloc(512); m_Controls.alloc(4096); m_Strings.alloc(lng_NextId); // Process sections for (size_t i = 0; i < countof(sections); i++) { if (jsonFile->getItem(sections[i].pszSection, jsonSection) && (jsonSection.getType() == MJsonValue::json_Object)) bOk |= LoadSection(&jsonSection, *(sections[i].arr), sections[i].idDiff); else Clean(*(sections[i].arr)); } nFinTick = GetTickCount(); wrap: SafeDelete(jsonFile); nDelTick = GetTickCount(); if (bOk) { _wsprintf(szLog, SKIPCOUNT(szLog) L"Language resources duration (ms): Parse: %u; Internal: %u; Delete: %u", (nLoadTick - nStartTick), (nFinTick - nLoadTick), (nDelTick - nFinTick)); gpConEmu->LogString(szLog); } return bOk; }
/* ==================== LoadAliasFile Tries to load script file from disk, and then from a pak file. ==================== */ qboolean LoadAliasFile (char *name) { char aliasfilename[MAX_QPATH] = ""; alias_from_pak = false; GameDirRelativePath (name, aliasfilename); alias_data = ReadTextFile(aliasfilename, &alias_data_size); // If file doesn't exist on hard disk, it must be in a pak file if (!alias_data) { cvar_t *basedir, *gamedir; char filename[256]; char pakfile[256]; char textname[128]; int i, k, num, numitems; qboolean in_pak = false; FILE *fpak; pak_header_t pakheader; pak_item_t pakitem; basedir = gi.cvar("basedir", "", 0); gamedir = gi.cvar("gamedir", "", 0); strcpy(filename,basedir->string); sprintf(textname, name); if(strlen(gamedir->string)) strcpy(filename,gamedir->string); // check all pakfiles in current gamedir for (i=0; i<10; i++) { sprintf(pakfile,"%s/pak%d.pak",filename,i); if (NULL != (fpak = fopen(pakfile, "rb"))) { num=fread(&pakheader,1,sizeof(pak_header_t),fpak); if(num >= sizeof(pak_header_t)) { if (pakheader.id[0] == 'P' && pakheader.id[1] == 'A' && pakheader.id[2] == 'C' && pakheader.id[3] == 'K' ) { numitems = pakheader.dsize/sizeof(pak_item_t); fseek(fpak,pakheader.dstart,SEEK_SET); for(k=0; k<numitems && !in_pak; k++) { fread(&pakitem,1,sizeof(pak_item_t),fpak); if (!stricmp(pakitem.name,textname)) { in_pak = true; fseek(fpak,pakitem.start,SEEK_SET); alias_data = gi.TagMalloc(pakitem.size + 1, TAG_LEVEL); if (!alias_data) { fclose(fpak); gi.dprintf("LoadAliasData: Memory allocation failure for entalias.dat\n"); return false; } alias_data_size = fread(alias_data,1,pakitem.size,fpak); alias_data[pakitem.size] = 0; // put end marker alias_from_pak = true; } } } } fclose(fpak); } } } if (!alias_data) return false; return true; }