Ejemplo n.º 1
0
void frmMain::OnSaveDefinition(wxCommandEvent &event)
{

	wxLogInfo(wxT("Saving object definition"));

	if (sqlPane->GetText().IsNull())
	{
		wxLogError(__("There is nothing in the SQL pane to save!"));
		return;
	}

	wxString file;
	settings->Read(wxT("frmMain/LastFile"), &file, wxEmptyString);

#ifdef __WXMSW__
	wxFileDialog filename(this, _("Select output file"), ::wxPathOnly(file), file, _("SQL Scripts (*.sql)|*.sql|All files (*.*)|*.*"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
#else
	wxFileDialog filename(this, _("Select output file"), ::wxPathOnly(file), file, _("SQL Scripts (*.sql)|*.sql|All files (*)|*"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
#endif

	// Show the dialogue
	if (filename.ShowModal() == wxID_OK)
	{
		// Write the file
		if (!FileWrite(filename.GetPath(), sqlPane->GetText()))
		{
			wxLogError(__("Could not write the file %s: Errcode=%d."), filename.GetPath().c_str(), wxSysErrorCode());
		}
	}
	else
	{
		wxLogInfo(wxT("User cancelled"));
	}

	settings->Write(wxT("frmMain/LastFile"), filename.GetPath());
}
Ejemplo n.º 2
0
// щелчок на кнопке "Добавить"
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    AnsiString st;

    /* файл можно открыть в режиме fmCreate, тогда, если
       файл существует, он будет открыт для записи,
       если файла нет, то он будет создан */

    st = MonthCalendar1->Date.DateString() + " " + Edit1->Text + "\r\n";

    /* открыть для записи или создать файл meteo.txt */


    if ( FileExists("meteo.txt") )
        f = FileOpen("meteo.txt",fmOpenWrite);
    else
       f = FileCreate("meteo.txt");


    if ( f != -1 )
    {
        // файл открыт для записи
        FileSeek(f,0,2); // установить указатель на конец файла
        FileWrite(f,st.c_str(),st.Length());
        FileClose(f);
        Button1->Enabled = false;
    }

    else
    {
        /* ошибка доступа к файлу: ни открыть,
           ни создать не получилось */
        ShowMessage("Oшибка доступа к файлу: ни открыть,"
                     "ни создать не получилось");
    }
}
Ejemplo n.º 3
0
//-----------------------------------------------------------------------------------------------
void calc_alpha_signal (double Input_Array[], int param_counted_bars)
{
   // Calculate alpha index of close[]
   // using least squares algorithm

   // Adapted by E Farrell 2013
   // source supplied by J Blackledge 2012


   // initialize R & T
   ArrayResize(T,Lookback);
   ArrayResize(R,Lookback);

   // set up the T array
   for(int t = 1; t <= Lookback; t++)
      T[t-1] = MathLog(t);


   for (int i = phase_lookback; i >= 0; i--)
   {
      // Create autocorrelation array for R,
      // based on "Input_Array"
      BuildRArray (Lookback, i, Input_Array);

      // Calculate alpha index
      // of closing price (signal)
      levy_signal[i] = -GetHurstExponent(Lookback, T, R);

      if (DEBUG == 1){
         // Output array values to Expert Log
         //Print("\t levy_signal[\t", DoubleToStr(i,0), "\t] \t", DoubleToStr(levy_signal[i],6));
         file_result = FileWrite (file_handle, "levy_signal", i, levy_signal[i]);
      }
   }

}
Ejemplo n.º 4
0
Int2  Main(void)

{
    
    Char *profilesFileName; /*file name for list of profile file names*/
    Char sequencesFileName[MAX_NAME_LENGTH]; /*file anme for list of sequence file names*/
    Char matrixFileName[MAX_NAME_LENGTH]; /*file name for list of matrix file names*/
    Char auxFileName[MAX_NAME_LENGTH]; /*file name for file containing auxiliary information*/
    Char bigFileName[MAX_NAME_LENGTH]; /*file name to store byte-encoded coalesced matrix*/
    Char lookupName[MAX_NAME_LENGTH]; /*file name to store precalculated lookup table */
    FILE *auxiliaryfp; /*file descriptor for matrix auxiliary file*/
    FILE *sequencesfp; /*files descriptor for file containing list of sequences*/
    FILE *matrixnamefp; /*file descriptor for file containing matrix names*/
    FILE *bigmatrixfile; /*file descriptor for file containing single big matrix*/
    Int4 numProfiles; /*number of profiles*/
    Int4 totalProfileLength; /*total length of all profiles*/
    ScoreRow *combinedMatrix; /*combined matrix for all profiles*/
    Char *directoryPrefix; /*directory where profile library is kept, used
                             to reach other directories indirectly*/

    Int4Ptr seqlens;
    Nlm_FloatHi scalingFactor; /*matrix scale to skip over in reading*/

    if (! GetArgs ("copymatrices", NUMARG, myargs)) {
        return (1);
    }
    
    if ((Boolean) myargs[1].intvalue) {
        IMPALAPrintHelp(FALSE, 80, "copymat", stdout);
        return(1);
    }
    profilesFileName = myargs[0].strvalue;
    directoryPrefix = (Char *) MemNew(MAX_NAME_LENGTH *sizeof(char));
    strcpy(directoryPrefix,profilesFileName);
    
    impalaMakeFileNames(profilesFileName, auxFileName, bigFileName,
                        sequencesFileName, matrixFileName, NULL, 
                        directoryPrefix);
    
    if ((matrixnamefp = FileOpen(matrixFileName, "r")) == NULL) {
        ErrPostEx(SEV_FATAL, 1, 0, "copymatrices: Unable to open file with matrix file names %s\n", matrixFileName);
        return (1);
    }
    
    if ((sequencesfp = FileOpen(sequencesFileName, "r")) == NULL) {
        ErrPostEx(SEV_FATAL, 1, 0, "copymatrices: Unable to open file with sequence file names %s\n", sequencesFileName);
        return (1);
    }
    
    if ((auxiliaryfp = FileOpen(auxFileName, "r")) == NULL) {
        ErrPostEx(SEV_FATAL, 1, 0, "profiles: Unable to open auxiliary file %s\n", auxFileName);
        return (1);
    }

    /* -- SSH -- Name of matrix file depends on program - RPS or Impala */
    
    if((Boolean) myargs[2].intvalue) {
        sprintf(bigFileName, "%s.rps", profilesFileName);
    }
    
    if ((bigmatrixfile = FileOpen(bigFileName, "wb")) == NULL) {
        ErrPostEx(SEV_FATAL, 1, 0, "rps-blast: Unable to open big matrix file %s\n", bigFileName);
        return (1);
    }
    
    numProfiles =  countProfiles(sequencesfp, matrixnamefp);
    totalProfileLength = findTotalLength(auxiliaryfp, numProfiles, 
                                         &scalingFactor);
    
    /* -- SSH -- Additional line in matrix with -INT2_MAX values */
    if((Boolean) myargs[2].intvalue) {
        totalProfileLength += numProfiles;
    }

    combinedMatrix = allocateMatrix(totalProfileLength);
    if (NULL == combinedMatrix) {
        ErrPostEx(SEV_FATAL, 1, 0, "copymatrices: Unable to allocate matrix with%d rows\n", totalProfileLength);
        return (1);
        
    }
    /* -- SSH -- RPS Blast data */
    if ((Boolean) myargs[2].intvalue) {
        seqlens = (Int4Ptr) MemNew((numProfiles +1) * sizeof(Int4));
    } else {
        seqlens = NULL;
    }
    
    readAllMatrices(matrixnamefp, combinedMatrix, numProfiles,
                    directoryPrefix, seqlens);
    
    /* -- SSH -- For RPS Blast additional info will be added to the file */
    if ((Boolean) myargs[2].intvalue) {
        Int4 magicNumber = RPS_MAGIC_NUMBER;
        FileWrite(&magicNumber, sizeof(Int4), 1, bigmatrixfile);
        FileWrite(&numProfiles, sizeof(Int4), 1, bigmatrixfile);
        FileWrite(seqlens, sizeof(Int4), numProfiles + 1, bigmatrixfile);
        
        sprintf(lookupName, "%s.loo", profilesFileName);
        RPSCreateLookupFile(combinedMatrix, numProfiles, seqlens, lookupName,
                            scalingFactor);

        if(!RPSConcatSequences(sequencesfp, profilesFileName)) {
            ErrPostEx(SEV_ERROR, 0,0, "Failure to concatenate sequences");
            return 1;
        }
        
    }
    
    FileWrite((void *) combinedMatrix[0], sizeof(ScoreRow), 
              (size_t) totalProfileLength, bigmatrixfile);
    freeMatrix(combinedMatrix); 
    FileClose(bigmatrixfile);
    FileClose(matrixnamefp);
    FileClose(sequencesfp);
    FileClose(auxiliaryfp);
    return 0;
}
Ejemplo n.º 5
0
/* -- SSH --
   Create lookup table for the large sequence, that represented
   by all collection of PSSM matrixes and dump this table to disk
   Used by RPS Blast.
*/
Boolean RPSCreateLookupFile(ScoreRow *combinedMatrix, Int4 numProfiles,
                            Int4Ptr seqlens, CharPtr filename, 
                            Nlm_FloatHi scalingFactor)
{
    BlastScoreBlk *sbp;
    FILE *fd;
    Int4  **posMatrix;
    Int4 start, i, header_size, all_length, magicNumber;
    Int4Ptr offsets;
    Int4 num_lookups;
    BlastSeqLoc *lookup_segment=NULL;
    BlastAaLookupTable *lookup;
    LookupTableWrap* lookup_wrap_ptr=NULL;
    LookupTableOptions* lookup_options;
   

    if((fd = FileOpen(filename, "wb")) == NULL)
        return FALSE;
    
    num_lookups = 1; /* Single lookup table for all set */

    all_length = seqlens[numProfiles] - seqlens[0];
    
    posMatrix = MemNew((all_length + 1) * sizeof(Int4 *));
    for (i = 0; i < all_length; i++) {
        posMatrix[i] = (Int4 *) &(combinedMatrix[i][0]);
    }
    
    /* Last row is necessary */
    posMatrix[all_length] = MemNew(sizeof(Int4) * PRO_ALPHABET_SIZE);

    for(i = 0; i < PRO_ALPHABET_SIZE; i++) {
        posMatrix[all_length][i] = -INT2_MAX;
    }

    sbp = BlastScoreBlkNew(BLASTAA_SEQ_CODE, 1);
    RPSPsiMatrixAttach(sbp, posMatrix);
    LookupTableOptionsNew(eBlastTypeBlastp, &lookup_options);
    BLAST_FillLookupTableOptions(lookup_options, eBlastTypePsiBlast, FALSE, 
	(Int4) (myargs[3].floatvalue*scalingFactor), myargs[4].intvalue);


    BlastSeqLocNew(&lookup_segment, 0, all_length);

    /* Need query for psi-blast??  where to put the PSSM? */
    LookupTableWrapInit(NULL, lookup_options, NULL, lookup_segment, sbp, &lookup_wrap_ptr, NULL, NULL);
   
    RPSPsiMatrixDetach(sbp);
    sbp = BlastScoreBlkFree(sbp);
    lookup_options = LookupTableOptionsFree(lookup_options);
    lookup_segment = BlastSeqLocFree(lookup_segment);

    lookup = (BlastAaLookupTable*) lookup_wrap_ptr->lut;

    /* Only Uint4 maximum length for lookup file allowed in current
       implementation */
    header_size = (numProfiles+1)*sizeof(Int4) + 8*sizeof(Int4);
    
    /* Beginning of file will be allocated for lookup offsets */
    fseek(fd, header_size, SEEK_SET);
    
    offsets = MemNew(sizeof(Int4) * (num_lookups + 1));
    

    offsets[0] = ftell(fd);
    
    start = seqlens[0]; /* 0 */
    
    RPSDumpLookupTable(lookup, fd);
    
    i = 1;
    
    offsets[i] = ftell(fd); /* Last offset also recorded */
    
    fseek(fd, 0, SEEK_SET);
    magicNumber = RPS_MAGIC_NUMBER;
    FileWrite(&magicNumber, sizeof(Int4), 1, fd); /* header[0] */
    FileWrite(&num_lookups, sizeof(Int4), 1, fd); /* header[1] */
    FileWrite(&lookup->neighbor_matches, sizeof(Int4), 1, fd); /* header[2] */
    FileWrite(&lookup->neighbor_matches, sizeof(Int4), 1, fd); /* header[3] */
    FileWrite(&lookup->overflow_size, sizeof(Int4), 1, fd); /* header[4] */
    
    /* Now writing recorded offsets in the beginning of the file */
    
    fseek(fd, 8*sizeof(Int4), SEEK_SET);
    FileWrite(offsets, sizeof(Int4), num_lookups + 1, fd);
    FileClose(fd);
    
    /* Final memory cleenup */
    
    MemFree(posMatrix[all_length]);
    MemFree(posMatrix);

    return TRUE;
}
Ejemplo n.º 6
0
int ProcessCTR(char* path){
	PartitionInfo myInfo;
	File myFile;
	char myString[256];  //In case it is needed...
	if(FileOpen(&myFile, path, 0)){
		ConsoleInit();
		ConsoleAddText(TITLE);
		unsigned int ncch_base = 0x100;
		unsigned char magic[] = { 0, 0, 0, 0, 0};
		FileRead(&myFile, magic, 4, ncch_base);
		if(magic[0] == 'N' && magic[1] == 'C' && magic[2] == 'S' && magic[3] == 'D'){
			ncch_base = 0x4000;
			FileRead(&myFile, magic, 4, ncch_base+0x100);
			if(!(magic[0] == 'N' && magic[1] == 'C' && magic[2] == 'C' && magic[3] == 'H')){
				FileClose(&myFile);
				return 2;
			}
		}else if(magic[0] == 'N' && magic[1] == 'C' && magic[2] == 'C' && magic[3] == 'H'){
			ncch_base = 0x0;
		}else{
			FileClose(&myFile);
			return 2;
		}
		ctr_ncchheader NCCH; unsigned int mediaunitsize = 0x200;
		FileRead(&myFile, &NCCH, 0x200, ncch_base);

		//ConsoleAddText(path);
		ConsoleAddText(NCCH.productcode);
		unsigned int NEWCRYPTO = 0, CRYPTO = 1;
		if(NCCH.flags[3] != 0) NEWCRYPTO = 1;
		if(NCCH.flags[7] & 4) CRYPTO = 0;
		if(NEWCRYPTO){
			ConsoleAddText("\nCryptoType : 7.X Key security");
		}else if(CRYPTO){
			ConsoleAddText("\nCryptoType : Secure");
		}else{
			ConsoleAddText("\nCryptoType : None");
			ConsoleAddText("Decryption completed!");
			FileClose(&myFile);
			ConsoleShow();
			return 3;
		}

		ConsoleShow();
		u8 CTR[16];
		if(getle32(NCCH.extendedheadersize) > 0){
			ConsoleAddText("Decrypting ExHeader..."); ConsoleShow();
			ncch_get_counter(NCCH, CTR, 1);
			FileRead(&myFile, BUFFER_ADDR, 0x800, ncch_base + 0x200);
			myInfo.buffer = BUFFER_ADDR;
			myInfo.size = 0x800;
			myInfo.keyslot = 0x2C;
			myInfo.ctr = CTR;
			myInfo.keyY = NCCH.signature;
			DecryptPartition(&myInfo);
			FileWrite(&myFile, BUFFER_ADDR, 0x800, ncch_base + 0x200);
		}
		if(getle32(NCCH.exefssize) > 0){
			ConsoleAddText("Decrypting ExeFS..."); ConsoleShow();
			ncch_get_counter(NCCH, CTR, 2);
			myInfo.buffer = BUFFER_ADDR;
			myInfo.keyslot = NEWCRYPTO ? 0x25 : 0x2C;
			myInfo.ctr = CTR;
			myInfo.keyY = NCCH.signature;

			size_t bytesRead = FileRead(&myFile, BUFFER_ADDR, getle32(NCCH.exefssize) * mediaunitsize, ncch_base + getle32(NCCH.exefsoffset) * mediaunitsize);
			myInfo.size = bytesRead;
			ProcessExeFS(&myInfo); //Explanation at function definition
			FileWrite(&myFile, BUFFER_ADDR, getle32(NCCH.exefssize) * mediaunitsize, ncch_base + getle32(NCCH.exefsoffset) * mediaunitsize);
		}
		if(getle32(NCCH.romfssize) > 0){
			ConsoleAddText("Decrypting RomFS..."); ConsoleShow();
			ncch_get_counter(NCCH, CTR, 3);
			myInfo.buffer = BUFFER_ADDR;
			myInfo.keyslot = NEWCRYPTO ? 0x25 : 0x2C;
			myInfo.ctr = CTR;
			myInfo.keyY = NCCH.signature;
			for(int i = 0; i < getle32(NCCH.romfssize) * mediaunitsize / BLOCK_SIZE; i++){
				sprintf(myString, "%i%%", (int)((i*BLOCK_SIZE)/(getle32(NCCH.romfssize) * mediaunitsize/ 100)));
				int x, y; ConsoleGetXY(&x, &y); y += CHAR_WIDTH * 4; x += CHAR_WIDTH*22;
				DrawString(TOP_SCREEN, myString, x, y, ConsoleGetTextColor(),  ConsoleGetBackgroundColor());
				size_t bytesRead = FileRead(&myFile, BUFFER_ADDR, BLOCK_SIZE, ncch_base + getle32(NCCH.romfsoffset) * mediaunitsize + i*BLOCK_SIZE);
				myInfo.size = bytesRead;
				DecryptPartition(&myInfo);
				add_ctr(myInfo.ctr, bytesRead/16);
				FileWrite(&myFile, BUFFER_ADDR, BLOCK_SIZE, ncch_base + getle32(NCCH.romfsoffset) * mediaunitsize + i*BLOCK_SIZE);
			}
		}
		NCCH.flags[7] |= 4; //Disable encryption
		NCCH.flags[3] = 0;  //Disable 7.XKey usage
		FileWrite(&myFile, &NCCH, 0x200, ncch_base);
		if(ncch_base == 0x4000) FileWrite(&myFile, ((u8*)&NCCH) + 0x100, 0x100, 0x1100);   //Only for NCSD
		FileClose(&myFile);
		ConsoleAddText("Decryption completed!"); ConsoleShow();
		return 0;
	}else return 1;
}
Ejemplo n.º 7
0
BOOLEAN SaveMapScreenMessagesToSaveGameFile( HWFILE hFile )
{
	UINT32	uiNumBytesWritten;
	UINT32	uiCount;
	UINT32	uiSizeOfString;
	StringSaveStruct StringSave;


	//	write to the begining of the message list
	FileWrite( hFile, &gubEndOfMapScreenMessageList, sizeof( UINT8 ), &uiNumBytesWritten );
	if( uiNumBytesWritten != sizeof( UINT8 ) )
	{
		return(FALSE);
	}

	FileWrite( hFile, &gubStartOfMapScreenMessageList, sizeof( UINT8 ), &uiNumBytesWritten );
	if( uiNumBytesWritten != sizeof( UINT8 ) )
	{
		return(FALSE);
	}

	//	write the current message string
	FileWrite( hFile, &gubCurrentMapMessageString, sizeof( UINT8 ), &uiNumBytesWritten );
	if( uiNumBytesWritten != sizeof( UINT8 ) )
	{
		return(FALSE);
	}


	//Loopthrough all the messages
	for( uiCount=0; uiCount<256; uiCount++)
	{
		if( gMapScreenMessageList[ uiCount ] )
		{
			uiSizeOfString = ( wcslen( gMapScreenMessageList[ uiCount ]->pString16 ) + 1 ) * 2;
		}
		else
			uiSizeOfString = 0;

		//	write to the file the size of the message
		FileWrite( hFile, &uiSizeOfString, sizeof( UINT32 ), &uiNumBytesWritten );
		if( uiNumBytesWritten != sizeof( UINT32 ) )
		{
			return(FALSE);
		}

		//if there is a message
		if( uiSizeOfString )
		{
			//	write the message to the file
			FileWrite( hFile, gMapScreenMessageList[ uiCount ]->pString16, uiSizeOfString, &uiNumBytesWritten );
			if( uiNumBytesWritten != uiSizeOfString )
			{
				return(FALSE);
			}

			// Create  the saved string struct
			StringSave.uiFont = gMapScreenMessageList[ uiCount ]->uiFont;
			StringSave.usColor = gMapScreenMessageList[ uiCount ]->usColor;
			StringSave.fBeginningOfNewString = gMapScreenMessageList[ uiCount ]->fBeginningOfNewString;
			StringSave.uiTimeOfLastUpdate = gMapScreenMessageList[ uiCount ]->uiTimeOfLastUpdate;
			StringSave.uiFlags= gMapScreenMessageList[ uiCount ]->uiFlags;


			//Write the rest of the message information to the saved game file
			FileWrite( hFile, &StringSave, sizeof( StringSaveStruct ), &uiNumBytesWritten );
			if( uiNumBytesWritten != sizeof( StringSaveStruct ) )
			{
				return(FALSE);
			}
		}

	}

	return( TRUE );
}
Ejemplo n.º 8
0
/*
 * BufFileDumpBuffer
 *
 * Dump buffer contents starting at curOffset.
 * At call, should have dirty = true, nbytes > 0.
 * On exit, dirty is cleared if successful write, and curOffset is advanced.
 */
static void
BufFileDumpBuffer(BufFile *file)
{
	int			wpos = 0;
	int			bytestowrite;
	File		thisfile;

	/*
	 * Unlike BufFileLoadBuffer, we must dump the whole buffer even if it
	 * crosses a component-file boundary; so we need a loop.
	 */
	while (wpos < file->nbytes)
	{
		/*
		 * Advance to next component file if necessary and possible.
		 */
		if (file->curOffset >= MAX_PHYSICAL_FILESIZE && file->isTemp)
		{
			while (file->curFile + 1 >= file->numFiles)
				extendBufFile(file);
			file->curFile++;
			file->curOffset = 0L;
		}

		/*
		 * Enforce per-file size limit only for temp files, else just try to
		 * write as much as asked...
		 */
		bytestowrite = file->nbytes - wpos;
		if (file->isTemp)
		{
			off_t		availbytes = MAX_PHYSICAL_FILESIZE - file->curOffset;

			if ((off_t) bytestowrite > availbytes)
				bytestowrite = (int) availbytes;
		}

		/*
		 * May need to reposition physical file.
		 */
		thisfile = file->files[file->curFile];
		if (file->curOffset != file->offsets[file->curFile])
		{
			if (FileSeek(thisfile, file->curOffset, SEEK_SET) != file->curOffset)
				return;			/* seek failed, give up */
			file->offsets[file->curFile] = file->curOffset;
		}
		bytestowrite = FileWrite(thisfile, file->buffer + wpos, bytestowrite);
		if (bytestowrite <= 0)
			return;				/* failed to write */
		file->offsets[file->curFile] += bytestowrite;
		file->curOffset += bytestowrite;
		wpos += bytestowrite;

		pgBufferUsage.temp_blks_written++;
	}
	file->dirty = false;

	/*
	 * At this point, curOffset has been advanced to the end of the buffer,
	 * ie, its original value + nbytes.  We need to make it point to the
	 * logical file position, ie, original value + pos, in case that is less
	 * (as could happen due to a small backwards seek in a dirty buffer!)
	 */
	file->curOffset -= (file->nbytes - file->pos);
	if (file->curOffset < 0)	/* handle possible segment crossing */
	{
		file->curFile--;
		Assert(file->curFile >= 0);
		file->curOffset += MAX_PHYSICAL_FILESIZE;
	}

	/*
	 * Now we can set the buffer empty without changing the logical position
	 */
	file->pos = 0;
	file->nbytes = 0;
}
Ejemplo n.º 9
0
void __fastcall TFormSim::Button6Click(TObject *Sender)
{
int file;
file = FileOpen("D:\\smart-environment-simulator20140308\\Bin\\new.txt", fmOpenWrite);
if(frmMainFrame->num>0){
    for(int i=0;i<frmMainFrame->route1->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route1->Items[i];
        if(i==frmMainFrame->route1->Count-1)
        {
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else
        {
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>1){
    for(int i=0;i<frmMainFrame->route2->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route2->Items[i];
        if(i==frmMainFrame->route2->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>2){
    for(int i=0;i<frmMainFrame->route3->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route3->Items[i];
        if(i==frmMainFrame->route3->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>3){
    for(int i=0;i<frmMainFrame->route4->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route4->Items[i];
        if(i==frmMainFrame->route4->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
//**************By WYP at 20150426**********************************
if(frmMainFrame->num>4){
    for(int i=0;i<frmMainFrame->route5->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route5->Items[i];
        if(i==frmMainFrame->route5->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>5){
    for(int i=0;i<frmMainFrame->route6->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route6->Items[i];
        if(i==frmMainFrame->route6->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>6){
    for(int i=0;i<frmMainFrame->route7->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route7->Items[i];
        if(i==frmMainFrame->route7->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>7){
    for(int i=0;i<frmMainFrame->route8->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route8->Items[i];
        if(i==frmMainFrame->route8->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
if(frmMainFrame->num>8){
    for(int i=0;i<frmMainFrame->route9->Count;i++){
        FCMsNode*my = (FCMsNode*)frmMainFrame->route9->Items[i];
        if(i==frmMainFrame->route9->Count-1){
            FileSeek(file,0,2);
            String s = my->m_strName;
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
            FileWrite(file, "\r\n",sizeof("\r\n"));
        }
        else{
            FileSeek(file,0,2);
            String s = my->m_strName;
            s = s+"->";
            FileWrite(file, s.c_str(), sizeof(s.c_str()));
        }
}
}
//******************************************************************
FileClose(file);
}
Ejemplo n.º 10
0
int InstallData(char* drive){
	FIL firmfile;
	char* progressbar = "[       ]";
	char* progress = progressbar+1;
	print("%s", progressbar);  ConsolePrevLine();
	
	//Create the workdir
	sprintf(tmpstr, "%s:%s", drive, DATAFOLDER);
	f_mkdir(tmpstr);
	f_chmod(tmpstr, AM_HID, AM_HID);
	
	//Read firmware data
	if(f_open(&firmfile, "firmware.bin", FA_READ | FA_OPEN_EXISTING) == FR_OK){
		//... We'll see
	}else return CONF_NOFIRMBIN;
	*progress++ = '.'; DrawString(BOT_SCREEN, progressbar, 130, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());
	
	//Create patched native_firm
	f_read(&firmfile, WORKBUF, NAT_SIZE, &tmpu32);
	u8* n_firm = decryptFirmTitle(WORKBUF, NAT_SIZE, 0x00000002);
	u8* n_firm_patch = GetFilePack("nat_patch.bin");
	applyPatch(n_firm, n_firm_patch);
	u8 keyx[16] = {0};
	if(GetSystemVersion() < 3){
		FileOpen(&tempfile, KEYFILENAME, 0);
		FileRead(&tempfile, &keyx[0], 16, 0);
		FileClose(&tempfile);
	}
	*progress++ = '.'; DrawString(BOT_SCREEN, progressbar, 130, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());
	for(int i = 0; i < NAT_SIZE; i+=0x4){
		if(!strcmp((char*)n_firm + i, "Shit")){
			if(1){
				memcpy((char*)n_firm + i, rxmode_emu_label, 4);
			}else{
				memcpy((char*)n_firm + i, rxmode_sys_label , 4);
			}
		}
		if(!strcmp((char*)n_firm + i, "InsertKeyXHere!") && keyx[0] != 0){
			memcpy(n_firm + i, keyx, 16);
		}
		if(*((unsigned int*)(n_firm + i)) == 0xAAAABBBB){
			*((unsigned int*)(n_firm + i)) = (checkEmuNAND() / 0x200) - 1;
		}
	}
	*progress++ = '.'; DrawString(BOT_SCREEN, progressbar, 130, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());
	sprintf(tmpstr, "%s:%s/0004013800000002.bin", drive, DATAFOLDER);
	if(FileOpen(&tempfile, tmpstr, 1)){
		FileWrite(&tempfile, n_firm, NAT_SIZE, 0);
		FileClose(&tempfile);
		//FileCopy("0004013800000002.bin", tmpstr);
	}else return CONF_ERRNFIRM;
	*progress++ = '.'; DrawString(BOT_SCREEN, progressbar, 130, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());
	
	//Create AGB patched firmware
	f_read(&firmfile, WORKBUF, AGB_SIZE, &tmpu32);
	u8* a_firm = decryptFirmTitle(WORKBUF, AGB_SIZE, 0x00000202);
	u8* a_firm_patch = GetFilePack("agb_patch.bin");
	if(a_firm){
		applyPatch(a_firm, a_firm_patch);
		sprintf(tmpstr, "%s:%s/0004013800000202.bin", drive, DATAFOLDER);
		if(FileOpen(&tempfile, tmpstr, 1)){
			FileWrite(&tempfile, a_firm, AGB_SIZE, 0);
			FileClose(&tempfile);
		}else return CONF_ERRNFIRM;
		*progress++ = '.';
	}else{	
		//If we cannot decrypt it from firmware.bin becouse of titlekey messed up, it probably means that AGB has been modified in some way.
		//So we read it from his installed ncch...
		FindApp(0x00040138, 0x00000202, 1);
		char* path = getContentAppPath();
		FileOpen(&tempfile, path, 0);
		FileRead(&tempfile, WORKBUF, AGB_SIZE, 0);
		FileClose(&tempfile);
		a_firm = decryptFirmTitleNcch(WORKBUF, AGB_SIZE);
		if(a_firm){
			applyPatch(a_firm, a_firm_patch);
			sprintf(tmpstr, "%s:%s/0004013800000202.bin", drive, DATAFOLDER);
			if(FileOpen(&tempfile, tmpstr, 1)){
				FileWrite(&tempfile, a_firm, AGB_SIZE, 0);
				FileClose(&tempfile);
			}else return CONF_ERRNFIRM;
			*progress++ = '.';
		}else{
			*progress++ = 'x'; //If we get here, then we'll play without AGB, lol
		}
	}
	DrawString(BOT_SCREEN, progressbar, 130, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());
	
	//Create TWL patched firmware
	f_read(&firmfile, WORKBUF, TWL_SIZE, &tmpu32);
	u8* t_firm = decryptFirmTitle(WORKBUF, TWL_SIZE, 0x00000102);
	u8* t_firm_patch = GetFilePack("twl_patch.bin");
	if(t_firm){
		applyPatch(t_firm, t_firm_patch);
		sprintf(tmpstr, "%s:%s/0004013800000102.bin", drive, DATAFOLDER);
		if(FileOpen(&tempfile, tmpstr, 1)){
			FileWrite(&tempfile, t_firm, TWL_SIZE, 0);
			FileClose(&tempfile);
			//FileCopy("0004013800000102.bin", tmpstr);
		}else return CONF_ERRNFIRM;
		*progress++ = '.'; 
	}else{
		*progress++ = 'x'; 
	}
	DrawString(BOT_SCREEN, progressbar, 130, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());
	
	sprintf(tmpstr, "%s:%s/data.bin", drive, DATAFOLDER);
	if(FileOpen(&tempfile, tmpstr, 1)){
		FileWrite(&tempfile, __DATE__, 12, 0);
		FileWrite(&tempfile, __TIME__, 9, 12);
		FileClose(&tempfile);
	}else return CONF_CANTOPENFILE;
	*progress++ = '.'; DrawString(BOT_SCREEN, progressbar, 130, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());
	
	f_close(&firmfile);
	return 0;
}
Ejemplo n.º 11
0
//Write the file back out, with the changes
bool BlueZip::Write(bool Store)
{
	//TODO: Do not use a TempFile, send straight to the output

	char TempFileName[MAX_PATH];
	File f;

	zList* z;
	zList** next = &Files; //where to insert the next zList

	int i, j; //global enumeration variables

	if ((Files == NULL) && (Pending == NULL))
	{
		ErrMsg("Blank ZIP files not allowed");
		return false;
	}

	//Always use a temporary file name (they may have the ZIP file on a floppy)
	f = FileOpenTemp(TempFileName);
	if (!FileValid(f))
	{
		ErrMsg(Failed to open the temporary file);
		return false;
	}

	if (Files != NULL)
	{
		File Orig = FileOpenRead(FileName);
		if (!FileValid(Orig))
		{
			ErrMsg("Failed to open the reading file");
			return false;
		}

		const int BlockSize = 4096;
		char* Buffer = new char[BlockSize];
		datCentral hLocal;
		for (z = Files; z != NULL; z = z->next)
		{
			if (!z->Delete)
			{
				//Remove any that have dropped out of the list
				*next = z;
				next = &z->next;

				//Perform a ZIP copy
				SeekBeg(Orig, z->data.Offset + z->FileDeltaPos);
				z->data.Offset = FilePos(f);

				u32 sig;
				FileRead(Orig, &sig, 4);
				Assert(sig == sigLocal);
				FileWrite(f, &sig, 4);

				hLocal.ReadLocal(Orig);
				hLocal.WriteLocal(f);

				i = hLocal.CompSize + hLocal.lFileName + hLocal.lExtra;
				while(i != 0)
				{
					j = min(i, BlockSize);
					FileRead(Orig, Buffer, j);
					FileWrite(f, Buffer, j);
					i -= j;
				}
			}
		}
		FileClose(Orig);
		delete[] Buffer;
	}


	while (Pending != NULL)
	{
		fList* fAdd = Pending;
		Pending = Pending->next;

		z = fAdd->ZipUp(f, Store);
		if (z == NULL)
		{
			ErrMsg("Failed to add the file");
		}
		else
		{
			*next = z;
			next = &z->next;
		}

		delete fAdd;

	}

	//Write out the central header
	data.Count = 0;
	data.Offset = FilePos(f);
	for (z = Files; z != NULL; z = z->next, data.Count++)
		z->WriteCentral(f);

	data.Size = FilePos(f) - data.Offset;
	WriteEnd(f);

	FileClose(f);

	//Using a temp file
	if (!FileReplace(FileName, TempFileName))
	{
		ErrMsg("Failed to copy the temporary file");
		return false;
	}

	return true;
}
Ejemplo n.º 12
0
int UpdateValues(WPARAM hContact, LPARAM lparam)
{
	// to make this code faster
	if (!hContact)
		return 0;

	DBCONTACTWRITESETTING *cws = (DBCONTACTWRITESETTING *)lparam;
	char *szProto = GetContactProto(hContact);

	if (cws->value.type == DBVT_DWORD && !strcmp(cws->szSetting, "LastSeen") && !mir_strcmp(cws->szModule, szProto)) {
		DBWriteTimeTS(cws->value.dVal, hContact);
		
		HWND hwnd = WindowList_Find(g_pUserInfo, hContact);
		if (hwnd != NULL)
			SendMessage(hwnd, WM_REFRESH_UI, hContact, 0);
		return 0;
	}

	BOOL isIdleEvent = includeIdle ? (strcmp(cws->szSetting, "IdleTS") == 0) : 0;
	if (strcmp(cws->szSetting, "Status") && strcmp(cws->szSetting, "StatusTriger") && (isIdleEvent == 0))
		return 0;
	
	if (!strcmp(cws->szModule, S_MOD)) {
		// here we will come when Settings/SeenModule/StatusTriger is changed
		WORD prevStatus = db_get_w(hContact, S_MOD, "OldStatus", ID_STATUS_OFFLINE);
		if (includeIdle) {
			if (db_get_b(hContact, S_MOD, "OldIdle", 0))
				prevStatus &= 0x7FFF;
			else
				prevStatus |= 0x8000;
		}
		if ((cws->value.wVal | 0x8000) <= ID_STATUS_OFFLINE) {
			// avoid repeating the offline status
			if ((prevStatus | 0x8000) <= ID_STATUS_OFFLINE)
				return 0;

			db_set_b(hContact, S_MOD, "Offline", 1);
			{
				char str[MAXMODULELABELLENGTH + 9];

				mir_snprintf(str, "OffTime-%s", szProto);
				DWORD t = db_get_dw(NULL, S_MOD, str, 0);
				if (!t)
					t = time(NULL);
				DBWriteTimeTS(t, hContact);
			}

			if (!db_get_b(NULL, S_MOD, "IgnoreOffline", 1)) {
				if (g_bFileActive)
					FileWrite(hContact);

				char *sProto = GetContactProto(hContact);
				if (CallProtoService(sProto, PS_GETSTATUS, 0, 0) > ID_STATUS_OFFLINE) {
					myPlaySound(hContact, ID_STATUS_OFFLINE, prevStatus);
					if (db_get_b(NULL, S_MOD, "UsePopups", 0))
						ShowPopup(hContact, sProto, ID_STATUS_OFFLINE);
				}

				if (db_get_b(NULL, S_MOD, "KeepHistory", 0))
					HistoryWrite(hContact);

				if (db_get_b(hContact, S_MOD, "OnlineAlert", 0))
					ShowHistory(hContact, 1);
			}

		}
		else {
			if (cws->value.wVal == prevStatus && !db_get_b(hContact, S_MOD, "Offline", 0))
				return 0;

			DBWriteTimeTS(time(NULL), hContact);

			if (g_bFileActive) FileWrite(hContact);
			if (prevStatus != cws->value.wVal) myPlaySound(hContact, cws->value.wVal, prevStatus);
			if (db_get_b(NULL, S_MOD, "UsePopups", 0))
				if (prevStatus != cws->value.wVal)
					ShowPopup(hContact, GetContactProto(hContact), cws->value.wVal | 0x8000);

			if (db_get_b(NULL, S_MOD, "KeepHistory", 0)) HistoryWrite(hContact);
			if (db_get_b(hContact, S_MOD, "OnlineAlert", 0)) ShowHistory(hContact, 1);
			db_set_b(hContact, S_MOD, "Offline", 0);
		}
	}
	else if (hContact && IsWatchedProtocol(cws->szModule) && !db_get_b(hContact, cws->szModule, "ChatRoom", false)) {
		// here we will come when <User>/<module>/Status is changed or it is idle event and if <module> is watched
		if (CallProtoService(cws->szModule, PS_GETSTATUS, 0, 0) > ID_STATUS_OFFLINE) {
			mir_cslock lck(csContacts);
			logthread_info *p = arContacts.find((logthread_info*)&hContact);
			if (p == NULL) {
				p = (logthread_info*)mir_calloc(sizeof(logthread_info));
				p->hContact = hContact;
				mir_strncpy(p->sProtoName, cws->szModule, _countof(p->sProtoName));
				arContacts.insert(p);
				mir_forkthread(waitThread, p);
			}
			p->currStatus = isIdleEvent ? db_get_w(hContact, cws->szModule, "Status", ID_STATUS_OFFLINE) : cws->value.wVal;
		}
	}

	return 0;
}
Ejemplo n.º 13
0
BOOL SaveChart (HWND hWndGraph, HANDLE hInputFile, BOOL bGetFileName)
   {
   PGRAPHSTRUCT   pGraph ;
   PLINE          pLine ;
   HANDLE         hFile ;
   DISKCHART      DiskChart ;
   PERFFILEHEADER FileHeader ;
   TCHAR          szFileName [256] ;
   BOOL           newFileName = FALSE ;

   if (hInputFile)
      {
      // use the input file handle if it is available
      // this is the case for saving workspace data
      hFile = hInputFile ;
      }
   else
      {
      if (pChartFullFileName)
         {
         lstrcpy (szFileName, pChartFullFileName) ;
         }
      if (bGetFileName || pChartFullFileName == NULL)
         {
//         if (!pChartFullFileName)
//            {
//            StringLoad (IDS_GRAPH_FNAME, szFileName) ;
//            }

         if (!FileGetName (hWndGraph, IDS_CHARTFILE, szFileName))
            {
            return (FALSE) ;
            }
         newFileName = TRUE ;
         }

      hFile = FileHandleCreate (szFileName) ;

      if (hFile && newFileName)
         {
         ChangeSaveFileName (szFileName, IDM_VIEWCHART) ;
         }
      else if (!hFile)
         {
         DlgErrorBox (hWndGraph, ERR_CANT_OPEN, szFileName) ;
         }
      }

   if (!hFile)
      return (FALSE) ;

   pGraph = pGraphs ;
   if (!pGraph)
      {
      if (!hInputFile)
         {
         CloseHandle (hFile) ;
         }
      return (FALSE) ;
      }

   if (!hInputFile)
      {
      // only need to write file header if not workspace 
      memset (&FileHeader, 0, sizeof (FileHeader)) ;
      lstrcpy (FileHeader.szSignature, szPerfChartSignature) ;
      FileHeader.dwMajorVersion = ChartMajorVersion ;
      FileHeader.dwMinorVersion = ChartMinorVersion ;
   
      if (!FileWrite (hFile, &FileHeader, sizeof (PERFFILEHEADER)))
         {
         goto Exit0 ;
         }
      }

   DiskChart.Visual = pGraph->Visual ;
   DiskChart.gOptions = pGraph->gOptions ;
   DiskChart.gMaxValues = pGraph->gMaxValues ;
   DiskChart.dwNumLines = NumLines (pGraph->pLineFirst) ;
   DiskChart.bManualRefresh = pGraph->bManualRefresh ;
   DiskChart.perfmonOptions = Options ;

   if (!FileWrite (hFile, &DiskChart, sizeof (DISKCHART)))
      {
      goto Exit0 ;
      }

   for (pLine = pGraph->pLineFirst ;
        pLine ;
        pLine = pLine->pLineNext)
      {  // for
      if (!WriteLine (pLine, hFile))
         {
         goto Exit0 ;
         }
      }  // for

   if (!hInputFile)
      {
      CloseHandle (hFile) ;
      }

   return (TRUE) ;

Exit0:
   if (!hInputFile)
      {
      CloseHandle (hFile) ;

      // only need to report error if not workspace 
      DlgErrorBox (hWndGraph, ERR_SETTING_FILE, szFileName) ;
      }
   return (FALSE) ;

   }  // SaveChart
Ejemplo n.º 14
0
//***********************************************************************************************
// Saves an FTL File
// Must pass the original name of the theo file
//-----------------------------------------------------------------------------------------------
// VERIFIED (Cyril 2001/10/15)
//***********************************************************************************************
bool ARX_FTL_Save(const char * file, EERIE_3DOBJ * obj)
{
	// Need an object to be saved !
	if (obj == NULL) return false;

	// Generate File name/path and create it
	char path[256];
	char gamefic[256];
	sprintf(gamefic, "Game\\%s", file);
	SetExt(gamefic, ".FTL");
	strcpy(path, gamefic);
	RemoveName(path);

	if (!CreateFullPath(path)) return NULL;

	// create some usefull vars
	ARX_FTL_PRIMARY_HEADER 	*		afph;
	ARX_FTL_SECONDARY_HEADER 	*		afsh;
	ARX_FTL_CLOTHES_DATA_HEADER 	*	afcdh;
	ARX_FTL_3D_DATA_HEADER 	*		af3Ddh;
	ARX_FTL_COLLISION_SPHERES_DATA_HEADER 	*		afcsdh;
	unsigned char * dat = NULL;
	long pos = 0;
	long allocsize = 8000000; // need to compute it more precisely

	// Compute allocsize...
	allocsize =	sizeof(ARX_FTL_PRIMARY_HEADER)
	            +	512 //checksum
	            +	sizeof(ARX_FTL_SECONDARY_HEADER)
	            +	sizeof(ARX_FTL_3D_DATA_HEADER)
	            +	sizeof(EERIE_OLD_VERTEX) * obj->nbvertex

	            +	sizeof(EERIE_FACE_FTL) * obj->nbfaces
	            +	obj->nbmaps * 256	// texturecontainernames
	            +	sizeof(EERIE_ACTIONLIST) * obj->nbaction
	            +	128000; // just in case...

	if (obj->nbgroups > 0)
	{
		allocsize += sizeof(EERIE_GROUPLIST) * obj->nbgroups;

		for (long i = 0; i < obj->nbgroups; i++)
		{
			if (obj->grouplist[i].nb_index > 0)
			{
				allocsize += sizeof(long) * obj->grouplist[i].nb_index;
			}
		}
	}

	if (obj->nbselections > 0)
	{
		allocsize += sizeof(EERIE_SELECTIONS) * obj->nbselections;

		for (long i = 0; i < obj->nbselections; i++)
		{
			allocsize += sizeof(long) * obj->selections[i].nb_selected;
		}
	}

	if (obj->sdata && obj->sdata->nb_spheres) // Collision Spheres Data
	{
		allocsize += sizeof(ARX_FTL_COLLISION_SPHERES_DATA_HEADER);
		allocsize += sizeof(COLLISION_SPHERE) * obj->sdata->nb_spheres;
	}

	if (obj->cdata) // Clothes DATA
	{
		allocsize += sizeof(ARX_FTL_CLOTHES_DATA_HEADER);
		allocsize += sizeof(CLOTHESVERTEX) * obj->cdata->nb_cvert;
		allocsize += sizeof(EERIE_SPRINGS) * obj->cdata->nb_springs;
	}

	// Finished computing allocsize Now allocate it...
	dat = (unsigned char *)malloc(allocsize);

	if (!dat)
		HERMES_Memory_Emergency_Out();

	memset(dat, 0, allocsize);

	// Primary Header
	afph = (ARX_FTL_PRIMARY_HEADER *)dat;
	pos += sizeof(ARX_FTL_PRIMARY_HEADER);

	if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");

	afph->ident[0] = 'F';
	afph->ident[1] = 'T';
	afph->ident[2] = 'L';
	afph->version = CURRENT_FTL_VERSION;

	// Identification
	char check[512];
	
	HERMES_CreateFileCheck(file, check, 512, CURRENT_FTL_VERSION);
	memcpy(dat + pos, check, 512);
	pos += 512;

	if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");

	// Secondary Header
	afsh = (ARX_FTL_SECONDARY_HEADER *)(dat + pos);
	pos += sizeof(ARX_FTL_SECONDARY_HEADER);

	if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");

	// 3D Data
	afsh->offset_3Ddata = pos; //-1;
	af3Ddh = (ARX_FTL_3D_DATA_HEADER *)(dat + afsh->offset_3Ddata);
	pos += sizeof(ARX_FTL_3D_DATA_HEADER);

	if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");

	af3Ddh->nb_vertex = obj->nbvertex;
	af3Ddh->nb_faces = obj->nbfaces;
	af3Ddh->nb_maps = obj->nbmaps;
	af3Ddh->nb_groups = obj->nbgroups;
	af3Ddh->nb_action = obj->nbaction;
	af3Ddh->nb_selections = obj->nbselections;
	af3Ddh->origin = obj->origin;

	// vertexes
	if (af3Ddh->nb_vertex > 0)
	{
		for (long ii = 0; ii < af3Ddh->nb_vertex; ii++)
		{
			memcpy(dat + pos, &obj->vertexlist[ii], sizeof(EERIE_OLD_VERTEX));
			pos += sizeof(EERIE_OLD_VERTEX);
		}

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");
	}

	// faces
	if (af3Ddh->nb_faces > 0)
	{
		for (long ii = 0; ii < af3Ddh->nb_faces; ii++)
		{
			EERIE_FACE_FTL * eff = (EERIE_FACE_FTL *)(dat + pos);
			eff->facetype = obj->facelist[ii].facetype;
			eff->texid = obj->facelist[ii].texid;
			eff->transval = obj->facelist[ii].transval;
			eff->temp = obj->facelist[ii].temp;
			memcpy(&eff->norm, &obj->facelist[ii].norm, sizeof(EERIE_3D));

			for (long kk = 0; kk < IOPOLYVERT; kk++)
			{
				memcpy(&eff->nrmls[kk], &obj->facelist[ii].nrmls[kk], sizeof(EERIE_3D));
				eff->vid[kk] = obj->facelist[ii].vid[kk];
				eff->u[kk] = obj->facelist[ii].u[kk];
				eff->v[kk] = obj->facelist[ii].v[kk];
				eff->ou[kk] = obj->facelist[ii].ou[kk];
				eff->ov[kk] = obj->facelist[ii].ov[kk];
				eff->rgb[kk] = 0; 
			}

			pos += sizeof(EERIE_FACE_FTL); 
			if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");
		}
	}

	// textures
	for (long i = 0; i < af3Ddh->nb_maps; i++)
	{
		char ficc[256];
		memset(ficc, 0, 256);

		if (obj->texturecontainer[i])
			strcpy(ficc, obj->texturecontainer[i]->m_texName);

		memcpy(dat + pos, ficc, 256);
		pos += 256;

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");
	}

	// groups
	if (af3Ddh->nb_groups > 0)
	{
		memcpy(dat + pos, obj->grouplist, sizeof(EERIE_GROUPLIST)*af3Ddh->nb_groups);
		pos += sizeof(EERIE_GROUPLIST) * af3Ddh->nb_groups;

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");

		for (int i = 0; i < af3Ddh->nb_groups; i++)
		{
			if (obj->grouplist[i].nb_index > 0)
			{
				memcpy(dat + pos, obj->grouplist[i].indexes, sizeof(long)*obj->grouplist[i].nb_index);
				pos += sizeof(long) * obj->grouplist[i].nb_index;

				if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");
			}
		}
	}


	// actionpoints
	if (af3Ddh->nb_action > 0)
	{
		memcpy(dat + pos, obj->actionlist, sizeof(EERIE_ACTIONLIST)*af3Ddh->nb_action);
		pos += sizeof(EERIE_ACTIONLIST) * af3Ddh->nb_action;

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");
	}

	// selections
	if (af3Ddh->nb_selections > 0)
	{
		memcpy(dat + pos, obj->selections, sizeof(EERIE_SELECTIONS)*af3Ddh->nb_selections);
		pos += sizeof(EERIE_SELECTIONS) * af3Ddh->nb_selections;

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");

		for (int i = 0; i < af3Ddh->nb_selections; i++)
		{
			memcpy(dat + pos, obj->selections[i].selected, sizeof(long)*obj->selections[i].nb_selected);
			pos += sizeof(long) * obj->selections[i].nb_selected;

			if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");
		}

		strcpy(af3Ddh->name, obj->file);
	}

	// Progressive DATA
	afsh->offset_progressive_data = -1;
	

	// Collision Spheres Data
	if (obj->sdata && obj->sdata->nb_spheres)
	{
		afsh->offset_collision_spheres = pos; //-1;
		afcsdh = (ARX_FTL_COLLISION_SPHERES_DATA_HEADER *)(dat + afsh->offset_collision_spheres);
		pos += sizeof(ARX_FTL_COLLISION_SPHERES_DATA_HEADER);

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");

		afcsdh->nb_spheres = obj->sdata->nb_spheres;

		memcpy(dat + pos, obj->sdata->spheres, sizeof(COLLISION_SPHERE)*obj->sdata->nb_spheres);
		pos += sizeof(COLLISION_SPHERE) * obj->sdata->nb_spheres;

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");
	}
	else afsh->offset_collision_spheres = -1;


	// Clothes DATA
	if (obj->cdata == NULL)
	{
		afsh->offset_clothes_data = -1;
	}
	else
	{
		afsh->offset_clothes_data = pos;
		afcdh = (ARX_FTL_CLOTHES_DATA_HEADER *)(dat + afsh->offset_clothes_data);

		afcdh->nb_cvert = obj->cdata->nb_cvert;
		afcdh->nb_springs = obj->cdata->nb_springs;
		pos += sizeof(ARX_FTL_CLOTHES_DATA_HEADER);

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");

		// now save cvert
		memcpy(dat + pos, obj->cdata->cvert, sizeof(CLOTHESVERTEX)*obj->cdata->nb_cvert);
		pos += sizeof(CLOTHESVERTEX) * obj->cdata->nb_cvert;

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");

		// now saves springs
		memcpy(dat + pos, obj->cdata->springs, sizeof(EERIE_SPRINGS)*obj->cdata->nb_springs);
		pos += sizeof(EERIE_SPRINGS) * obj->cdata->nb_springs;

		if (pos > allocsize) ShowPopup("Invalid Allocsize in ARX_FTL_Save");
	}

	afsh->offset_physics_box = -1;

	afsh->offset_cylinder = -1;

	// Now we can flush our cool FTL file to the hard drive
	FileHandle handle;
	char _error[512];

	if (pos > allocsize)
	{
		sprintf(_error, "Badly Allocated SaveBuffer...%s", gamefic);
		goto error;
	}

	char * compressed;
	compressed = NULL;
	long cpr_pos;
	cpr_pos = 0;
	LogError <<"IMPLODE NOT IMPLEMENTED";
	// TODO fix
	//compressed = STD_Implode((char *)dat, pos, &cpr_pos);

	// Now Saving Whole Buffer
	if (!(handle = FileOpenWrite(gamefic)))
	{
		sprintf(_error, "Unable to Open %s for Write...", gamefic);
		goto error;
	}

	if (FileWrite(handle, compressed, cpr_pos) != cpr_pos)
	{
		sprintf(_error, "Unable to Write to %s", gamefic);
		goto error;
	}

	FileCloseWrite(handle);
	free(compressed);
	free(dat);
	return true;

error:
	;
	ShowPopup(_error);
	free(dat);

	return false;
}
Ejemplo n.º 15
0
int CStsValueList::Aggregation(time_t a_endTime, string a_strDir, string a_strTableName, int a_nIndex)
{
    int nRet = 0;
    time_t collectEndTime = 0;
    bool blnCollectFlag = false;
    list<CStsValue*>::iterator iter;
    list<int> *lstValue = NULL;
    CStsValue *cCollectValue = NULL;
    CStsValue *cValue = NULL;
    int nFileNameLen = 0;
    char chFileName[FILE_NAME_LEN];
    string strFileName;

    for(iter = m_lstValue->begin();iter != m_lstValue->end();){
        cValue = *iter;

        collectEndTime = cValue->GetCollectEndTime();
        if(collectEndTime > a_endTime){
            break;
        }

        if(cCollectValue == NULL){
            if(cValue->GetAggregationFlag() == true){
                iter++;
                continue;
            }
            cCollectValue = cValue;
            cCollectValue->SetAggregationFlag();
            iter++;
            blnCollectFlag = false;
            continue;
        }

        if((cValue->GetCollectEndTime() - cCollectValue->GetCollectStartTime()) > 60){
            iter++;
            /* write value */
            nFileNameLen = snprintf(chFileName,FILE_NAME_LEN,"%lu_%lu_%d_%s%s",
                    cCollectValue->GetCollectStartTime(), 
                    cCollectValue->GetCollectEndTime(), a_nIndex, a_strTableName.c_str(), FILE_LOG_EXT);
            strFileName.clear();
            strFileName.append(a_strDir);
            strFileName.append("/");
            strFileName.append(chFileName);

            DEBUG_LOG("FILENAME=%s\n",strFileName.c_str());
            nRet = FileWrite(strFileName, cCollectValue);
            if(nRet != STA_OK){
                STA_LOG(STA_ERR,"File write failed(nRet=%d)\n",nRet);
            }

            cCollectValue->SetFileName(strFileName);

            cCollectValue = cValue;
            cCollectValue->SetAggregationFlag();

            blnCollectFlag = true;
            continue;
        }

        lstValue = cValue->GetValue();
        cCollectValue->UpdateValue(lstValue);
        cCollectValue->SetCollectEndTime(cValue->GetCollectEndTime());
        delete cValue;

        m_lstValue->erase(iter++);
        blnCollectFlag = false;
    }

    if((cCollectValue != NULL) && (blnCollectFlag == false)){
        /* write value */
        nFileNameLen = snprintf(chFileName,FILE_NAME_LEN,"%lu_%lu_%d_%s%s",
                cCollectValue->GetCollectStartTime(), 
                cCollectValue->GetCollectEndTime(), a_nIndex, a_strTableName.c_str(), FILE_LOG_EXT);
        strFileName.clear();
        strFileName.append(a_strDir);
        strFileName.append("/");
        strFileName.append(chFileName);

        DEBUG_LOG("FILENAME=%s\n",strFileName.c_str());
        nRet = FileWrite(strFileName, cCollectValue);
        if(nRet != STA_OK){
            STA_LOG(STA_ERR,"File write failed(nRet=%d)\n",nRet);
        }

        cCollectValue->SetFileName(strFileName);
    }

    return STA_OK;
}
Ejemplo n.º 16
0
// This routine opens the export file and put in the header info.
// It is used by ExportChart, ExportAlert, & ExportReport.
INT  ExportFileOpen (HWND hWnd, HANDLE *phFile, int IntervalMSecs, LPTSTR *ppFileName)
{
   CHAR           TempBuff [LongTextLen] ;
   TCHAR          UnicodeBuff [LongTextLen] ;
   TCHAR          UnicodeBuff1 [MiscTextLen] ;
   SYSTEMTIME     SystemTime ;
   int            StringLen ;
   INT            ErrCode = 0 ;
   FLOAT          eIntervalSecs ;

   // defined and setup in status.c
   extern TCHAR   szCurrentActivity [] ;
   extern TCHAR   szStatusFormat [] ;

   *phFile = 0 ;

   if (!FileGetName (hWnd, IDS_EXPORTFILE, UnicodeBuff))
      {
      // user cancel 
      goto Exit0 ;
      }

   *ppFileName = StringAllocate (UnicodeBuff) ;

   // open the file..
   if (!(*phFile = FileHandleCreate (UnicodeBuff)))
      {
      // can't open the file
      ErrCode = ERR_CANT_OPEN ;
      goto Exit0 ;
      }


   // export header
   StringLoad (IDS_REPORT_HEADER, UnicodeBuff) ;
   ConvertUnicodeStr (TempBuff, UnicodeBuff) ;
   StringLen = strlen (TempBuff) ;
   ConvertUnicodeStr (&TempBuff[StringLen], LocalComputerName) ;
   strcat (TempBuff, LineEndStr) ;

   if (!FileWrite (*phFile, TempBuff, strlen(TempBuff)))
      {
      ErrCode = ERR_EXPORT_FILE ;
      goto Exit0 ;
      }

   // export today's date time
   GetLocalTime (&SystemTime) ;

   StringLoad (IDS_EXPORT_DATE, UnicodeBuff) ;
   StringLen = lstrlen (UnicodeBuff) ;
   UnicodeBuff[StringLen] = TEXT(':') ;
   UnicodeBuff[StringLen+1] = TEXT(' ') ;
   SystemTimeDateString (&SystemTime, &UnicodeBuff[StringLen+2]) ;
   ConvertUnicodeStr (TempBuff, UnicodeBuff) ;
   strcat (TempBuff, LineEndStr) ;

   if (!FileWrite (*phFile, TempBuff, strlen(TempBuff)))
      {
      ErrCode = ERR_EXPORT_FILE ;
      goto Exit0 ;
      }

   StringLoad (IDS_EXPORT_TIME, UnicodeBuff) ;
   StringLen = lstrlen (UnicodeBuff) ;
   UnicodeBuff[StringLen] = TEXT(':') ;
   UnicodeBuff[StringLen+1] = TEXT(' ') ;
   SystemTimeTimeString (&SystemTime, &UnicodeBuff[StringLen+2], FALSE) ;
   ConvertUnicodeStr (TempBuff, UnicodeBuff) ;
   strcat (TempBuff, LineEndStr) ;

   if (!FileWrite (*phFile, TempBuff, strlen(TempBuff)))
      {
      ErrCode = ERR_EXPORT_FILE ;
      goto Exit0 ;
      }


   // export data source
   TSPRINTF (UnicodeBuff, szStatusFormat,
      PlayingBackLog () ?
      PlaybackLog.szFileTitle : szCurrentActivity) ;
   ConvertUnicodeStr (TempBuff, UnicodeBuff) ;
   strcat (TempBuff, LineEndStr) ;
   
   if (!FileWrite (*phFile, TempBuff, strlen(TempBuff)))
      {
      ErrCode = ERR_EXPORT_FILE ;
      goto Exit0 ;
      }


   if (!PlayingBackLog())
      {
         
      eIntervalSecs = (FLOAT)IntervalMSecs / (FLOAT) 1000.0 ;
      StringLoad (IDS_CHARTINT_FORMAT, UnicodeBuff1) ;
      TSPRINTF (UnicodeBuff, UnicodeBuff1, eIntervalSecs) ;
      ConvertDecimalPoint (UnicodeBuff) ;
      ConvertUnicodeStr (TempBuff, UnicodeBuff) ;
      strcat (TempBuff, LineEndStr) ;
   
      if (!FileWrite (*phFile, TempBuff, strlen(TempBuff)))
         {

         ErrCode = ERR_EXPORT_FILE ;
         goto Exit0 ;
         }
      }
   else
      {
      // export the log start and stop date/time
      StringLoad (IDS_START_TEXT, UnicodeBuff) ;
      StringLen = lstrlen (UnicodeBuff) ;
      LogPositionSystemTime (&(PlaybackLog.StartIndexPos), &SystemTime) ;
      SystemTimeDateString (&SystemTime, &UnicodeBuff[StringLen]) ;
      StringLen = lstrlen (UnicodeBuff) ;
      UnicodeBuff[StringLen] = TEXT(' ') ;
      StringLen++ ;
      SystemTimeTimeString (&SystemTime, &UnicodeBuff[StringLen], FALSE) ;
      ConvertUnicodeStr (TempBuff, UnicodeBuff) ;
      strcat (TempBuff, LineEndStr) ;

      if (!FileWrite (*phFile, TempBuff, strlen(TempBuff)))
         {

         ErrCode = ERR_EXPORT_FILE ;
         goto Exit0 ;
         }

      StringLoad (IDS_STOP_TEXT, UnicodeBuff) ;
      StringLen = lstrlen (UnicodeBuff) ;
      LogPositionSystemTime (&(PlaybackLog.StopIndexPos), &SystemTime) ;
      SystemTimeDateString (&SystemTime, &UnicodeBuff[StringLen]) ;
      StringLen = lstrlen (UnicodeBuff) ;
      UnicodeBuff[StringLen] = TEXT(' ') ;
      StringLen++ ;
      SystemTimeTimeString (&SystemTime, &UnicodeBuff[StringLen], FALSE) ;
      ConvertUnicodeStr (TempBuff, UnicodeBuff) ;
      strcat (TempBuff, LineEndStr) ;

      if (!FileWrite (*phFile, TempBuff, strlen(TempBuff)))
         {
         ErrCode = ERR_EXPORT_FILE ;
         goto Exit0 ;
         }

      if (hWnd == hWndAlert)
         {
         eIntervalSecs = (FLOAT)IntervalMSecs / (FLOAT) 1000.0 ;
         StringLoad (IDS_CHARTINT_FORMAT, UnicodeBuff1) ;
         TSPRINTF (UnicodeBuff, UnicodeBuff1, eIntervalSecs) ;
         ConvertDecimalPoint (UnicodeBuff) ;
         ConvertUnicodeStr (TempBuff, UnicodeBuff) ;
         strcat (TempBuff, LineEndStr) ;
      
         if (!FileWrite (*phFile, TempBuff, strlen(TempBuff)))
            {
            ErrCode = ERR_EXPORT_FILE ;
            goto Exit0 ;
            }
         }
      
      }

   return (0) ;

Exit0:

   return (ErrCode) ;

}  // ExportFileOpen
Ejemplo n.º 17
0
bool CEncoderVorbis::Init(const char* strFile, int iInChannels, int iInRate, int iInBits)
{
  // we only accept 2 / 44100 / 16 atm
  if (iInChannels != 2 || iInRate != 44100 || iInBits != 16) return false;

  // set input stream information and open the file
  if (!CEncoder::Init(strFile, iInChannels, iInRate, iInBits)) return false;

  float fQuality = 0.5f;
  if (g_guiSettings.GetInt("cddaripper.quality") == CDDARIP_QUALITY_MEDIUM) fQuality = 0.4f;
  if (g_guiSettings.GetInt("cddaripper.quality") == CDDARIP_QUALITY_STANDARD) fQuality = 0.5f;
  if (g_guiSettings.GetInt("cddaripper.quality") == CDDARIP_QUALITY_EXTREME) fQuality = 0.7f;

  if (!m_VorbisEncDll.Load() || !m_OggDll.Load() || !m_VorbisDll.Load())
  {
    // failed loading the dll's, unload it all
    CLog::Log(LOGERROR, "CEncoderVorbis::Init() Error while loading ogg.dll and or vorbis.dll");
    return false;
  }

  m_VorbisDll.vorbis_info_init(&m_sVorbisInfo);
  if (g_guiSettings.GetInt("cddaripper.quality") == CDDARIP_QUALITY_CBR)
  {
    // not realy cbr, but abr in this case
    int iBitRate = g_guiSettings.GetInt("cddaripper.bitrate") * 1000;
    m_VorbisEncDll.vorbis_encode_init(&m_sVorbisInfo, m_iInChannels, m_iInSampleRate, -1, iBitRate, -1);
  }
  else
  {
    if (m_VorbisEncDll.vorbis_encode_init_vbr(&m_sVorbisInfo, m_iInChannels, m_iInSampleRate, fQuality)) return false;
  }

  /* add a comment */
  m_VorbisDll.vorbis_comment_init(&m_sVorbisComment);
  m_VorbisDll.vorbis_comment_add_tag(&m_sVorbisComment, (char*)"comment", (char*)m_strComment.c_str());
  m_VorbisDll.vorbis_comment_add_tag(&m_sVorbisComment, (char*)"artist", (char*)m_strArtist.c_str());
  m_VorbisDll.vorbis_comment_add_tag(&m_sVorbisComment, (char*)"title", (char*)m_strTitle.c_str());
  m_VorbisDll.vorbis_comment_add_tag(&m_sVorbisComment, (char*)"album", (char*)m_strAlbum.c_str());
  m_VorbisDll.vorbis_comment_add_tag(&m_sVorbisComment, (char*)"genre", (char*)m_strGenre.c_str());
  m_VorbisDll.vorbis_comment_add_tag(&m_sVorbisComment, (char*)"tracknumber", (char*)m_strTrack.c_str());
  m_VorbisDll.vorbis_comment_add_tag(&m_sVorbisComment, (char*)"date", (char*)m_strYear.c_str());

  /* set up the analysis state and auxiliary encoding storage */
  m_VorbisDll.vorbis_analysis_init(&m_sVorbisDspState, &m_sVorbisInfo);

  m_VorbisDll.vorbis_block_init(&m_sVorbisDspState, &m_sVorbisBlock);

  /* set up our packet->stream encoder */
  /* pick a random serial number; that way we can more likely build
  chained streams just by concatenation */
  srand(time(NULL));
  m_OggDll.ogg_stream_init(&m_sOggStreamState, rand());

  {
    ogg_packet header;
    ogg_packet header_comm;
    ogg_packet header_code;

    m_VorbisDll.vorbis_analysis_headerout(&m_sVorbisDspState, &m_sVorbisComment,
                              &header, &header_comm, &header_code);

    m_OggDll.ogg_stream_packetin(&m_sOggStreamState, &header);
    m_OggDll.ogg_stream_packetin(&m_sOggStreamState, &header_comm);
    m_OggDll.ogg_stream_packetin(&m_sOggStreamState, &header_code);

    /* This ensures the actual
    * audio data will start on a new page, as per spec
    */
    while (1)
    {
      int result = m_OggDll.ogg_stream_flush(&m_sOggStreamState, &m_sOggPage);
      if (result == 0)break;
      FileWrite(m_sOggPage.header, m_sOggPage.header_len);
      FileWrite(m_sOggPage.body, m_sOggPage.body_len);
    }
  }
  m_pBuffer = new BYTE[4096];

  return true;
}
Ejemplo n.º 18
0
BOOL WritePalette(
    /************************************************************************/
    LPSTR 		lpFileName,
    LPPALETTE 	lpPalette)
{
    int ofh;		/* file handle( unbuffered) */
    FILEBUF ofd;		/* file descriptor( buffered) */
    int i;
    VERSIONINFO	version;
    RECINFO rec;

    if (!lpPalette)
        return(FALSE);

    /* open the output file */
    if ( ( ofh = _lcreat( lpFileName, 0)) < 0 )
    {
        Message( IDS_EWRITE, lpFileName);
        return( NO);
    }
    /* create a buffered stream to speed access */
    FileFDOpenWrt( &ofd, ofh, (LPTR)LineBuffer[0], 16*1024);

// write palette version
    version.Length = sizeof(version.Number);
    version.Type = PALFILE_VERSION;
    version.Number = CURRENT_VERSION;
    FileWrite(&ofd, (LPTR)&version, sizeof(version));

    while (lpPalette)
    {
        if (lpPalette->iColors || TRUE)
        {
            // write palette name
            rec.Length = lstrlen(lpPalette->szName)+1;
            rec.Type = PALFILE_NAME;
            FileWrite(&ofd, (LPTR)&rec, sizeof(rec));
            FileWrite(&ofd, (LPTR)lpPalette->szName, rec.Length);

            // write palette colors
            rec.Length = sizeof(WORD)+(lpPalette->iColors * sizeof(COLOR));
            rec.Type = PALFILE_COLORS;
            FileWrite(&ofd, (LPTR)&rec, sizeof(rec));
            intelWriteWord( &ofd, lpPalette->iColors);
            for (i = 0; i < lpPalette->iColors; ++i)
            {
                intelWriteDWord(&ofd, RGB2long(lpPalette->lpColorInfo[i].rgb));
            }

            // write color lables
            if (lpPalette->lpLabels && lpPalette->LabelsLength)
            {
                rec.Length = lpPalette->LabelsLength;
                rec.Type = PALFILE_LABELS;
                FileWrite(&ofd, (LPTR)&rec, sizeof(rec));
                FileWrite(&ofd, lpPalette->lpLabels,
                          rec.Length);
            }

            // write formating information
            if (lstrlen(lpPalette->szFormat) > 0)
            {
                rec.Length = lstrlen(lpPalette->szFormat)+1;
                rec.Type = PALFILE_FORMAT;
                FileWrite(&ofd, (LPTR)&rec, sizeof(rec));
                FileWrite(&ofd, (LPTR)lpPalette->szFormat,
                          rec.Length);
            }

            // write palette grouping
            rec.Length = 4;
            rec.Type = PALFILE_GROUP;
            FileWrite(&ofd, (LPTR)&rec, sizeof(rec));
            intelWriteDWord( &ofd, lpPalette->dwGroup);

            lpPalette = lpPalette->lpNext;
        }
    }
// write palette end record
    rec.Length = 0;
    rec.Type = PALFILE_END;
    FileWrite(&ofd, (LPTR)&rec, sizeof(rec));

    FileFlush(&ofd);

    _lclose(ofh);

    if ( ofd.err)
    {
        Message( IDS_EWRITE, lpFileName);
        return( NO);
    }
    return( YES);
}
Ejemplo n.º 19
0
/*
 *	mdextend() -- Add a block to the specified relation.
 *
 *		The semantics are nearly the same as mdwrite(): write at the
 *		specified position.  However, this is to be used for the case of
 *		extending a relation (i.e., blocknum is at or beyond the current
 *		EOF).  Note that we assume writing a block beyond current EOF
 *		causes intervening file space to become filled with zeroes.
 */
void
mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
		 char *buffer, bool isTemp)
{
	off_t		seekpos;
	int			nbytes;
	MdfdVec    *v;

	/* This assert is too expensive to have on normally ... */
#ifdef CHECK_WRITE_VS_EXTEND
	Assert(blocknum >= mdnblocks(reln, forknum));
#endif

	/*
	 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
	 * more --- we mustn't create a block whose number actually is
	 * InvalidBlockNumber.
	 */
	if (blocknum == InvalidBlockNumber)
		ereport(ERROR,
				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
				 errmsg("cannot extend file \"%s\" beyond %u blocks",
						relpath(reln->smgr_rnode, forknum),
						InvalidBlockNumber)));

	v = _mdfd_getseg(reln, forknum, blocknum, isTemp, EXTENSION_CREATE);

	seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));

	Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);

	/*
	 * Note: because caller usually obtained blocknum by calling mdnblocks,
	 * which did a seek(SEEK_END), this seek is often redundant and will be
	 * optimized away by fd.c.	It's not redundant, however, if there is a
	 * partial page at the end of the file. In that case we want to try to
	 * overwrite the partial page with a full page.  It's also not redundant
	 * if bufmgr.c had to dump another buffer of the same file to make room
	 * for the new page's buffer.
	 */
	if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not seek to block %u in file \"%s\": %m",
						blocknum, FilePathName(v->mdfd_vfd))));

	if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
	{
		if (nbytes < 0)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not extend file \"%s\": %m",
							FilePathName(v->mdfd_vfd)),
					 errhint("Check free disk space.")));
		/* short write: complain appropriately */
		ereport(ERROR,
				(errcode(ERRCODE_DISK_FULL),
				 errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
						FilePathName(v->mdfd_vfd),
						nbytes, BLCKSZ, blocknum),
				 errhint("Check free disk space.")));
	}

	if (!isTemp)
		register_dirty_segment(reln, forknum, v);

	Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
}
Ejemplo n.º 20
0
// Installation of WinPcap
void EmInstallWinPcap(HWND hWnd, RPC *r)
{
	wchar_t temp_name[MAX_SIZE];
	HGLOBAL g;
	HINSTANCE h;
	HRSRC hr;
	UINT size;
	void *data;
	IO *io;

	// Ask whether the user want to start the installation
	if (MsgBox(hWnd, MB_ICONQUESTION | MB_YESNO, _UU("EM_WPCAP_INSTALL")) == IDNO)
	{
		return;
	}

	// Generate a temporary file name
	UniFormat(temp_name, sizeof(temp_name), L"%s\\winpcap_installer.exe", MsGetTempDirW());

	// Read from the resource
	h = GetUiDll();
	hr = FindResource(h, MAKEINTRESOURCE(BIN_WINPCAP), "BIN");
	if (hr == NULL)
	{
RES_ERROR:
		MsgBox(hWnd, MB_ICONSTOP, _UU("EM_RESOURCE"));
		return;
	}

	g = LoadResource(h, hr);
	if (g == NULL)
	{
		goto RES_ERROR;
	}

	size = SizeofResource(h, hr);
	data = LockResource(g);

	if (data == NULL)
	{
		goto RES_ERROR;
	}

	// Write to a temporary file
	io = FileCreateW(temp_name);
	if (io == NULL)
	{
		goto RES_ERROR;
	}

	FileWrite(io, data, size);
	FileClose(io);

	// Run
	if (RunW(temp_name, NULL, false, true) == false)
	{
		// Failure
		FileDeleteW(temp_name);
		goto RES_ERROR;
	}

	FileDeleteW(temp_name);

	if (r == NULL)
	{
		return;
	}

	// Message after the end
	if (OS_IS_WINDOWS_NT(GetOsInfo()->OsType) == false)
	{
		// Need to restart the computer
		MsgBox(hWnd, MB_ICONINFORMATION, _UU("EM_WPCAP_REBOOT1"));
	}
	else
	{
		// Need to restart the service
		if (MsgBox(hWnd, MB_ICONQUESTION | MB_YESNO, _UU("EM_WPCAP_REBOOT2")) == IDNO)
		{
			// Not restart
		}
		else
		{
			// Restart
			RPC_TEST t;
			RPC_BRIDGE_SUPPORT t2;
			Zero(&t, sizeof(t));
			EcRebootServer(r, &t);

			SleepThread(500);

			Zero(&t2, sizeof(t2));
			CALL(hWnd, EcGetBridgeSupport(r, &t2));
		}
	}
}
Ejemplo n.º 21
0
bool CfgSaveExW3(CFG_RW *rw, FOLDER *f, wchar_t *name, UINT *written_size, bool write_binary)
{
	wchar_t tmp[MAX_SIZE];
	bool text = !write_binary;
	UCHAR hash[SHA1_SIZE];
	BUF *b;
	IO *o;
	bool ret = true;
	UINT dummy_int = 0;
	// Validate arguments
	if (name == NULL || f == NULL)
	{
		return false;
	}
	if (written_size == NULL)
	{
		written_size = &dummy_int;
	}

	// Convert to buffer
	b = CfgFolderToBuf(f, text);
	if (b == NULL)
	{
		return false;
	}
	// Hash the contents
	Hash(hash, b->Buf, b->Size, true);

	// Compare the contents to be written with the content which was written last
	if (rw != NULL)
	{
		if (Cmp(hash, rw->LashHash, SHA1_SIZE) == 0)
		{
			// Contents are not changed
			ret = false;
		}
		else
		{
			Copy(rw->LashHash, hash, SHA1_SIZE);
		}
	}

	if (ret || OS_IS_UNIX(GetOsInfo()->OsType))
	{
		// Generate a temporary file name
		UniFormat(tmp, sizeof(tmp), L"%s.log", name);
		// Copy the file that currently exist to a temporary file
		FileCopyW(name, tmp);

		// Save the new file
		o = FileCreateW(name);
		if (o != NULL)
		{
			if (FileWrite(o, b->Buf, b->Size) == false)
			{
				// File saving failure
				FileClose(o);
				FileDeleteW(name);
				FileRenameW(tmp, name);

				if (rw != NULL)
				{
					Zero(rw->LashHash, sizeof(rw->LashHash));
				}
			}
			else
			{
				// Successful saving file
				FileClose(o);
				// Delete the temporary file
				FileDeleteW(tmp);
			}
		}
		else
		{
			// File saving failure
			FileRenameW(tmp, name);

			if (rw != NULL)
			{
				Zero(rw->LashHash, sizeof(rw->LashHash));
			}
		}
	}

	*written_size = b->Size;

	// Release memory 
	FreeBuf(b);

	return ret;
}
Ejemplo n.º 22
0
static int Boot(enum boot_settings settings)
{
	int result=0;
	int opened;

	OSD_Puts("Initializing SD card\n");
	if(spi_init())
	{
		int dipsw=GetDIPSwitch();

		if(!FindDrive())
			return(0);

		if(sd_ishc())
		{
			OSD_Puts("SDHC not supported;");
			OSD_Puts("\ndisabling SD card\n\x10 OK\n");
			WaitEnter();
			dipsw|=4; // Disable SD card.
			HW_HOST(HW_HOST_CTRL)=HW_HOST_CTRLF_RESET;	// Put OCMSX into Reset again
			HW_HOST(HW_HOST_SW)=dipsw;
			SetDIPSwitch(dipsw);
		}
		else if(IsFat32())
		{
			OSD_Puts("Fat32 not supported;");
			OSD_Puts("\ndisabling SD card\n\x10 OK\n");
			WaitEnter();
			dipsw|=4; // Disable SD card.
			HW_HOST(HW_HOST_CTRL)=HW_HOST_CTRLF_RESET;	// Put OCMSX into Reset again
			HW_HOST(HW_HOST_SW)=dipsw;
			SetDIPSwitch(dipsw);
		}
		HW_HOST(HW_HOST_CTRL)=HW_HOST_CTRLF_SDCARD;	// Release reset but steal SD card

		if(opened=FileOpen(&file,"OCMSX   CFG"))	// Do we have a configuration file?
		{
			if(settings==BOOT_SAVESETTINGS)	// If so, are we saving to it, or loading from it?
			{
				int i;
				int *p=(int *)sector_buffer;
				*p++=dipsw;
				*p++=GetVolumes();
				*p++=GetMouseSettings();
				for(i=0;i<125;++i)	// Clear remainder of buffer
					*p++=0;
				FileWrite(&file,sector_buffer);
			}
			else if(settings==BOOT_LOADSETTINGS)
			{
				FileRead(&file,sector_buffer);
				dipsw=*(int *)(&sector_buffer[0]);
				SetVolumes(*(int *)(&sector_buffer[4]));
				SetMouseSettings(*(int *)(&sector_buffer[8]));
				HW_HOST(HW_HOST_SW)=dipsw;
				SetDIPSwitch(dipsw);
			}
//				printf("DIP %d, Vol %d\n",dipsw,GetVolumes());
		}

		OSD_Puts("Trying MSX3BIOS.SYS\n");
		if(!(opened=FileOpen(&file,"MSX3BIOSSYS")))	// Try and load MSX3 BIOS first
		{
			OSD_Puts("Trying BIOS_M2P.ROM\n");
			opened=FileOpen(&file,"BIOS_M2PROM"); // If failure, load MSX2 BIOS.
		}
		if(opened)
		{
			OSD_Puts("Loading BIOS\n");
			int filesize=file.size;
			unsigned int c=0;
			int bits;

			bits=0;
			c=filesize;
			while(c)
			{
				++bits;
				c>>=1;
			}
			bits-=9;

			while(filesize>0)
			{
				OSD_ProgressBar(c,bits);
				if(FileRead(&file,sector_buffer))
				{
					int i;
					int *p=(int *)&sector_buffer;
					for(i=0;i<(filesize<512 ? filesize : 512) ;i+=4)
					{
						int t=*p++;
						int t1=t&255;
						int t2=(t>>8)&255;
						int t3=(t>>16)&255;
						int t4=(t>>24)&255;
						HW_HOST(HW_HOST_BOOTDATA)=t4;
						HW_HOST(HW_HOST_BOOTDATA)=t3;
						HW_HOST(HW_HOST_BOOTDATA)=t2;
						HW_HOST(HW_HOST_BOOTDATA)=t1;
					}
				}
				else
				{
					OSD_Puts("Read failed\n");
					return(0);
				}
				FileNextSector(&file);
				filesize-=512;
				++c;
			}
			HW_HOST(HW_HOST_CTRL)=HW_HOST_CTRLF_BOOTDONE;	// Release SD card and early-terminate any remaining requests for boot data
			return(1);
		}
Ejemplo n.º 23
0
// Download thread
void ViDownloadThread(THREAD *thread, void *param)
{
	VI_INSTALL_DLG *d;
	VI_SETTING_ARCH *a;
	HWND hWnd;
	UINT num_files = 2;
	VI_DOWNLOAD_FILE files[2];
	VI_DOWNLOAD_FILE *f;
	UINT i;
	// Validate arguments
	if (thread == NULL || param == NULL)
	{
		return;
	}

	d = (VI_INSTALL_DLG *)param;
	hWnd = d->hWnd;

	Zero(files, sizeof(files));

	a = ViGetSuitableArchForCpu();

	// File body
	f = &files[0];
	StrCpy(f->SrcPath, sizeof(f->SrcPath), a->Path);

	// Configuration file
	if (IsEmptyStr(setting.SettingPath) == false)
	{
		f = &files[1];
		StrCpy(f->SrcPath, sizeof(f->SrcPath), setting.SettingPath);
	}
	else
	{
		// No configuration file
		num_files = 1;
	}

	for (i = 0;i < num_files;i++)
	{
		bool b = true;

		if (i == 0 && setting.DownloadNotRequired)
		{
			b = false;
		}

		if (b)
		{
			wchar_t tmp[MAX_SIZE];
			IO *dest = NULL;
			VI_FILE *down;
			UINT ret;
			UINT totalsize;
			UINT currentsize;
			wchar_t filename_w[MAX_PATH];

			f = &files[i];
			GetFileNameFromFilePath(f->FileName, sizeof(f->FileName), f->SrcPath);
			MakeSafeFileName(f->FileName, sizeof(f->FileName), f->FileName);

			StrToUni(filename_w, sizeof(filename_w), f->FileName);
			ConbinePathW(f->DestPathW, sizeof(f->DestPathW), MsGetMyTempDirW(), filename_w);

			ViInstallDlgSetPos(hWnd, 0);
			UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADSTART+skip), f->FileName);
			ViInstallDlgSetText(d, hWnd, S_STATUS, tmp);

			down = ViOpenFile(f->SrcPath);
			if (down == NULL)
			{
				MsgBoxEx(hWnd, MB_ICONSTOP, _U(IDS_DOWNLOAD_ERROR+skip), f->FileName);

				ViInstallDlgCancel(hWnd);
				return;
			}

			dest = FileCreateW(f->DestPathW);
			if (dest == NULL)
			{
				MsgBoxEx(hWnd, MB_ICONSTOP, _U(IDS_TEMP_ERROR+skip), f->DestPathW);

				ViCloseFile(down);
				ViInstallDlgCancel(hWnd);
				return;
			}

			totalsize = ViGetFileSize(down);
			currentsize = 0;

			UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADING3+skip), f->FileName);
			ViInstallDlgSetText(d, hWnd, S_STATUS, tmp);

			while (true)
			{
				UINT pos = 0;

				if (d->Halt)
				{
					// User cancel
					FileClose(dest);
					ViCloseFile(down);
					return;
				}

				UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADING3+skip), f->FileName);

				ViInstallDlgSetText(d, hWnd, IDS_DOWNLOADING3+skip, tmp);
				ret = ViReadFile(down, d->Buf, d->BufSize);

				if (ret == INFINITE)
				{
					// Communication error
					MsgBoxEx(hWnd, MB_ICONSTOP, _U(IDS_DOWNLOAD_ERROR+skip), f->FileName);

					FileClose(dest);
					ViCloseFile(down);
					ViInstallDlgCancel(hWnd);

					return;
				}

				// Draw progress
				currentsize += ret;

				if (totalsize != 0)
				{
					UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADING+skip),
						((float)totalsize) / 1024.0f / 1024.0f,
						((float)currentsize) / 1024.0f / 1024.0f);

					pos = (UINT)(((float)currentsize) * 100.0f / ((float)totalsize));
				}
				else
				{
					UniFormat(tmp, sizeof(tmp), _U(IDS_DOWNLOADING2+skip),
						((float)currentsize) / 1024.0f / 1024.0f);
					pos = (UINT)(((float)currentsize) * 100.0f / (1024.0f * 1024.0f * 10.0f));
				}

				ViInstallDlgSetText(d, hWnd, S_SIZEINFO, tmp);
				ViInstallDlgSetPos(hWnd, pos);

				if (ret == 0)
				{
					// Download Complete
					break;
				}
				else
				{
					FileWrite(dest, d->Buf, ret);
				}
			}

			ViCloseFile(down);
			FileClose(dest);
		}
	}

	UniStrCpy(setting.DownloadedInstallerPathW, sizeof(setting.DownloadedInstallerPathW),
		files[0].DestPathW);

	if (num_files >= 2)
	{
		UniStrCpy(setting.DownloadedSettingPathW, sizeof(setting.DownloadedSettingPathW),
			files[1].DestPathW);
	}

	PostMessageA(hWnd, WM_VI_DOWNLOAD_FINISHED, 0, 0);
}
Ejemplo n.º 24
0
int WriteCPInfo(
    PCODEPAGE pCP,
    FILE *pOutputFile)
{
    int Size = CP_INFO_SIZE;      // size of CPINFO information


    //
    //  Get the translation of the MB default char and the
    //  Unicode default char.
    //
    if (GetTransDefaultChars(pCP))
    {
        return (1);
    }

    if (Verbose)
        printf("\nWriting CP Info...\n");

    //
    //  Write size of CPInfo to file.
    //
    if (FileWrite( pOutputFile,
                   &Size,
                   sizeof(WORD),
                   1,
                   "CPINFO Table Size" ))
    {
        return (1);
    }

    //
    //  Write CodePageValue to file.
    //
    if (FileWrite( pOutputFile,
                   &(pCP->CodePageValue),
                   sizeof(WORD),
                   1,
                   "CPINFO Code Page Value" ))
    {
        return (1);
    }

    //
    //  Write MaxCharSize to file.
    //
    if (FileWrite( pOutputFile,
                   &(pCP->MaxCharSize),
                   sizeof(WORD),
                   1,
                   "CPINFO Max Char Size" ))
    {
        return (1);
    }

    //
    //  Write Default Char to file.
    //
    if (FileWrite( pOutputFile,
                   &(pCP->DefaultChar),
                   sizeof(WORD),
                   1,
                   "CPINFO Default Char" ))
    {
        return (1);
    }

    //
    //  Write Unicode Default Char to file.
    //
    if (FileWrite( pOutputFile,
                   &(pCP->UniDefaultChar),
                   sizeof(WORD),
                   1,
                   "CPINFO Unicode Default Char" ))
    {
        return (1);
    }

    //
    //  Write Translation of Default Char to file.
    //
    if (FileWrite( pOutputFile,
                   &(pCP->TransDefChar),
                   sizeof(WORD),
                   1,
                   "CPINFO Translation of Default Char" ))
    {
        return (1);
    }

    //
    //  Write Translation of Unicode Default Char to file.
    //
    if (FileWrite( pOutputFile,
                   &(pCP->TransUniDefChar),
                   sizeof(WORD),
                   1,
                   "CPINFO Translation of Unicode Default Char" ))
    {
        return (1);
    }

    //
    //  Write DBCS LeadByte Ranges to file.
    //
    if (FileWrite( pOutputFile,
                   &(pCP->LeadBytes),
                   sizeof(BYTE),
                   MAX_NUM_LEADBYTE,
                   "CPINFO LeadBytes" ))
    {
        return (1);
    }

    //
    //  Return success.
    //
    return (0);
}
Ejemplo n.º 25
0
int InstallData(char* drive){
	static const FirmInfo agb_info = { 0x8B800, 0x4CE00, 0x08006800, 0xD600, 0xE200, 0x08020000};
	static const FirmInfo twl_info = { 0x153600, 0x4D200, 0x08006800, 0xD600, 0xE200, 0x08020000};
	FIL firmfile;
	unsigned int progressWidth, progressX;
	wchar_t progressbar[8] = {0,};
	wchar_t *progress = progressbar;
	int i;

	progressWidth = getMpInfo() == MPINFO_CTR ? 7 : 3;
	progressX = (BOT_SCREEN_WIDTH - progressWidth * FONT_WIDTH) / 2;

	for (i = 0; i < progressWidth; i++)
		wcscat(progressbar, strings[STR_PROGRESS]);
	print(L"%ls", progressbar);
	ConsolePrevLine();

	//Create the workdir
	sprintf(tmpstr, "%s:%s", drive, DATAFOLDER);
	f_mkdir(tmpstr);

	//Read firmware data
	if (f_open(&firmfile, "firmware.bin", FA_READ | FA_OPEN_EXISTING) != FR_OK) return CONF_NOFIRMBIN;
	wcsncpy(progress, strings[STR_PROGRESS_OK], wcslen(strings[STR_PROGRESS_OK]));
	progress += wcslen(strings[STR_PROGRESS_OK]);
	DrawString(BOT_SCREEN, progressbar, progressX, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());

	//Create decrypted native_firm
	f_read(&firmfile, WORKBUF, NAT_SIZE, &tmpu32);
	uint8_t* n_firm = decryptFirmTitle(WORKBUF, NAT_SIZE, 0x00000002, 1);
	wcsncpy(progress, strings[STR_PROGRESS_OK], wcslen(strings[STR_PROGRESS_OK]));
	progress += wcslen(strings[STR_PROGRESS_OK]);
	DrawString(BOT_SCREEN, progressbar, progressX, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());

	getFirmPath(tmpstr, getMpInfo() == MPINFO_KTR ?
		TID_KTR_NATIVE_FIRM : TID_CTR_NATIVE_FIRM);
	if(FileOpen(&tempfile, tmpstr, 1)){
		FileWrite(&tempfile, n_firm, NAT_SIZE, 0);
		FileClose(&tempfile);
	}else {
		f_close(&firmfile);
		return CONF_ERRNFIRM;
	}
	wcsncpy(progress, strings[STR_PROGRESS_OK], wcslen(strings[STR_PROGRESS_OK]));
	progress += wcslen(strings[STR_PROGRESS_OK]);
	DrawString(BOT_SCREEN, progressbar, progressX, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());

	if (getMpInfo() != MPINFO_CTR)
		goto end;

	//Create AGB patched firmware
	f_read(&firmfile, WORKBUF, AGB_SIZE, &tmpu32);
	uint8_t* a_firm = decryptFirmTitle(WORKBUF, AGB_SIZE, 0x00000202, 1);
	if (!a_firm && checkEmuNAND())
	{
		/* Try to get the Title Key from the EmuNAND */
		a_firm = decryptFirmTitle(WORKBUF, AGB_SIZE, 0x00000202, 2);
		if (!a_firm) {
			/* If we cannot decrypt it from firmware.bin because of titlekey messed up,
			it probably means that AGB has been modified in some way. */
			//So we read it from his installed ncch...
			FindApp(0x00040138, 0x00000202, 1);
			char* path = getContentAppPath();
			if (!FileOpen(&tempfile, path, 0) && checkEmuNAND())
			{
				/* Try with EmuNAND */
				FindApp(0x00040138, 0x00000202, 2);
				path = getContentAppPath();
				if (!FileOpen(&tempfile, path, 0))
				{
					f_close(&firmfile);
					return CONF_ERRNFIRM;
				}
			}

			FileRead(&tempfile, WORKBUF, AGB_SIZE, 0);
			FileClose(&tempfile);
			a_firm = decryptFirmTitleNcch(WORKBUF, AGB_SIZE);
		}
	}

	if (a_firm) {
		if (applyPatch(a_firm, "/rxTools/system/patches/ctr/agb_firm.elf", &agb_info))
			return CONF_ERRPATCH;

		getFirmPath(tmpstr, TID_CTR_TWL_FIRM);
		if(FileOpen(&tempfile, tmpstr, 1)){
			FileWrite(&tempfile, a_firm, AGB_SIZE, 0);
			FileClose(&tempfile);
		}else {
			f_close(&firmfile);
			return CONF_ERRNFIRM;
		}
		wcsncpy(progress, strings[STR_PROGRESS_OK], wcslen(strings[STR_PROGRESS_OK]));
		progress += wcslen(strings[STR_PROGRESS_OK]);
	} else {
		wcsncpy(progress, strings[STR_PROGRESS_FAIL], wcslen(strings[STR_PROGRESS_FAIL]));
		progress += wcslen(strings[STR_PROGRESS_FAIL]); //If we get here, then we'll play without AGB, lol
	}

	DrawString(BOT_SCREEN, progressbar, progressX, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());

	//Create TWL patched firmware
	f_read(&firmfile, WORKBUF, TWL_SIZE, &tmpu32);
	uint8_t* t_firm = decryptFirmTitle(WORKBUF, TWL_SIZE, 0x00000102, 1);
	if(t_firm){
		if (applyPatch(t_firm, "/rxTools/system/patches/ctr/twl_firm.elf", &twl_info))
			return CONF_ERRPATCH;

		getFirmPath(tmpstr, TID_CTR_TWL_FIRM);
		if(FileOpen(&tempfile, tmpstr, 1)){
			FileWrite(&tempfile, t_firm, TWL_SIZE, 0);
			FileClose(&tempfile);
			//FileCopy("0004013800000102.bin", tmpstr);
		}else {
			f_close(&firmfile);
			return CONF_ERRNFIRM;
		}
		wcsncpy(progress, strings[STR_PROGRESS_OK], wcslen(strings[STR_PROGRESS_OK]));
		progress += wcslen(strings[STR_PROGRESS_OK]);
	}else{
		wcsncpy(progress, strings[STR_PROGRESS_FAIL], wcslen(strings[STR_PROGRESS_FAIL]));
		progress += wcslen(strings[STR_PROGRESS_FAIL]);
	}
	DrawString(BOT_SCREEN, progressbar, progressX, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());

	sprintf(tmpstr, "%s:%s/data.bin", drive, DATAFOLDER);
	if(FileOpen(&tempfile, tmpstr, 1)){
		FileWrite(&tempfile, __DATE__, 12, 0);
		FileWrite(&tempfile, __TIME__, 9, 12);
		FileClose(&tempfile);
	}else {
		f_close(&firmfile);
		return CONF_CANTOPENFILE;
	}
	wcsncpy(progress, strings[STR_PROGRESS_OK], wcslen(strings[STR_PROGRESS_OK]));
	progress += wcslen(strings[STR_PROGRESS_OK]);
	DrawString(BOT_SCREEN, progressbar, progressX, 50, ConsoleGetTextColor(), ConsoleGetBackgroundColor());

end:
	f_close(&firmfile);
	return 0;
}
Ejemplo n.º 26
0
void WriteSTIFile( INT8 *pData, SGPPaletteEntry *pPalette, INT16 sWidth, INT16 sHeight,	STR cOutputName, UINT32 fFlags, UINT32 uiAppDataSize )
{
    UINT32							uiOriginalSize;
    UINT8 *							pOutputBuffer = NULL;
    UINT32							uiCompressedSize;

    STCIHeader					Header;
    UINT32							uiLoop;
    image_type					Image;

    SGPPaletteEntry *		pSGPPaletteEntry;
    STCIPaletteElement	STCIPaletteEntry;

    STCISubImage *			pSubImageBuffer = NULL;
    UINT16							usNumberOfSubImages;
    UINT32							uiSubImageBufferSize=0;

    //UINT16							usLoop;

    memset( &Header, 0, STCI_HEADER_SIZE );
    memset( &Image, 0, sizeof( image_type ));


    uiOriginalSize = sWidth * sHeight * (8 / 8);

    // set up STCI header for output
    memcpy( Header.cID, STCI_ID_STRING, STCI_ID_LEN );
    Header.uiTransparentValue = 0;
    Header.usHeight = sHeight;
    Header.usWidth = sWidth;
    Header.ubDepth = 8;
    Header.uiOriginalSize = uiOriginalSize;
    Header.uiStoredSize = uiOriginalSize;
    Header.uiAppDataSize = uiAppDataSize;

    Header.fFlags |= STCI_INDEXED;
    if (Header.ubDepth == 8)
    {
        // assume 8-bit pixels indexing into 256 colour palette with 24 bit values in
        // the palette
        Header.Indexed.uiNumberOfColours = 256;
        Header.Indexed.ubRedDepth = 8;
        Header.Indexed.ubGreenDepth = 8;
        Header.Indexed.ubBlueDepth = 8;
    }

    if ((Header.fFlags & STCI_INDEXED) && (fFlags & CONVERT_ETRLE_COMPRESS))
    {
        if( !ConvertToETRLE( &pOutputBuffer, &uiCompressedSize, (UINT8 **) &pSubImageBuffer, &usNumberOfSubImages, (UINT8 *)pData, sWidth, sHeight, fFlags ) )
        {
            pOutputBuffer = NULL;//dnl ch49 061009 pOutputBuffer already MemFree this buffer
        }
        uiSubImageBufferSize = (UINT32) usNumberOfSubImages * STCI_SUBIMAGE_SIZE;

        Header.Indexed.usNumberOfSubImages = usNumberOfSubImages;
        Header.uiStoredSize = uiCompressedSize;
        Header.fFlags |= STCI_ETRLE_COMPRESSED;
    }

    //dnl ch49 061009
    if(FileExists(cOutputName))//dnl ch77 111113
        FileDelete(cOutputName);// If file exist FileOpen will not truncate, so delete.
    HWFILE hFile = FileOpen(cOutputName, FILE_ACCESS_WRITE|FILE_CREATE_ALWAYS, FALSE);
    if(!hFile)
        return;
    FileWrite(hFile, &Header, STCI_HEADER_SIZE, NULL);
    // Write palette and subimage structs, if any
    if(Header.fFlags & STCI_INDEXED)
    {
        if(pPalette != NULL)
        {
            // Have to convert palette to STCI format!
            pSGPPaletteEntry = pPalette;
            for(uiLoop = 0; uiLoop < 256; uiLoop++)
            {
                STCIPaletteEntry.ubRed = pSGPPaletteEntry[uiLoop].peRed;
                STCIPaletteEntry.ubGreen = pSGPPaletteEntry[uiLoop].peGreen;
                STCIPaletteEntry.ubBlue = pSGPPaletteEntry[uiLoop].peBlue;
                FileWrite(hFile, &STCIPaletteEntry, STCI_PALETTE_ELEMENT_SIZE, NULL);
            }
        }
        if(Header.fFlags & STCI_ETRLE_COMPRESSED)
            FileWrite(hFile, pSubImageBuffer, uiSubImageBufferSize, NULL);
    }
    // Write file data
    if(Header.fFlags & STCI_ZLIB_COMPRESSED || Header.fFlags & STCI_ETRLE_COMPRESSED)
        FileWrite(hFile, pOutputBuffer, Header.uiStoredSize, NULL);
    else
        FileWrite(hFile, Image.pImageData, Header.uiStoredSize, NULL);
    // Write app-specific data (blanked to 0)
    if(Image.pAppData == NULL)
    {
        if(Header.uiAppDataSize > 0)
            for(uiLoop=0; uiLoop<Header.uiAppDataSize; uiLoop++)
                FileWrite(hFile, "", 1, NULL);
    }
    else
        FileWrite(hFile, Image.pAppData, Header.uiAppDataSize, NULL);
    FileClose(hFile);
    if(pOutputBuffer != NULL)
        MemFree(pOutputBuffer);
}
Ejemplo n.º 27
0
int WriteMB(
    PCODEPAGE pCP,
    FILE *pOutputFile)
{
    int TblSize;                  // size of table
    int Ctr;                      // loop counter
    int Ctr2;                     // loop counter
    PDBCS_ARRAY pDBCSArray;       // ptr to DBCS array
    PDBCS_RANGE pRange;           // ptr to range structure
    register int NumRanges;       // number of DBCS ranges
    register int NumTables;       // number of tables for range


    if (Verbose)
        printf("\nWriting MB Table...\n");

    //
    //  Compute size of table and write it to the output file.
    //
    TblSize = ComputeMBSize(pCP);

    if (FileWrite( pOutputFile,
                   &TblSize,
                   sizeof(WORD),
                   1,
                   "MB size" ))
    {
        return (1);
    }

    //
    //  Write MB Table to output file.
    //
    if (FileWrite( pOutputFile,
                   pCP->pMB,
                   sizeof(WORD),
                   MB_TABLE_SIZE,
                   "MB table" ))
    {
        return (1);
    }

    //
    //  Write Glyph Table to output file (if it exists).
    //
    if (pCP->WriteFlags & F_GLYPH)
    {
        TblSize = GLYPH_TABLE_SIZE;
        if (FileWrite( pOutputFile,
                       &TblSize,
                       sizeof(WORD),
                       1,
                       "GLYPH table size" ))
        {
            return (1);
        }

        if (FileWrite( pOutputFile,
                       pCP->pGlyph,
                       sizeof(WORD),
                       GLYPH_TABLE_SIZE,
                       "GLYPH table" ))
        {
            return (1);
        }
    }
    else
    {
        TblSize = 0;
        if (FileWrite( pOutputFile,
                       &TblSize,
                       sizeof(WORD),
                       1,
                       "GLYPH table size" ))
        {
            return (1);
        }
    }

    //
    //  Write number of DBCS ranges to output file.
    //
    if (FileWrite( pOutputFile,
                   &(pCP->NumDBCSRanges),
                   sizeof(WORD),
                   1,
                   "DBCS Ranges" ))
    {
        return (1);
    }

    //
    //  Write the DBCS tables to the file (if any exist).
    //
    NumRanges = pCP->NumDBCSRanges;
    if ((NumRanges > 0) && (pCP->WriteFlags & F_DBCS))
    {
        if (Verbose)
            printf("\n  Writing DBCS Table...\n");

        //
        //  Write the offsets.
        //
        if (FileWrite( pOutputFile,
                       pCP->pDBCSOff,
                       sizeof(WORD),
                       DBCS_OFFSET_SIZE,
                       "DBCS Offsets" ))
        {
            return (1);
        }

        //
        //  Write the tables.
        //
        pDBCSArray = pCP->pDBCS;
        for (Ctr = 0; Ctr < NumRanges; Ctr++)
        {
            pRange = pDBCSArray[Ctr];

            if (Verbose)
                printf("    Writing DBCS range %x to %x\n",
                            pRange->LowRange, pRange->HighRange);

            NumTables = pRange->HighRange - pRange->LowRange + 1;
            for (Ctr2 = 0; Ctr2 < NumTables; Ctr2++)
            {
                if (FileWrite( pOutputFile,
                               pRange->pDBCSTbls[Ctr2],
                               sizeof(WORD),
                               DBCS_TABLE_SIZE,
                               "DBCS Table" ))
                {
                    return (1);
                }

                if (Verbose)
                    printf("      Writing DBCS table %d\n", Ctr2 + 1);
            }
        }
    }

    //
    //  Return success.
    //
    return (0);
}
Ejemplo n.º 28
0
int writeCfg()
{
	File fd;
	char buf[128];
	const char *p;
	char *jsonCur;
	unsigned int i;
	size_t len;
	int left, res;

	left = sizeof(buf);
	jsonCur = buf;

	*jsonCur = '{';

	left--;
	jsonCur++;

	i = 0;
	for (i = 0; i < CFG_NUM; i++) {
		if (i > 0) {
			if (left < 1)
				return 1;

			*jsonCur = ',';
			left--;
			jsonCur++;
		}

		res = snprintf(jsonCur, left, "\n\t\"%s\": ", cfgs[i].key);
		if (res < 0 || res >= left)
			return 1;

		left -= res;
		jsonCur += res;

		switch (cfgs[i].type) {
			case CFG_TYPE_INT:
				res = snprintf(jsonCur, left,
					"%d", cfgs[i].val.i);
				if (res < 0 || res >= left)
					return 1;

				len = res;
				break;

			case CFG_TYPE_BOOLEAN:
				if (cfgs[i].val.i) {
					len = sizeof("true");
					p = "true";
				} else {
					len = sizeof("false");
					p = "false";
				}

				if (len >= left)
					return -1;

				strcpy(jsonCur, p);
				len--;
				break;

			case CFG_TYPE_STRING:
				res = snprintf(jsonCur, left,
					"\"%s\"", cfgs[i].val.s);
				if (res < 0 || res >= left)
					return 1;

				len = res;
				break;

			default:
				return -1;
		}

		left -= len;
		jsonCur += len;
	}

	left -= 3;
	if (left < 0)
		return 1;

	*jsonCur = '\n';
	jsonCur++;
	*jsonCur = '}';
	jsonCur++;
	*jsonCur = '\n';
	jsonCur++;

	if (!FileOpen(&fd, jsonPath, 1))
		return 1;

	FileWrite(&fd, buf, (uintptr_t)jsonCur - (uintptr_t)buf, 0);
	FileClose(&fd);

	return 0;
}
Ejemplo n.º 29
0
void FileWriteString(int H,AnsiString s)
{
    FileWrite(H,s.c_str(),s.Length());
}
Ejemplo n.º 30
0
/*
 * lo_export -
 *	  exports an (inversion) large object.
 */
Datum
lo_export(PG_FUNCTION_ARGS)
{
	Oid			lobjId = PG_GETARG_OID(0);
	text	   *filename = PG_GETARG_TEXT_PP(1);
	File		fd;
	int			nbytes,
				tmp;
	char		buf[BUFSIZE];
	char		fnamebuf[MAXPGPATH];
	LargeObjectDesc *lobj;
	mode_t		oumask;

#ifndef ALLOW_DANGEROUS_LO_FUNCTIONS
	if (!superuser())
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("must be superuser to use server-side lo_export()"),
				 errhint("Anyone can use the client-side lo_export() provided by libpq.")));
#endif

	CreateFSContext();

	/*
	 * open the inversion object (no need to test for failure)
	 */
	lobj = inv_open(lobjId, INV_READ, fscxt);

	/*
	 * open the file to be written to
	 *
	 * Note: we reduce backend's normal 077 umask to the slightly friendlier
	 * 022. This code used to drop it all the way to 0, but creating
	 * world-writable export files doesn't seem wise.
	 */
	text_to_cstring_buffer(filename, fnamebuf, sizeof(fnamebuf));
	oumask = umask(S_IWGRP | S_IWOTH);
	fd = PathNameOpenFile(fnamebuf, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY,
						  S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	umask(oumask);
	if (fd < 0)
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create server file \"%s\": %m",
						fnamebuf)));

	/*
	 * read in from the inversion file and write to the filesystem
	 */
	while ((nbytes = inv_read(lobj, buf, BUFSIZE)) > 0)
	{
		tmp = FileWrite(fd, buf, nbytes);
		if (tmp != nbytes)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not write server file \"%s\": %m",
							fnamebuf)));
	}

	FileClose(fd);
	inv_close(lobj);

	PG_RETURN_INT32(1);
}