Ejemplo n.º 1
0
void CIpuTestHarness::TestHarnessComplete()
//
//	Test harness completed without failures
	{
	_LIT(KTestCompleteFormat, "Total Tests %d, Failed Tests %d");
	TBuf<50> text;
	text.AppendFormat(KTestCompleteFormat, iTestCount, iFailedTests->Count()); 
	WriteComment(text);
	WriteComment(KTestHarnessCompleted);
	}
Ejemplo n.º 2
0
// if iType == 0 - header file, == 1 - source
// file
int CContainerBase :: OpenSourceFile(int iType)
{
	m_sFileName = pTargetDirectory;
	
	if (iType == 0)
		m_sFileName += "/include/";
	else
		m_sFileName += "/";
	
	m_sFileName += m_sBlockName;

	if (iType == 0)
		m_sFileName += ".h";
	else
		m_sFileName += ".cpp";

	vsGeneratedFiles.push_back(m_sFileName);

	CurrentOutput.open(m_sFileName.c_str());
	
	WriteComment();
	
	if (iType == 0)
		WriteHeaderStart();
	else
	{
		if (m_sBlockName == sProjectName)
			CurrentOutput << "#define __CPP_INIT__\n";

		WriteSourceStart();
	}

	return 1;
}
Ejemplo n.º 3
0
void WriteDelim()
{
/*
  WriteComment("****************************************************************");
*/ 
  WriteComment("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
Ejemplo n.º 4
0
void CFileImageStream::WriteImageFileHeaderForSaveAllBlocks(unsigned __int64 volumeSize, unsigned bytesPerCluster)
{
  const int cReadChunkSize = 2 * 1024 * 1024;
  unsigned __int64 dataOffset;

  // first write a default file header
  fImageHeader.WriteHeaderToFile(fHandle);
  Seek(0, FILE_END);
  fImageHeader.SetVerifyFormat(CImageFileHeader::verifyCRC32);
  fImageHeader.SetCompressionFormat(fCompressionFormat);
  fImageHeader.SetVerifyOffsetAndLength(fPosition, sizeof(DWORD));
  fImageHeader.SetVolumeType(fVolumeFormat);
  WriteCrc32Checksum(0); // dummy value just to reserve space at position in file
  WriteComment();
  dataOffset = fPosition; 
  fImageHeader.SetVolumeBitmapInfo(CImageFileHeader::noVolumeBitmap, 0, 0);
  fImageHeader.SetVolumeSize(volumeSize);
  fImageHeader.SetVolumeDataOffset(dataOffset);
  fImageHeader.SetVolumeUsedSize(volumeSize);
  fImageHeader.SetClusterSize(bytesPerCluster);
  // now write file header again after all information is complete
  fImageHeader.WriteHeaderToFile(fHandle);

  // update fPosition to file position
  LARGE_INTEGER pos, curPos;
  pos.QuadPart = 0LL;
  BOOL ok = SetFilePointerEx(fHandle, pos, &curPos, FILE_CURRENT);
  fPosition = curPos.QuadPart;
}
Ejemplo n.º 5
0
void CFileImageStream::WriteImageFileHeaderAndAllocationMap(CDiskImageStream* volumeImageStore)
{
  const int cReadChunkSize = 2 * 1024 * 1024;
  unsigned __int64 allocMapLength;
  unsigned __int64 usedSize = 0;
  unsigned __int64 volumeBitmapOffset = 0;

  // first write a default file header
  fImageHeader.WriteHeaderToFile(fHandle);
  Seek(0, FILE_END);
  fImageHeader.SetVerifyFormat(CImageFileHeader::verifyCRC32);
  fImageHeader.SetCompressionFormat(fCompressionFormat);
  fImageHeader.SetVerifyOffsetAndLength(fPosition, sizeof(DWORD));
  fImageHeader.SetVolumeType(fVolumeFormat);
  WriteCrc32Checksum(0); // dummy value just to reserve space at position in file
  WriteComment();
  volumeBitmapOffset = fPosition; 
  if (volumeImageStore) {
    allocMapLength = volumeImageStore->StoreVolumeBitmap(cReadChunkSize, fHandle, fFileName.c_str());
    fImageHeader.SetVolumeBitmapInfo(CImageFileHeader::simpleCompressedRunLength, volumeBitmapOffset, allocMapLength);
    usedSize  = volumeImageStore->GetAllocatedBytes();
  }
  fImageHeader.SetVolumeSize(volumeImageStore->GetSize());
  fImageHeader.SetVolumeDataOffset(allocMapLength + volumeBitmapOffset);
  fImageHeader.SetVolumeUsedSize(usedSize);
  fImageHeader.SetClusterSize(volumeImageStore->GetBytesPerCluster());
  // now write file header again after all information is complete
  fImageHeader.WriteHeaderToFile(fHandle);

  // update fPosition to file position
  LARGE_INTEGER pos, curPos;
  pos.QuadPart = 0LL;
  BOOL ok = SetFilePointerEx(fHandle, pos, &curPos, FILE_CURRENT);
  fPosition = curPos.QuadPart;
}
Ejemplo n.º 6
0
void debug_stream_test_cb (puObject* obj)
{
  SStream* s = new SStream;
  strncpy (s->filename, "teststream.txt",(PATH_MAX-1));
  strncpy (s->mode, "w",3);
  OpenStream (s);

  WriteComment ("Comment...testing testing testing", s);
  WriteComment ("", s);
  WriteTag ('bgno', "---- object ----", s);
  WriteTag ('bgno', "---- nested Object ----", s);
  WriteTag ('int_', "---- int ----", s);
  int i = 500;
  WriteInt (&i, s);
  WriteTag ('uint', "---- unsigned int ----", s);
  unsigned int ui = 12345678;
  WriteUInt (&ui, s);
  float f = 12345.67f;
  WriteTag ('flot', "---- float ----", s);
  WriteFloat (&f, s);
  double d = 987654.3210;
  WriteTag ('dubl', "---- double ----", s);
  WriteDouble (&d, s);
  WriteTag ('stng', "---- string ----", s);
  WriteString ("This a string", s);
  SVector v;
  v.x = 1.0;
  v.y = 2.0;
  v.z = 3.0;
  WriteTag ('vect', "--- vector ----", s);
  WriteVector (&v, s);
  SPosition pos;
  pos.lat = 1000.0;
  pos.lon = 2000.0;
  pos.alt = 3000.0;
  WriteTag ('posn', "---- position ----", s);
  WritePosition (&pos, s);
  SMessage mesg;
  WriteTag ('mesg', "---- message ----", s);
  WriteMessage (&mesg, s);
  WriteTag ('endo', s);
  WriteTag ('endo', s);

  CloseStream (s);
  delete s;
}
Ejemplo n.º 7
0
void FileHeaderTest::WriteHeaderTest()
{
  unsigned __int64 off, allocMapOffset, allocMapLength, crc32Offset, dataOffset, dataLength;
  unsigned commentLength;
  
  fHandle = CreateFile(fileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  CPPUNIT_ASSERT(fHandle != INVALID_HANDLE_VALUE);

  // first write a default file header
  fImageHeader.WriteHeaderToFile(fHandle);

  crc32Offset = Seek(0, FILE_END);
  fImageHeader.SetVerifyFormat(CImageFileHeader::verifyCRC32);
  fImageHeader.SetVerifyOffsetAndLength(crc32Offset, sizeof(DWORD));
  WriteCrc32Checksum(0, crc32Offset, sizeof(DWORD)); // dummy value just to reserve space at position in file
  
  off = Seek(0, FILE_END);
  commentLength = sizeof(comment);
  
  // simulate writing a comment
  WriteComment();
  fImageHeader.SetComment(off, commentLength);

  allocMapOffset = Seek(0, FILE_END);
  allocMapLength = sizeof(allocBitmap);

  
  /* simulate writing a volume bitmap */
  WriteAllocationBitmap();
  fImageHeader.SetVolumeBitmapInfo(CImageFileHeader::simpleCompressedRunLength, allocMapOffset, allocMapLength);

  /* simulate writing data */
  dataLength  = sizeof(volumeData);
  dataOffset = Seek(0, FILE_END);
  WriteVolumeData();
 
  // now we would know real checksum, simulate writing it
  WriteCrc32Checksum(crc32Value, crc32Offset, sizeof(DWORD));

  fImageHeader.SetVolumeSize(volumeSize);
  fImageHeader.SetCompressionFormat(compressionBZIP2);
  fImageHeader.SetVolumeDataOffset(dataOffset);
  fImageHeader.SetVolumeUsedSize(cUsedSize);
  fImageHeader.SetClusterSize(clusterSize);
  fImageHeader.SetDataSize(dataLength);
  fImageHeader.SetFileCount(fileCount);
  fImageHeader.SetVolumeType(CImageFileHeader::volumePartition);
  // now write file header again after all information is complete
  fImageHeader.WriteHeaderToFile(fHandle);

  CloseHandle(fHandle);
}
Ejemplo n.º 8
0
      /// <summary>Writes a Backup file</summary>
      /// <param name="f">The file</param>
      /// <exception cref="Logic::ComException">COM Error</exception>
      /// <exception cref="Logic::IOException">An I/O error occurred</exception>
      void  BackupFileWriter::WriteFile(const BackupFile& f)
      {
         // Header
         WriteInstruction(L"version='1.0' encoding='UTF-8'");
         WriteComment(L"Written by X-Studio II");

         // Root: File type
         auto root = WriteRoot(L"backups");
         WriteAttribute(root, L"type", GetString(f.Type));

         // Write revision (newest -> oldest)
         for (auto& rev : f.Revisions)
            WriteRevision(rev, root);
      }
Ejemplo n.º 9
0
EXPORT_C void CIpuTestHarness::LogIt(TRefByValue<const TDesC> aFmt, ...)
//
//	Messages to the front end emulator and to the Inu log
	{
	VA_LIST list;
	VA_START(list,aFmt);

	TBuf<KMaxFileName + 4> buf;
	buf.Append(KTestCommentPrepend);
	buf.AppendFormatList(aFmt,list);
	VA_END(list);

	WriteComment(buf);
	}
Ejemplo n.º 10
0
void CommentFncBegin( int f, int *vars )
{
VARIABLE *var;
char * name;
int narg;
int i;

  name = varTable[ f ]->name;
  narg = varTable[ f ]->maxi;
  var = varTable[ f ];

  WriteDelim();
  WriteComment("");
  WriteComment("%s - %s", var->name, var->comment );   
  WriteComment("  Arguments :");
  for( i = 0; i < narg; i++ ) {
    var = varTable[vars[i]];
    WriteComment("     %-10s- %s", var->name, var->comment ); 
  }  
  WriteComment("");
  WriteDelim();
  NewLines(1);
}
Ejemplo n.º 11
0
void CIpuTestHarness::TestHarnessFailed()
//
//	Test harness has a failure - log information
	{
	TBuf<KMaxFileName + 4> buf;
	buf.Format(KTestHarnessFailed, iFailedTests->Count());
	WriteComment(buf);
	//	Log fialed tests' information
	for (TInt ii=0; ii<iFailedTests->Count(); ++ii)
		{
		CTestInfo* failed = iFailedTests->At(ii);
		TPtrC name = failed->Name();
		LogIt(KTestFailInfo, failed->Number(), &name, failed->ErrorCode());
		}
	}
Ejemplo n.º 12
0
EXPORT_C
#if defined (_DEBUG)
void TInuLogger::LogIt(TRefByValue<const TDesC> aFmt, ...)
//
//	Messages to the front end emulator and to the log file
	{
	VA_LIST list;
	VA_START(list,aFmt);

	TBuf<KMaxFileName> buf;
	buf.Append(KTestCommentPrepend);
	buf.AppendFormatList(aFmt,list);
	VA_END(list);

	WriteComment(buf);
	}
Ejemplo n.º 13
0
EXPORT_C void CIpuTestHarness::NextStep(const TDesC& aStepName)
//
//	Logs the next step in a test - for informative use.
	{
	if (!iCanStartTest)
		{
		TBuf<KMaxFileName + 4> buf;
		buf.Format(KNextTestStepWithDesc, iTestCount, iStepNumber, &aStepName);
		WriteComment(buf);
		iTest.Next(aStepName);
		++iStepNumber;
		}
	else
		{
		//	Panic client - bad usage - test not started
		Panic(EBadStartTest);
		}
	}
Ejemplo n.º 14
0
EXPORT_C void CTestUtils::Printf(TRefByValue<const TDesC> aFmt,...)
	{
	// Print to the log file.
	TTestOverflow overflow(*this);
	VA_LIST list;
	VA_START(list, aFmt);
	TBuf<0x100> aBuf;
	aBuf.AppendFormatList(aFmt, list, &overflow);

	if (iLogToConsole)
		{
		iRTest.Printf(aBuf);
		}

	if (iLogToFile)
		{
		WriteComment(aBuf);
		}
	}
Ejemplo n.º 15
0
void PrintLine(void)
{
  CARDINAL i = 0;
  if (!linePrinted) {
    if (TextStart >= maxCols) {
      /*This is the silly line format case*/
      if (linePosition > TextStart) PutLine();
      else Tab(TextStart);
      while (currentLinePointer[i] != CR) PutCh(currentLinePointer[i++]);
    } else {
      /*This is the sensible case*/
      if ((linePosition > TextStart) && (currentLinePointer[i] != Space))
        PutLine();
      do {

        if ((currentLinePointer[i] == CommentSymbol) || (OpcodeStart >= maxCols))
         break;
        /*Write out the label*/
        WriteField(TextStart, FALSE, &i);

        if ((currentLinePointer[i] == CR) || (currentLinePointer[i] == CommentSymbol) || (OperandStart >= maxCols))
         break ;

        /*We have an opcode*/
        if (linePosition >= OpcodeStart) PutLine();
        WriteField(OpcodeStart, FALSE, &i);

        if ((currentLinePointer[i] == CR) || (currentLinePointer[i] == CommentSymbol) || (CommentStart >= maxCols))
         break ;

        /*We have an operand*/
        if (linePosition >= OperandStart) PutLine();
        WriteField(OperandStart, TRUE, &i);
      } while (1);
      if (currentLinePointer[i] != CR) WriteComment(&i);
    }; /* if */
    PutLine();
  }; /* if */
  linePrinted = TRUE;
  linePosition = 0;
  if (PollEscape()) abortFlag = TRUE;
} /* End PrintLine */
Ejemplo n.º 16
0
EXPORT_C
#if defined (_DEBUG)
/**
Function to print inputed log string on front end emulator and to write it to the log file.
@param aFmt The descriptor containing the format string. The TRefByValue class provides a constructor which takes a TDesC type.
@see TRefByValue
@see TDesC
*/
void THttpLogger::LogIt(TRefByValue<const TDesC> aFmt, ...)
//
//	Messages to the front end emulator and to the log file
	{
	VA_LIST list;
	VA_START(list,aFmt);

	TBuf<KMaxFileName> buf;
	buf.AppendFormatList(aFmt,list,this);
	VA_END(list);

	WriteComment(buf);
	}
Ejemplo n.º 17
0
EXPORT_C void CIpuTestHarness::EndTest(TInt aErrorCode)
//
//	Logs end of test
	{
	if (!iCanStartTest)
		{
		if (iTestMode == ETestModeNormal)
			{
			//	Get ptr to this test's entry in failed list - will be the last entry
			TBuf<KMaxFileName + 4> buf;
			TInt index = iFailedTests->Count();
			CTestInfo* ptr = iFailedTests->At(--index);
			if (aErrorCode)
				{
				//	Set the error code
				ptr->SetErrorCode(aErrorCode);
				buf.Format(KTestFailed, iTestCount, aErrorCode);
				WriteComment(buf);
				}
			else
				{
				//	Remove entry from list of failed tests
				delete ptr;
				iFailedTests->Delete(index);
				}
			
			}
		//	Allow new test to start
		iTest.End();
		iCanStartTest = ETrue;
		}
	else
		{
		if (iTestMode == ETestModeNormal)
			//	Panic client - bad usage - test not started
			Panic(EBadEndTest);
		// don't panic when we are memory leak testing as EndTestL will never get called to reset the test properly
		}
	}
Ejemplo n.º 18
0
EXPORT_C void CIpuTestHarness::StartTestL(const TDesC& aName)
//
//	Logs start of test aName
	{
	if (iCanStartTest)
		{
		//  - increment test count
		++iTestCount;
		
		if (iTestMode == ETestModeNormal) // don't add this info when we are doing memory leak testing otherwise it
										  // would get leaked!
			{

			//	Add this test to failed test list - set errorcode to zero
			CTestInfo* temp = CTestInfo::NewLC(aName, iTestCount, 0);
			iFailedTests->AppendL(temp);
			CleanupStack::Pop();	//	temp

			//	Stop new test being started until this one has ended
			iTest.Start(aName);
			iCanStartTest = EFalse;
			}

		
		TBuf<KMaxFileName + 4> buf;
		buf.Format(KTestStartingWithDesc, iTestCount, &aName);
		WriteComment(buf);

		// Reset iStepNumber - start at 1
		iStepNumber = 1;
		}
	else
		{
		//	Panic client - bad usage - not allowed to nest tests
		Panic(EBadStartTest);
		}
	}
Ejemplo n.º 19
0
  void XmlWriter::WriteNode(const Node& rNode)
  {
    switch (rNode.GetType())
    {
    case Node::TypeElement:
      WriteElement(rNode.GetElement());
      break;

    case Node::TypeText:
      WriteText(static_cast<const Text&>(rNode));
      break;

    case Node::TypeComment:
      WriteComment(static_cast<const Comment&>(rNode));
      break;

    case Node::TypeCdata:
      WriteCdata(static_cast<const Cdata&>(rNode));
      break;

    default:
      STAFF_THROW_ASSERT("Invalid Node Type: " + ToString(rNode.GetType()));
    }
  }
Ejemplo n.º 20
0
void MATLAB_FunctionBegin( int f, ... )
{
    Va_list args;
    int i;
    int v;
    int vars[20];
    char * name;
    int narg;
    FILE *oldf;
    char buf[200], bufname[200];
    time_t t;

    name = varTable[ f ]->name;
    narg = varTable[ f ]->maxi;

    /*Adi - each Matlab functin requires a separate file*/
    sprintf( buf, "%s_%s.m", rootFileName, varTable[ f ]->name );
    mex_funFile = fopen(buf, "w");
    if( mex_funFile == 0 ) {
        FatalError(3,"%s: Can't create file", buf );
    }
    UseFile( mex_funFile );
    /*Adi*/


    Va_start( args, f );
    for( i = 0; i < narg; i++ )
        vars[ i ] = va_arg( args, int );
    va_end( args );

    CommentFncBegin( f, vars );

    WriteDelim();
    WriteComment("");
    WriteComment("Generated by KPP - symbolic chemistry Kinetics PreProcessor" );
    WriteComment("    KPP is developed at CGRER labs University of Iowa by" );
    WriteComment("    Valeriu Damian & Adrian Sandu" );
    WriteComment("");
    WriteComment("%-20s : %s", "File", buf  );
    strcpy( buf, (char*)ctime( &t ) );
    buf[ (int)strlen(buf) - 1 ] = 0;
    WriteComment("%-20s : %s", "Time", buf );
    WriteComment("%-20s : %s", "Working directory", getcwd(buf, 200) );
    WriteComment("%-20s : %s", "Equation file", eqFileName );
    WriteComment("%-20s : %s", "Output root filename", rootFileName );
    WriteComment("");
    WriteDelim();
    NewLines(1);

    MATLAB_FunctionStart( f, vars );
    NewLines(1);

    FlushBuf();

    MapFunctionComment( f, vars );
}
Ejemplo n.º 21
0
void CommentFunctionEnd( int f )
{
  WriteComment("End of %s function", varTable[ f ]->name );   
  WriteDelim();
  NewLines(2);
}
Ejemplo n.º 22
0
void OpenFile( FILE **fpp, char *name, char * ext, char * identity )
{
char bufname[200];
char buf[200];
time_t t;
int blength;

  time( &t );
  sprintf( bufname, "%s%s", name, ext );  
  if( *fpp ) fclose( *fpp );
  *fpp = fopen( bufname, "w" );
  if ( *fpp == 0 ) 
    FatalError(3,"%s: Can't create file", bufname );
 
  UseFile( *fpp );
  
  WriteDelim();
  WriteComment("");
  WriteComment("%s",identity);
  WriteComment("");
  WriteComment("Generated by KPP-%s symbolic chemistry Kinetics PreProcessor",
                KPP_VERSION );
  WriteComment("      (http://www.cs.vt.edu/~asandu/Software/KPP)");
  WriteComment("KPP is distributed under GPL, the general public licence");
  WriteComment("      (http://www.gnu.org/copyleft/gpl.html)");
  WriteComment("(C) 1995-1997, V. Damian & A. Sandu, CGRER, Univ. Iowa" );
  WriteComment("(C) 1997-2005, A. Sandu, Michigan Tech, Virginia Tech" );
  WriteComment("    With important contributions from:" );
  WriteComment("       M. Damian, Villanova University, USA");
  WriteComment("       R. Sander, Max-Planck Institute for Chemistry, Mainz, Germany");
  WriteComment("");
  WriteComment("%-20s : %s", "File", bufname );
  strcpy( buf, ctime( &t ) ); 
  buf[ (int)strlen(buf) - 1 ] = 0;
  WriteComment("%-20s : %s", "Time", buf );
  WriteComment("%-20s : %s", "Working directory", getcwd(buf, 200) );
  WriteComment("%-20s : %s", "Equation file", eqFileName );
  WriteComment("%-20s : %s", "Output root filename", rootFileName );
  WriteComment("");
  WriteDelim();
  NewLines(1);  
/* Include Headers in .c  Files, except Makefile */
  blength = strlen(bufname);
  if ( (bufname[blength-2]=='.')&&(bufname[blength-1]=='c') ) {
    C_Inline("#include <stdio.h>");
    C_Inline("#include <stdlib.h>");
    C_Inline("#include <math.h>");
    C_Inline("#include <string.h>");
    C_Inline("#include \"%s_Parameters.h\"", rootFileName);
    C_Inline("#include \"%s_Global.h\"", rootFileName);
    if( useJacSparse )
       C_Inline("#include \"%s_Sparse.h\"", rootFileName);
    }   
  NewLines(2);
}
Ejemplo n.º 23
0
/*!
 This is a recursive function that gets the type of the \c value object and
 calls several protected functions depending on the type:

 \li \c WriteNullvalue for type NULL
 \li \c WriteStringValue() for STRING and CSTRING types
 \li \c WriteIntValue for INT types
 \li \c WriteUIntValue for UINT types
 \li \c WriteBoolValue for BOOL types
 \li \c WriteDoubleValue for DOUBLE types
 \li \c WriteMemoryBuff for MEMORYBUFF types

 If the value is an array or key/value map (types ARRAY and OBJECT), the function
 iterates through all JSON value object in the array/map and calls itself for every
 item in the container.
*/
int
wxJSONWriter::DoWrite( wxOutputStream& os, const wxJSONValue& value, const wxString* key, bool comma )
{
    // note that this function is recursive

    // some variables that cannot be allocated in the switch statement
    const wxJSONInternalMap* map = 0;
    int size;
    m_colNo = 1; m_lineNo = 1;
    // determine the comment position; it is one of:
    //
    //  wxJSONVALUE_COMMENT_BEFORE
    //  wxJSONVALUE_COMMENT_AFTER
    //  wxJSONVALUE_COMMENT_INLINE
    //
    // or -1 if comments have not to be written
    int commentPos = -1;
    if ( value.GetCommentCount() > 0 && (m_style & wxJSONWRITER_WRITE_COMMENTS))  {
        commentPos = value.GetCommentPos();
        if ( ( m_style & wxJSONWRITER_COMMENTS_BEFORE) != 0 ) {
            commentPos = wxJSONVALUE_COMMENT_BEFORE;
        }
        else if ( (m_style & wxJSONWRITER_COMMENTS_AFTER) != 0 ) {
            commentPos = wxJSONVALUE_COMMENT_AFTER;
        }
    }

    int lastChar = 0;  // check if WriteComment() writes the last LF char

    // first write the comment if it is BEFORE
    if ( commentPos == wxJSONVALUE_COMMENT_BEFORE )   {
        lastChar = WriteComment( os, value, true );
        if ( lastChar < 0 )   {
            return lastChar;
        }
        else if ( lastChar != '\n' )  {
            WriteSeparator( os );
        }
    }

    lastChar = WriteIndent( os );
    if ( lastChar < 0 )   {
        return lastChar;
    }

    // now write the key if it is not NULL
    if ( key )   {
        lastChar = WriteKey( os, *key );
    }
    if ( lastChar < 0 )   {
        return lastChar;
    }

    // now write the value
    wxJSONInternalMap::const_iterator it;    // declare the map object
    long int count = 0;

    wxJSONType t = value.GetType();
    switch ( t )  {
    case wxJSONTYPE_INVALID :
        WriteInvalid( os );
        wxFAIL_MSG( _T("wxJSONWriter::WriteEmpty() cannot be called (not a valid JSON text"));
        break;

    case wxJSONTYPE_INT :
    case wxJSONTYPE_SHORT :
    case wxJSONTYPE_LONG :
    case wxJSONTYPE_INT64 :
        lastChar = WriteIntValue( os, value );
        break;

    case wxJSONTYPE_UINT :
    case wxJSONTYPE_USHORT :
    case wxJSONTYPE_ULONG :
    case wxJSONTYPE_UINT64 :
        lastChar = WriteUIntValue( os, value );
        break;

    case wxJSONTYPE_NULL :
        lastChar = WriteNullValue( os );
        break;
    case wxJSONTYPE_BOOL :
        lastChar = WriteBoolValue( os, value );
        break;

    case wxJSONTYPE_DOUBLE :
        lastChar = WriteDoubleValue( os, value );
        break;

    case wxJSONTYPE_STRING :
    case wxJSONTYPE_CSTRING :
        lastChar = WriteStringValue( os, value.AsString());
        break;

    case wxJSONTYPE_MEMORYBUFF :
        lastChar = WriteMemoryBuff( os, value.AsMemoryBuff());
        break;

    case wxJSONTYPE_ARRAY :
        ++m_level;
        os.PutC( '[' );
        // the inline comment for objects and arrays are printed in the open char
        if ( commentPos == wxJSONVALUE_COMMENT_INLINE )   {
            commentPos = -1;  // we have already written the comment
            lastChar = WriteComment( os, value, false );
            if ( lastChar < 0 )   {
                return lastChar;
            }
            if ( lastChar != '\n' )   {
                lastChar = WriteSeparator( os );
            }
        }
        else   {    // comment is not to be printed inline, so write a LF
            lastChar = WriteSeparator( os );
            if ( lastChar < 0 )   {
                return lastChar;
            }
        }

        // now iterate through all sub-items and call DoWrite() recursively
        size = value.Size();
        for ( int i = 0; i < size; i++ )  {
            bool comma = false;
            if ( i < size - 1 )  {
                comma = true;
            }
            wxJSONValue v = value.ItemAt( i );
            lastChar = DoWrite( os, v, 0, comma );
            if ( lastChar < 0 )  {
                return lastChar;
            }

        }
        --m_level;
        lastChar = WriteIndent( os );
        if ( lastChar < 0 )   {
            return lastChar;
        }
        os.PutC( ']' );
        break;

    case wxJSONTYPE_OBJECT :
        ++m_level;

        os.PutC( '{' );
        // the inline comment for objects and arrays are printed in the open char
        if ( commentPos == wxJSONVALUE_COMMENT_INLINE )   {
            commentPos = -1;  // we have already written the comment
            lastChar = WriteComment( os, value, false );
            if ( lastChar < 0 )   {
                return lastChar;
            }
            if ( lastChar != '\n' )   {
                WriteSeparator( os );
            }
        }
        else   {
            lastChar = WriteSeparator( os );
        }

        map = value.AsMap();
        size = value.Size();
        count = 0;
        for ( it = map->begin(); it != map->end(); ++it )  {
            // get the key and the value
            wxString key = it->first;
            const wxJSONValue& v = it->second;
            bool comma = false;
            if ( count < size - 1 )  {
                comma = true;
            }
            lastChar = DoWrite( os, v, &key, comma );
            if ( lastChar < 0 )  {
                return lastChar;
            }
            count++;
        }
        --m_level;
        lastChar = WriteIndent( os );
        if ( lastChar < 0 )   {
            return lastChar;
        }
        os.PutC( '}' );
        break;

    default :
        // a not yet defined wxJSONType: we FAIL
        wxFAIL_MSG( _T("wxJSONWriter::DoWrite() undefined wxJSONType type"));
        break;
    }

    // writes the comma character before the inline comment
    if ( comma )  {
        os.PutC( ',' );
    }

    if ( commentPos == wxJSONVALUE_COMMENT_INLINE )   {
        lastChar = WriteComment( os, value, false );
        if ( lastChar < 0 )   {
            return lastChar;
        }
    }
    else if ( commentPos == wxJSONVALUE_COMMENT_AFTER )   {
        WriteSeparator( os );
        lastChar = WriteComment( os, value, true );
        if ( lastChar < 0 )   {
            return lastChar;
        }
    }
    if ( lastChar != '\n' )  {
        lastChar = WriteSeparator( os );
    }
    return lastChar;
}
Ejemplo n.º 24
0
//
//---------------------------------------------------------
//
// PBN File output routine
//
BOOL CEasyBDoc::WriteFilePBN(CArchive& ar) 
{
	pFile = ar.GetFile();
	ASSERT(pFile != NULL);

	// write header
	WriteComment("");
	WriteComment("EXPORT");
	WriteComment("PBN Format 1.0");
	WriteComment(FormString("File generated by Easy Bridge version %s", theApp.GetProgramVersionString()));
	WriteComment("");

	//
	// write the data
	//

	// Event tag
	WriteLine(TAG_EVENT, FormString("%s Game", theApp.GetValue(tstrProgramTitle)));

	// Site Tag
	WriteLine(TAG_SITE, "At Home"); // NCR added At Home

	// Date Tag
	CTime time = CTime::GetCurrentTime();
	WriteLine(TAG_DATE, time.Format("%Y.%m.%d"));

/*
 * skip the round tag -- no longer mandatory in PBN 0.91+
 *
	// Round Tag
	WriteLine(TAG_ROUND, "");
 */

	// Board Tag
	WriteLine(TAG_BOARD, "1"); // NCR added 1

	// West/North/East/South Tags
	WriteLine(TAG_WEST, "Computer");
	WriteLine(TAG_NORTH, "Computer");
	WriteLine(TAG_EAST, "Computer");
	WriteLine(TAG_SOUTH, "Human Player");

	// Dealer Tag
	WriteLine(TAG_DEALER, FormString("%c", PositionToChar(m_nDealer)));

	// Vulnerable Tag
	CString strVulnerable;
	if ((m_bVulnerable[NORTH_SOUTH]) && (m_bVulnerable[EAST_WEST]))
		strVulnerable = "Both";
	else if (m_bVulnerable[NORTH_SOUTH])
		strVulnerable = "NS";
	else if (m_bVulnerable[EAST_WEST])
		strVulnerable = "EW";
	else
		strVulnerable = "None";
	WriteLine(TAG_VULNERABLE, strVulnerable);

	// deal tag
	CString strDeal = "W:";
	int nPos = WEST;
	int i; // NCR-FFS added here, removed below
	for(/*int*/ i=0;i<4;i++)
	{
		CCardHoldings& cards = m_pPlayer[nPos]->GetHand().GetInitialHand();
		strDeal += cards.GetGIBFormatHoldingsString();
		nPos = GetNextPlayer(nPos);
		if (i < 3)
			strDeal += ' ';
	}
	WriteLine(TAG_DEAL, strDeal);

	// Scoring tag
	if (theApp.IsRubberInProgress())
		WriteLine(TAG_SCORING, _T("Rubber"));
	else
		WriteLine(TAG_SCORING, _T("None"));

	// Declarer Tag
	if (ISPOSITION(m_nDeclarer))
		WriteLine(TAG_DECLARER, FormString("%c", PositionToChar(m_nDeclarer)));
	else
		WriteLine(TAG_DECLARER, "?");

	// Contract Tag
	if (ISBID(m_nContract)) 
	{
		// NCR Include ContractToString() here as PBN file does NOT have space before X
		CString strBid;
		strBid.Format("%d%s", 
					  BID_LEVEL(m_nContract), 
					  szSuitNameShort[BID_SUIT(m_nContract)]);
		int nModifier = pDOC->GetContractModifier();
		if (nModifier > 0)
			strBid += FormString("%s", ((nModifier == 1)? "X" : "XX")); // w/o space

		WriteLine(TAG_CONTRACT, strBid);  // NCR replaced ContractToString(m_nContract)
	}
	else
		WriteLine(TAG_CONTRACT, "?");

	// Result tag
	if (m_numTricksPlayed == 13)
		WriteLine(TAG_RESULT, FormString("%d", m_numTricksWon[m_nContractTeam])); // NCR removed extra "s
	else
		WriteLine(TAG_RESULT, "?");

	//
	// write out the hands in comment form
	//
	CString strHands = "{\r\n" + pDOC->FormatOriginalHands() + "}";
	WriteLine(strHands);

	//
	// write out auction
	//
	CString strBids = FormString("[Auction \"%c\"]", PositionToChar(m_nDealer)); // NCR Lowercased
	if (m_numBidsMade > 0)
		strBids += "\r\n";
	nPos = m_nDealer;
	for(i=0;i<m_numBidsMade;i++)
	{
		strBids += FormString("%s ", ::BidToPBNString(m_nBiddingHistory[i]));
		nPos = ::GetNextPlayer(nPos);
		if ( (((i+1) % 4) == 0) && (i < m_numBidsMade-1) )
			strBids += "\r\n";
	}
	// add marker if needed
	if (!ISBID(m_nContract))
		strBids += "\r\n*";
	// and write out
	WriteLine(strBids);


	//
	// write out plays
	//
	CString strPlays = FormString("[Play \"%c\"]", PositionToChar(m_nGameLead));  // NCR Lowercased
	if (m_numTricksPlayed> 0)
		strPlays += "\r\n";
	bool bLastRowFnd = false;  // NCR added - only output single row with -s
	for(i=0;i<m_numTricksPlayed;i++)
	{
		int nPos = m_nGameLead;
		for(int j=0;j<4;j++)
		{
			CCard* pCard = m_pGameTrick[i][nPos];
			if (pCard == NULL) {
				strPlays += "-  ";
				bLastRowFnd = true;  // NCR this row will end the output
			}
			else
				strPlays += FormString("%s ", pCard->GetName());
			nPos = ::GetNextPlayer(nPos);
		} // end for(j) thru poisitions
		if (i < m_numTricksPlayed-1)
			strPlays += "\r\n";
		if(bLastRowFnd)
			break;  // NCR finished output plays on line with -s
	} // end for(i) thru tricks
	// add marker if needed
	if (m_numTricksPlayed < 13)
		strPlays += "\r\n*";
	// and write out
	WriteLine(strPlays);


	// Generator Tag
	WriteLine(TAG_GENERATOR, FormString("Easy Bridge version %s", theApp.GetProgramVersionString()));

	// Description Tag
	WriteLine(TAG_DESCRIPTION, m_strFileDescription);

	// blank line
//	SkipLine();

	//
	// write out the auction
	//

	//	
	// All done
	//
	ar.Flush();
	return TRUE;
}
Ejemplo n.º 25
0
	//!Save the XML Element based with or without formatting
	int HtlXDLWriter::SaveXDLElement(HtlElement * ptrElement, std::string & strOutput, bool blnWithFormatting)
	{	
		/*
		//SAVE ELEMENT
		START THE OPENTAG
		SERIALIZE THE ATTRIBUTES INTO THE OPEN TAG
		CLOSE THE OPEN TAG
		WRITE THE VALUE
		WRITE THE COMMENTS
		WRITE THE PROCESSES
		WRITE THE SUB ELEMENTS
		WRITE THE CLOSE TAG
		*/
		int i,intNumAttributes,intNumComments,intNumProcesses,intNumSubElements;
		int intTemp, intReturn;
		bool blnNullNode = false;
		bool blnRootNode = false;
		bool blnInline = false;
		intReturn = 1;
		blnRootNode = ptrElement->IsRootNode();
		blnNullNode = ptrElement->IsNullNode();
		intNumAttributes = ptrElement->CountAttributes();
		intNumComments = ptrElement->CountComments();
		intNumProcesses = ptrElement->CountProcesses();
		intNumSubElements = ptrElement->CountSubElements();
		if((intNumComments <= 0)&&(intNumProcesses <= 0)&&(intNumSubElements <= 0))
		{
			//then treat as an inline HtlElement
			blnInline = true;
		};
		//if the element is the root node, and an xml processing statement is present, then write that first.
		if((ptrElement->Get_blnRootNode() == true)&&(intNumProcesses > 0))
		{
			//write a carriage return if necessary for formatting
			for(i = 0; i < intNumProcesses;i++)
			{
				intTemp = WriteProcess(ptrElement->GetProcess(i),strOutput,blnWithFormatting);
				if(intTemp < 0){intReturn = -1;};
			};
			//write a carriage return if necessary for formatting
			if(blnWithFormatting){strOutput += '\n';};
		};

		//START THE OPENTAG///////////////////////////////////////////////
		intTemp = WriteOpenTag(ptrElement,strOutput,blnWithFormatting);
		if(intTemp < 0){intReturn = -1;};

		if(blnNullNode)
		{
			return 1;
		};

		if(blnInline)
		{
			//then treat as an inline XML Element
			intTemp = WriteValue(ptrElement,strOutput,false);
			if(intTemp < 0){intReturn = -1;};
			//write the close tag inline
			intTemp = WriteCloseTag(ptrElement,strOutput,false);
			if(intTemp < 0){intReturn = -1;};
			return intReturn;
		}else{
			//WRITE THE VALUE////////////////////////////////////////////////
			intTemp = WriteValue(ptrElement,strOutput,blnWithFormatting);
			if(intTemp < 0){intReturn = -1;};
			//WRITE THE PROCESSES/////////////////////////////////////////////
			if((ptrElement->Get_blnRootNode() == false)&&(intNumProcesses > 0))
			{
				//write a carriage return if necessary for formatting
				for(i = 0; i < intNumProcesses;i++)
				{
					intTemp = WriteProcess(ptrElement->GetProcess(i),strOutput,blnWithFormatting);
					if(intTemp < 0){intReturn = -1;};
				};
			};
			//WRITE THE COMMENTS/////////////////////////////////////////////
			if(intNumComments > 0)
			{
				//write a carriage return if necessary for formatting
				for(i = 0; i < intNumComments;i++)
				{
					intTemp = WriteComment(ptrElement->GetComment(i),strOutput,blnWithFormatting);
					if(intTemp < 0){intReturn = -1;};
				};
			};
			//WRITE THE SUB ELEMENTS/////////////////////////////////////////////
			if(intNumSubElements > 0)
			{
				//write a carriage return if necessary for formatting
				for(i = 0; i < intNumSubElements;i++)
				{
					intTemp = SaveXDLElement(ptrElement->GetSubElement(i),strOutput, blnWithFormatting);
					if(intTemp < 0){intReturn = -1;};
				};
			};
			//WRITE THE CLOSE TAG 
			intTemp = WriteCloseTag(ptrElement,strOutput,blnWithFormatting);
			if(intTemp < 0){intReturn = -1;};
			return intReturn;
		};//end simple inline element check
		return intReturn;
	};
Ejemplo n.º 26
0
int WriteGIFHeader(FILE *fp, int w, int h, byte *rmap, byte *gmap, byte *bmap,
             int numcols, ColorStyleType colorstyle, char *comment)
{ int   RWidth, RHeight;
  int   LeftOfs, TopOfs;
  int   ColorMapSize;
  int   InitCodeSize, BitsPerPixel;
  int   Background;
  int   i,j;
  int   nc;
  int   Interlace;

  struct GifStore *aGifStore = (struct GifStore *)malloc(sizeof(struct GifStore));
  if (aGifStore==NULL)
  { AVSerror("WriteGIFHeader: out of memory");
    return AVS_ERROR;
  }
  memset(aGifStore, 0, sizeof(struct GifStore));

  Interlace = 0;
  Background = 0;

  for (i=0; i<256; i++)
    aGifStore->pc2nc[i] = aGifStore->r1[i] = aGifStore->g1[i] = aGifStore->b1[i] = 0;

  /* compute number of unique colors */
  nc = 0;

  for (i=0; i<numcols; i++)
  { /* see if color #i is already used */
    for (j=0; j<i; j++)
    { if (rmap[i] == rmap[j] && gmap[i] == gmap[j] && bmap[i] == bmap[j])
        break;
    }

    if (j==i)    /* wasn't found */
    { aGifStore->pc2nc[i] = (byte)nc;
      aGifStore->r1[nc] = rmap[i];
      aGifStore->g1[nc] = gmap[i];
      aGifStore->b1[nc] = bmap[i];
      nc++;
    }
    else
      aGifStore->pc2nc[i] = aGifStore->pc2nc[j];
  }

  /* figure out 'BitsPerPixel' */
  for (i=1; i<8; i++)
    if ( (1<<i) >= nc)
      break;

  BitsPerPixel = (char)i;

  ColorMapSize = 1 << BitsPerPixel;

  RWidth  = w;
  RHeight = h;
  LeftOfs = TopOfs = 0;

  if (BitsPerPixel <= 1) InitCodeSize = 2;
                    else InitCodeSize = BitsPerPixel;

  if (!fp)
  { AVSerror("WriteGIFHeader: file not open for writing");
    free(aGifStore);
    return AVS_ERROR;
  }

  fwrite("GIF89a", (size_t) 1, (size_t) 6, fp);    /* the GIF magic number */

  putword2(RWidth, fp);           /* screen descriptor */
  putword2(RHeight, fp);

  if (colorstyle==csGlobalPalette)
  { i = 0x80;	                   /* Yes, there is a color map */
    i |= (8-1)<<4;                 /* OR in the color resolution (hardwired 8) */
    i |= (BitsPerPixel - 1);       /* OR in the # of bits per pixel */
  }
  else
    i = 0;
  fputc(i,fp);

  fputc(Background, fp);         /* background color */

  fputc(0, fp);                  /* future expansion byte */

  if (colorstyle==csGlobalPalette)
    WritePalette(fp, aGifStore, ColorMapSize);
  WriteComment(fp, comment);

  free(aGifStore);

  return AVS_OK;
}