Ejemplo n.º 1
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE hFullLib;
    HANDLE hShortLib;
    HANDLE hRelLib;

    int    iRetVal  = FAIL;
    char   fullPath[_MAX_DIR];
    char drive[_MAX_DRIVE];
    char dir[_MAX_DIR];
    char relTestDir[_MAX_DIR];
    char fname[_MAX_FNAME];
    char ext[_MAX_EXT];
    
    BOOL bRc = FALSE;
    char   relLibPath[_MAX_DIR];


    /* Initialize the PAL. */
    if ((PAL_Initialize(argc, argv)) != 0)
    {
        return (FAIL);
    }

    /* Initalize the buffer.
     */
    memset(fullPath, 0, _MAX_DIR);

    /* Get the full path to the library (DLL).
     */
  
       if (NULL != _fullpath(fullPath,argv[0],_MAX_DIR)) {
	
	 _splitpath(fullPath,drive,dir,fname,ext);
	 _makepath(fullPath,drive,dir,LibraryName,"");
	 
	
	} else {
		Fail("ERROR: conversion from relative path \" %s \" to absolute path failed. _fullpath returned NULL\n",argv[0]);
	}

       /* Get relative path to the library
	*/
       _splitpath(argv[0], drive, relTestDir, fname, ext);
       _makepath(relLibPath,drive,relTestDir,LibraryName,"");


    /* Call Load library with the short name of
     * the dll.
     */
    hShortLib = LoadLibrary(LibraryName);
    if(hShortLib == NULL)
    {
        Fail("ERROR:%u:Short:Unable to load library %s\n", 
             GetLastError(), 
             LibraryName);
    }
    
    /* Test the loaded library.
     */
    if (!TestDll(hShortLib))
    {
        iRetVal = FAIL;
        goto cleanUpOne;
    }

    /* Call Load library with the full name of
     * the dll.
     */
    hFullLib = LoadLibrary(fullPath);
    if(hFullLib == NULL)
    {
        Trace("ERROR:%u:Full:Unable to load library %s\n", 
              GetLastError(), 
              fullPath);
        iRetVal = FAIL;
        goto cleanUpTwo;
    }

    /* Test the loaded library.
     */
    if (!TestDll(hFullLib))
    {
        iRetVal = FAIL;
        goto cleanUpTwo;
    }

    /*
    ** Call the load library with the relative path
    ** wrt to the directory ./testloadlibrary/.. 
    ** since we don't want to make any assumptions
    ** regarding the type of build
    */
    hRelLib = LoadLibrary(relLibPath);
    if(hRelLib == NULL)
    {
        Trace("ERROR:%u:Rel:Unable to load library at %s\n", 
              GetLastError(), relLibPath);
        iRetVal = FAIL;
        goto cleanUpTwo;
    }

    /* Test the loaded library.
     */
    if (!TestDll(hRelLib))
    {
        iRetVal = FAIL;
        goto cleanUpThree;
    }

   if( hRelLib != hFullLib )
   {
        Trace("Relative and Absolute Paths to libraries don't have same handle\n");
            iRetVal = FAIL;
            goto cleanUpThree;
   }

   if( hRelLib != hShortLib )
   {
        Trace("Relative and Short Paths to libraries don't have same handle\n");
            iRetVal = FAIL;
            goto cleanUpThree;
   }


   /* Test Succeeded.
     */
    iRetVal = PASS;

cleanUpThree:

    /* Call the FreeLibrary API. 
     */ 

    if (!FreeLibrary(hRelLib))
    {
        Trace("ERROR:%u: Unable to free library \"%s\"\n", 
              GetLastError(),
              relLibPath);
        iRetVal = FAIL;
    }

cleanUpTwo:

    /* Call the FreeLibrary API. 
     */ 
    if (!FreeLibrary(hFullLib))
    {
        Trace("ERROR:%u: Unable to free library \"%s\"\n", 
              GetLastError(),
              fullPath);
        iRetVal = FAIL;
    }

cleanUpOne:

    /* Call the FreeLibrary API. 
     */ 
    if (!FreeLibrary(hShortLib))
    {
        Trace("ERROR:%u: Unable to free library \"%s\"\n", 
              GetLastError(),
              LibraryName);
        iRetVal = FAIL;
    }


    /* Terminate the PAL.
     */
    PAL_Terminate();
    return iRetVal;

}
Ejemplo n.º 2
0
/*
    FIXME: this is an ugly function!
*/
void ActionRename( cmdline_t *cmd, const char *in, const char *out,
    uint file_num, int make_lib, size_t page_size ) {
/***************************************************/
    char        sp_buf[ _MAX_PATH2 ];
    char        sp_buf2[ _MAX_PATH2 ];
    char        *drive;
    char        *dir;
    char        *fname;
    char        *ext;
    char        buf[ _MAX_PATH ];
    const char  *output;
    act_grp_t   *cur;
    int         rc;

/**/myassert( cmd != NULL );
/**/myassert( cmd->need_output );
/**/myassert( cmd->action != NULL );
/**/myassert( file_num < cmd->action->num_files );
    cur = cmd->action;
    output = cur->output;
    if( output == NULL || output[0] == 0 ) {
        /* get the drive and directory of input file */
        _splitpath2( in, sp_buf, &drive, &dir, NULL, NULL );
        fname = "";
        ext = "";
    } else {
        /* split up the output spec */
        _splitpath2( output, sp_buf, &drive, &dir, &fname, &ext );
    }
    /* If the output spec was like '/o=.mbj' or '/o=f:\tmp\.mbj' then
       we have to use the filename and/or the extension from the input. */
    _splitpath2( cur->files[ file_num ], sp_buf2, NULL, NULL,
        ( fname[0] == 0 ) ? &fname : NULL,      /* get filename from input */
        ( ext[0] == 0 ) ? &ext : NULL );        /* get extension from input */
    if( ext[0] == 0 ) {                 /* use default extension if necessary */
        ext = OBJ_EXTENSION;
    }
    _makepath( buf, drive, dir, fname, ext );
    if( make_lib ) {
        if( cur->batch ) {
            PrtFmt( "wlib %s /b/n/p=%u +%s\n", buf, page_size, out );
            PrtFmt( "del %s\n", out );
        } else {
            char pbuf[ sizeof( size_t ) * 3 ];
            StrDec( pbuf, page_size );
#ifdef _M_I86
            _fheapshrink();
#endif
            _nheapshrink();
            rc = spawnlp(P_WAIT,"wlib","wlib",buf,"/b/n/p=",pbuf,"+",out,NULL);
            if( rc < 0 ) {
                Fatal( MSG_DISK_ERROR, "spawnlp( , \"wlib\", ... )" );
            } else if( rc > 0 ) {
                Fatal( MSG_WLIB_ERROR );
            }
            if( unlink( out ) != 0 ) {
                Fatal( MSG_DISK_ERROR, "unlink" );
            }
        }
    } else if( cur->batch ) {
        PrtFmt( "if exist %s del %s\n", buf, buf );
        PrtFmt( "rename %s %s\n", out, buf );
    } else {
        unlink( buf );          /* delete any file of this name */
        if( rename( out, buf ) != 0 ) {
            Fatal( MSG_DISK_ERROR, "rename" );
        }
    }
}
HRESULT CVidSubtitler::LoadSubtitles(char* Filename, char* SubtitleFile)
{	
	if(!Filename) return S_OK;

	for(int i=0; i<m_Subtitles.GetSize(); i++) delete m_Subtitles[i];
	m_Subtitles.RemoveAll();

	m_LastSample = -1;
	m_CurrentSubtitle = 0;
	m_ShowSubtitle = false;


	char NewFile[MAX_PATH];
	char drive[_MAX_DRIVE];
	char dir[_MAX_DIR];
	char fname[_MAX_FNAME];

	if(SubtitleFile)
	{
		strcpy(NewFile, SubtitleFile);
	}
	else
	{
		_splitpath(Filename, drive, dir, fname, NULL);
		_makepath(NewFile, drive, dir, fname, ".SUB");
	}

	DWORD Size;
	BYTE* Buffer = Game->m_FileManager->ReadWholeFile(NewFile, &Size, false);
	if(Buffer==NULL) return S_OK; // no subtitles


	LONG Start, End;
	bool InToken;
	char* TokenStart;
	int TokenLength;
	int TokenPos;
	int TextLength;

	int Pos = 0;
	int LineLength = 0;
	while(Pos<Size){
		Start = End = -1;
		InToken = false;
		TokenPos = -1;
		TextLength = 0;

		LineLength = 0;
		while(Pos+LineLength < Size && Buffer[Pos+LineLength]!='\n' && Buffer[Pos+LineLength]!='\0') LineLength++;

		int RealLength = LineLength - (Pos+LineLength>=Size?0:1);
		char* Text = new char[RealLength+1];
		char* line = (char*)&Buffer[Pos];

		for(int i=0; i<RealLength; i++){
			if(line[i]=='{'){
				if(!InToken){
					InToken = true;
					TokenStart = line+i+1;
					TokenLength = 0;
					TokenPos++;
				}
				else TokenLength++;
			}
			else if(line[i]=='}'){
				if(InToken){
					InToken = false;
					char* Token = new char[TokenLength+1];
					strncpy(Token, TokenStart, TokenLength);
					Token[TokenLength] = '\0';
					if(TokenPos==0) Start = atoi(Token);
					else if(TokenPos==1) End = atoi(Token);

					delete [] Token;
				}
				else{
					Text[TextLength] = line[i];
					TextLength++;
				}
			}
			else{
				if(InToken){
					TokenLength++;
				}
				else{
					Text[TextLength] = line[i];
					if(Text[TextLength]=='|') Text[TextLength] = '\n';
					TextLength++;
				}
			}
		}
		Text[TextLength] = '\0';

		if(Start!=-1 && TextLength>0 && (Start!=1 || End!=1)) m_Subtitles.Add(new CVidSubtitle(Game, Text, Start, End));

		delete [] Text;

		Pos+=LineLength+1;
	}

	delete [] Buffer;
	return S_OK;
}
Ejemplo n.º 4
0
/*
 * AddDataToEXE - tack data to end of an EXE
 */
void AddDataToEXE( char *exe, char *buffer, unsigned short len, unsigned long tocopy )
{
    int                 h, i, newh;
    char                buff[MAGIC_COOKIE_SIZE + 3];
    long                shift;
    short               taillen;
    char                *copy;
    char                foo[128];
    char                drive[_MAX_DRIVE], dir[_MAX_DIR];

    /*
     * get files
     */
    copy = malloc( COPY_SIZE );
    if( copy == NULL ) {
        Abort( "Out of Memory" );
    }
    h = open( exe, O_RDWR | O_BINARY );
    if( h == -1 ) {
        Abort( "Fatal error opening \"%s\"", exe );
    }
    _splitpath( exe, drive, dir, NULL, NULL );
    _makepath( foo, drive, dir, "__cge__", ".exe" );
    newh = open( foo, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
                 S_IRWXU | S_IRWXG | S_IRWXO );
    if( newh == -1 ) {
        Abort( "Fatal error opening \"%s\"", foo );
    }

    /*
     * get trailer
     */
    i = lseek( h, -((long)MAGIC_COOKIE_SIZE + 3L), SEEK_END );
    if( i == -1 ) {
        Abort( "Initial seek error on \"%s\"", exe );
    }
    i = read( h, buff, 3 + MAGIC_COOKIE_SIZE );
    if( i == -1 ) {
        Abort( "Read error on \"%s\"", exe );
    }

    /*
     * if trailer is one of ours, then set back to overwrite data;
     * else just set to write at end of file
     */
    if( strcmp( buff, magic_cookie ) ) {
        if( sflag ) {
            Abort( "\"%s\" does not contain configuration data!", exe );
        }
    } else {
        taillen = *( (unsigned short *)&(buff[MAGIC_COOKIE_SIZE + 1]) );
        shift = (long)-((long)taillen + (long)MAGIC_COOKIE_SIZE + 3);
        tocopy += shift;
    }
    i = lseek( h, 0, SEEK_SET );
    if( i ) {
        Abort( "Seek error on \"%s\"", exe );
    }

    /*
     * copy crap
     */
    while( tocopy > 0 ) {
        if( tocopy > (unsigned long)COPY_SIZE ) {
            i = read( h, copy, COPY_SIZE );
            if( i != COPY_SIZE ) {
                Abort( "Read error on \"%s\"", exe );
            }
            i = write( newh, copy, COPY_SIZE );
            if( i != COPY_SIZE ) {
                Abort( "Write error on \"%s\"", foo );
            }
            tocopy -= (unsigned long)COPY_SIZE;
        } else {
            i = read( h, copy, (unsigned int)tocopy );
            if( i != tocopy ) {
                Abort( "Read error on \"%s\"", exe );
            }
            i = write( newh, copy, (unsigned int)tocopy );
            if( i != (int)tocopy ) {
                Abort( "Write error on \"%s\"", foo );
            }
            tocopy = 0;
        }
    }
    close( h );

    /*
     * write out data and new trailer
     */
    if( !sflag ) {
        i = write( newh, buffer, len );
        if( i != len ) {
            Abort( "write 1 error on \"%s\"", exe );
        }
        i = write( newh, magic_cookie, MAGIC_COOKIE_SIZE + 1 );
        if( i != MAGIC_COOKIE_SIZE + 1 ) {
            Abort( "write 2 error on \"%s\"", exe );
        }
        i = write( newh, &len, sizeof( short ) );
        if( i != sizeof( short ) ) {
            Abort( "write 3 error on \"%s\"", exe );
        }
    }
    close( newh );
    remove( exe );
    rename( foo, exe );

} /* AddDataToEXE */
Ejemplo n.º 5
0
int main(int argc, char* argv[])
{
    //--- File IO ----
    FILE* inp;
    FILE* outp;
    char inname[500];
    char outname[500];

    /* Runtime statistics */
    double        rate;
    double        rateRCU;
    unsigned long totalbits = 0;
    unsigned long totalBitsRCU = 0;
    unsigned long totalsmpls =0;

    WebRtc_Word32   bottleneck = 39;
    WebRtc_Word16   frameSize = 30;           /* ms */
    WebRtc_Word16   codingMode = 1;
    WebRtc_Word16   shortdata[FRAMESAMPLES_SWB_10ms];
    WebRtc_Word16   decoded[MAX_FRAMESAMPLES_SWB];
    //WebRtc_UWord16  streamdata[1000];
    WebRtc_Word16   speechType[1];
    WebRtc_Word16   payloadLimit;
    WebRtc_Word32   rateLimit;
    ISACStruct*   ISAC_main_inst;

    WebRtc_Word16   stream_len = 0;
    WebRtc_Word16   declen;
    WebRtc_Word16   err;
    WebRtc_Word16   cur_framesmpls;
    int           endfile;
#ifdef WIN32
    double        length_file;
    double        runtime;
    char          outDrive[10];
    char          outPath[500];
    char          outPrefix[500];
    char          outSuffix[500];
    char          bitrateFileName[500];
    FILE*         bitrateFile;
    double        starttime;
    double        rateLB = 0;
    double        rateUB = 0;
#endif
    FILE*         histFile;
    FILE*         averageFile;
    int           sampFreqKHz;
    int           samplesIn10Ms;
    WebRtc_Word16   maxStreamLen = 0;
    char          histFileName[500];
    char          averageFileName[500];
    unsigned int  hist[600];
    unsigned int  tmpSumStreamLen = 0;
    unsigned int  packetCntr = 0;
    unsigned int  lostPacketCntr = 0;
    WebRtc_UWord16  payload[600];
    WebRtc_UWord16  payloadRCU[600];
    WebRtc_UWord16  packetLossPercent = 0;
    WebRtc_Word16   rcuStreamLen = 0;
	int onlyEncode;
	int onlyDecode;


    BottleNeckModel packetData;
	packetData.arrival_time  = 0;
	packetData.sample_count  = 0;
	packetData.rtp_number    = 0;
    memset(hist, 0, sizeof(hist));

    /* handling wrong input arguments in the command line */
    if(argc < 5)
    {
		int size;
		WebRtcIsac_AssignSize(&size);

        printf("\n\nWrong number of arguments or flag values.\n\n");

        printf("Usage:\n\n");
        printf("%s infile outfile -bn bottelneck [options] \n\n", argv[0]);
        printf("with:\n");
        printf("-I................... indicates encoding in instantaneous mode.\n");
        printf("-bn bottleneck....... the value of the bottleneck in bit/sec, e.g. 39742,\n");
		printf("                      in instantaneous (channel-independent) mode.\n\n");
        printf("infile............... Normal speech input file\n\n");
        printf("outfile.............. Speech output file\n\n");
        printf("OPTIONS\n");
        printf("-------\n");
        printf("-fs sampFreq......... sampling frequency of codec 16 or 32 (default) kHz.\n");
        printf("-plim payloadLim..... payload limit in bytes,\n");
        printf("                      default is the maximum possible.\n");
        printf("-rlim rateLim........ rate limit in bits/sec, \n");
        printf("                      default is the maimum possible.\n");
        printf("-h file.............. record histogram and *append* to 'file'.\n");
        printf("-ave file............ record average rate of 3 sec intervales and *append* to 'file'.\n");
        printf("-ploss............... packet-loss percentage.\n");
		printf("-enc................. do only encoding and store the bit-stream\n");
		printf("-dec................. the input file is a bit-stream, decode it.\n");

        printf("\n");
        printf("Example usage:\n\n");
        printf("%s speechIn.pcm speechOut.pcm -B 40000 -fs 32 \n\n", argv[0]);

		printf("structure size %d bytes\n", size);

        exit(0);
    }



    /* Get Bottleneck value */
    bottleneck = readParamInt(argc, argv, "-bn", 50000);
    fprintf(stderr,"\nfixed bottleneck rate of %d bits/s\n\n", bottleneck);

    /* Get Input and Output files */
    sscanf(argv[1], "%s", inname);
    sscanf(argv[2], "%s", outname);
    codingMode = readSwitch(argc, argv, "-I");
    sampFreqKHz = (WebRtc_Word16)readParamInt(argc, argv, "-fs", 32);
    if(readParamString(argc, argv, "-h", histFileName, 500) > 0)
    {
        histFile = fopen(histFileName, "a");
        if(histFile == NULL)
        {
            printf("cannot open hist file %s", histFileName);
            exit(0);
        }
    }
    else
    {
        // NO recording of hitstogram
        histFile = NULL;
    }


    packetLossPercent = readParamInt(argc, argv, "-ploss", 0);

    if(readParamString(argc, argv, "-ave", averageFileName, 500) > 0)
    {
        averageFile = fopen(averageFileName, "a");
        if(averageFile == NULL)
        {
            printf("cannot open file to write rate %s", averageFileName);
            exit(0);
        }
    }
    else
    {
        averageFile = NULL;
    }

	onlyEncode = readSwitch(argc, argv, "-enc");
	onlyDecode = readSwitch(argc, argv, "-dec");


    switch(sampFreqKHz)
    {
    case 16:
        {
            samplesIn10Ms = 160;
            break;
        }
    case 32:
        {
            samplesIn10Ms = 320;
            break;
        }
    default:
        printf("A sampling frequency of %d kHz is not supported,\
valid values are 8 and 16.\n", sampFreqKHz);
        exit(-1);
    }
    payloadLimit = (WebRtc_Word16)readParamInt(argc, argv, "-plim", 400);
    rateLimit = readParamInt(argc, argv, "-rlim", 106800);

    if ((inp = fopen(inname,"rb")) == NULL) {
        printf("  iSAC: Cannot read file %s.\n", inname);
        exit(1);
    }
    if ((outp = fopen(outname,"wb")) == NULL) {
        printf("  iSAC: Cannot write file %s.\n", outname);
        exit(1);
    }

#ifdef WIN32
    _splitpath(outname, outDrive, outPath, outPrefix, outSuffix);
    _makepath(bitrateFileName, outDrive, outPath, "bitrate", ".txt");

    bitrateFile = fopen(bitrateFileName, "a");
    fprintf(bitrateFile, "%  %%s  \n", inname);
#endif

    printf("\n");
    printf("Input.................... %s\n", inname);
    printf("Output................... %s\n", outname);
    printf("Encoding Mode............ %s\n",
        (codingMode == 1)? "Channel-Independent":"Channel-Adaptive");
    printf("Bottleneck............... %d bits/sec\n", bottleneck);
    printf("Packet-loss Percentage... %d\n", packetLossPercent);
    printf("\n");

#ifdef WIN32
    starttime = clock()/(double)CLOCKS_PER_SEC; /* Runtime statistics */
#endif

    /* Initialize the ISAC and BN structs */
    err = WebRtcIsac_Create(&ISAC_main_inst);

    WebRtcIsac_SetEncSampRate(ISAC_main_inst, (sampFreqKHz == 16)? kIsacWideband: kIsacSuperWideband);
    WebRtcIsac_SetDecSampRate(ISAC_main_inst, (sampFreqKHz == 16)? kIsacWideband: kIsacSuperWideband);
    /* Error check */
    if (err < 0) {
        fprintf(stderr,"\n\n Error in create.\n\n");
        exit(EXIT_FAILURE);
    }

    framecnt = 0;
    endfile     = 0;

    /* Initialize encoder and decoder */
    if(WebRtcIsac_EncoderInit(ISAC_main_inst, codingMode) < 0)
    {
        printf("cannot initialize encoder\n");
        return -1;
    }
    if(WebRtcIsac_DecoderInit(ISAC_main_inst) < 0)
    {
        printf("cannot initialize decoder\n");
        return -1;
    }

    //{
    //    WebRtc_Word32 b1, b2;
    //    FILE* fileID = fopen("GetBNTest.txt", "w");
    //    b2 = 32100;
    //    while(b2 <= 52000)
    //    {
    //        WebRtcIsac_Control(ISAC_main_inst, b2, frameSize);
    //        WebRtcIsac_GetUplinkBw(ISAC_main_inst, &b1);
    //        fprintf(fileID, "%5d %5d\n", b2, b1);
    //        b2 += 10;
    //    }
    //}

    if(codingMode == 1)
    {
        if(WebRtcIsac_Control(ISAC_main_inst, bottleneck, frameSize) < 0)
        {
            printf("cannot set bottleneck\n");
            return -1;
        }
    }
    else
    {
        if(WebRtcIsac_ControlBwe(ISAC_main_inst, 15000, 30, 1) < 0)
        {
            printf("cannot configure BWE\n");
            return -1;
        }
    }

    if(WebRtcIsac_SetMaxPayloadSize(ISAC_main_inst, payloadLimit) < 0)
    {
        printf("cannot set maximum payload size %d.\n", payloadLimit);
        return -1;
    }

    if (rateLimit < 106800) {
        if(WebRtcIsac_SetMaxRate(ISAC_main_inst, rateLimit) < 0)
        {
            printf("cannot set the maximum rate %d.\n", rateLimit);
            return -1;
        }
    }

    //=====================================
//#ifdef HAVE_DEBUG_INFO
//    if(setupDebugStruct(&debugInfo) < 0)
//    {
//        exit(1);
//    }
//#endif

    while (endfile == 0)
    {
        fprintf(stderr,"  \rframe = %7li", framecnt);

        //============== Readind from the file and encoding =================
        cur_framesmpls = 0;
        stream_len = 0;


		if(onlyDecode)
		{
			WebRtc_UWord8 auxUW8;
                        size_t auxSizet;
			if(fread(&auxUW8, sizeof(WebRtc_UWord8), 1, inp) < 1)
			{
				break;
			}
			stream_len = ((WebRtc_UWord8)auxUW8) << 8;
			if(fread(&auxUW8, sizeof(WebRtc_UWord8), 1, inp) < 1)
			{
				break;
			}
			stream_len |= (WebRtc_UWord16)auxUW8;
                        auxSizet = (size_t)stream_len;
                        if(fread(payload, 1, auxSizet, inp) < auxSizet)
			{
				printf("last payload is corrupted\n");
				break;
			}
		}
		else
		{
			while(stream_len == 0)
			{
				// Read 10 ms speech block
				endfile = readframe(shortdata, inp, samplesIn10Ms);
				if(endfile)
				{
					break;
				}
				cur_framesmpls += samplesIn10Ms;

				//-------- iSAC encoding ---------
				stream_len = WebRtcIsac_Encode(ISAC_main_inst, shortdata,
					(WebRtc_Word16*)payload);

				if(stream_len < 0)
				{
					// exit if returned with error
					//errType=WebRtcIsac_GetErrorCode(ISAC_main_inst);
					fprintf(stderr,"\nError in encoder\n");
					getchar();
					exit(EXIT_FAILURE);
				}


			}
			//===================================================================
			if(endfile)
			{
				break;
			}

			rcuStreamLen = WebRtcIsac_GetRedPayload(ISAC_main_inst, (WebRtc_Word16*)payloadRCU);

			get_arrival_time(cur_framesmpls, stream_len, bottleneck, &packetData,
				sampFreqKHz * 1000, sampFreqKHz * 1000);
			if(WebRtcIsac_UpdateBwEstimate(ISAC_main_inst,
				payload,  stream_len, packetData.rtp_number,
				packetData.sample_count,
				packetData.arrival_time) < 0)
			{
				printf(" BWE Error at client\n");
				return -1;
			}
		}

        if(endfile)
        {
            break;
        }

        maxStreamLen = (stream_len > maxStreamLen)? stream_len:maxStreamLen;
        packetCntr++;

        hist[stream_len]++;
        if(averageFile != NULL)
        {
            tmpSumStreamLen += stream_len;
            if(packetCntr == 100)
            {
                // kbps
                fprintf(averageFile, "%8.3f ", (double)tmpSumStreamLen * 8.0 / (30.0 * packetCntr));
                packetCntr = 0;
                tmpSumStreamLen = 0;
            }
        }

		if(onlyEncode)
		{
                  WebRtc_UWord8 auxUW8;
                  auxUW8 = (WebRtc_UWord8)(((stream_len & 0x7F00) >> 8) & 0xFF);
                  if (fwrite(&auxUW8, sizeof(WebRtc_UWord8), 1, outp) != 1) {
                    return -1;
                  }

                  auxUW8 = (WebRtc_UWord8)(stream_len & 0xFF);
                  if (fwrite(&auxUW8, sizeof(WebRtc_UWord8), 1, outp) != 1) {
                    return -1;
                  }
                  if (fwrite(payload, 1, stream_len,
                             outp) != (size_t)stream_len) {
                    return -1;
                  }
		}
		else
		{

			//======================= iSAC decoding ===========================

			if((rand() % 100) < packetLossPercent)
			{
				declen = WebRtcIsac_DecodeRcu(ISAC_main_inst, payloadRCU,
					rcuStreamLen, decoded, speechType);
				lostPacketCntr++;
			}
			else
			{
				declen = WebRtcIsac_Decode(ISAC_main_inst, payload,
					stream_len, decoded, speechType);
			}
			if(declen <= 0)
			{
				//errType=WebRtcIsac_GetErrorCode(ISAC_main_inst);
				fprintf(stderr,"\nError in decoder.\n");
				getchar();
				exit(1);
			}

			// Write decoded speech frame to file
                        if (fwrite(decoded, sizeof(WebRtc_Word16),
                                   declen, outp) != (size_t)declen) {
                          return -1;
                        }
			cur_framesmpls = declen;
		}
        // Update Statistics
        framecnt++;
        totalsmpls += cur_framesmpls;
        if(stream_len > 0)
        {
            totalbits += 8 * stream_len;
        }
        if(rcuStreamLen > 0)
        {
            totalBitsRCU += 8 * rcuStreamLen;
        }
    }
Ejemplo n.º 6
0
/*
 * barfScript - write a compiled script
 */
static vi_rc barfScript( char *fn, sfile *sf, vlist *vl, unsigned *ln, char *vn )
{
    sfile       *curr;
    FILE        *foo;
    char        drive[_MAX_DRIVE], directory[_MAX_DIR], name[_MAX_FNAME];
    char        path[FILENAME_MAX];
    char        tmp[MAX_SRC_LINE];
    int         i, k;
    vi_rc       rc;

    /*
     * get compiled file name, and make error file
     */
    if( vn[0] == 0 ) {
        _splitpath( fn, drive, directory, name, NULL );
        _makepath( path, drive, directory, name, "._vi" );
    } else {
        strcpy( path, vn );
    }
    foo = fopen( path, "w" );
    if( foo == NULL ) {
        return( ERR_FILE_OPEN );
    }
    MyFprintf( foo, "VBJ__\n" );
    curr = sf;
    *ln = 1;

    /*
     * process all lines
     */
    for( ;; ) {

        curr = curr->next;
        if( curr == NULL ) {
            break;
        }

        if( curr->data != NULL ) {
            strcpy( tmp, curr->data );
        } else {
            tmp[0] = 0;
        }

        /*
         * expand variables, if requested
         */
        if( EditFlags.CompileAssignments ) {
            /*
             * process the assign command
             */
            if( curr->token == SRC_T_ASSIGN ) {
                rc = SrcAssign( tmp, vl );
                if( rc != ERR_NO_ERR ) {
                    fclose( foo );
                    return( rc );
                }
                if( !EditFlags.CompileAssignments ) {
                    strcpy( tmp, curr->data );
                    EditFlags.CompileAssignments = true;
                } else {
                    continue;
                }
            } else {
                if( curr->token != SRC_T_IF ) {
                    if( curr->hasvar ) {
                        Expand( tmp, vl );
                        curr->hasvar = false;
                        k = strlen( curr->data );
                        for( i = 0; i < k; i++ ) {
                            if( curr->data[i] == '%' ) {
                                curr->hasvar = true;
                                break;
                            }
                        }
                    }
                }
            }
        }

        /*
         * process any additional commands
         */
        switch( curr->token ) {
        /*
         * process the map command
         */
        case PCL_T_MAP + SRC_T_NULL + 1:
        case PCL_T_MAP_DMT + SRC_T_NULL + 1:
            if( curr->token == PCL_T_MAP_DMT + SRC_T_NULL + 1 ) {
                rc = MapKey( MAPFLAG_DAMMIT, tmp );
            } else {
                rc = MapKey( 0, tmp );
            }
            if( rc != ERR_NO_ERR ) {
                fclose( foo );
                return( rc );
            }
            strcpy( tmp, WorkLine->data );
            break;
        }

        /*
         * spew out line
         */
        MyFprintf( foo, "%c%d %s", ( curr->hasvar ) ? '1' : '0', curr->token, tmp );
        if( curr->token == SRC_T_GOTO ) {
            MyFprintf( foo, " %d", curr->branchcond );
        }
        MyFprintf( foo, "\n" );
        *ln += 1;

    }
    fclose( foo );
    return( ERR_NO_ERR );

} /* barfScript */
Ejemplo n.º 7
0
inst_t
disk_install(const char *datfile, const char *descfile,
	     char *fromdir, char *destdir)
{
  char *s;
  char lsmfile[_MAX_PATH];		/* Linux software map file */
  int ret;
  int ch;
  int i;
  int dat_size = 30;			/* malloc size of the dat array */
  int dat_count;			/* size of the dat array */
  dat_t *dat_ary;			/* the DAT array */
  inst_t this;				/* return: no. of errors,warnings */

  /* Initialize variables */

  this.errors = 0;
  this.warnings = 0;

  /* Read dat file */

  dat_ary = malloc (sizeof (dat_t) * dat_size);
  if (dat_ary == NULL)
    {
      fprintf (stderr, "Error!\n");
      fprintf (stderr, "Unable to allocate enough memory for install floppy data file!\n");

      gotoxy (1, 25);
      s = catgets (cat, 1, 0, "Press any key to continue");
      cputs (s);

      getch();
      return (this);
    }

  dat_count = dat_read (datfile, dat_ary, dat_size);
  if (dat_count < 1)
    {
      fprintf (stderr, "Error!\n");
      fprintf (stderr, "The install floppy data file is empty!\n");

      gotoxy (1, 25);
      s = catgets (cat, 1, 0, "Press any key to continue");
      cputs (s);

      getch();
      free (dat_ary);
      return (this);
    }

  /* Run the install */

  for (i = 0; i < dat_count; i++) {
    /* Print the screen and progress bargraph */

    repaint_empty();
    gotoxy (15, 20);
    bargraph (i, dat_count, 50 /* width */);

    /* Print the package name */

    gotoxy (1, 5);
    s = catgets (cat, 3, 3, "Package: ");
    cputs (s);

    cputs (dat_ary[i].name);

    /* Show the package description */

    /* Generate the lsmfile name */

    _makepath (lsmfile, "", fromdir, dat_ary[i].name, "LSM");

    if (isfile (lsmfile))
      {
	lsm_description (8, 1, 10, lsmfile);
      }
    else
      {
	/* no lsm file. try it again with a plain txt file */

	_makepath (lsmfile, "", fromdir, dat_ary[i].name, "TXT");

	if (isfile (lsmfile))
	  {
	    cat_file (lsmfile, 8 /* start line */, 10 /* no. lines */);
	  }
      }

    /* Find out which ones the user wants to install */

    gotoxy (1, 23);
    switch (dat_ary[i].rank) {
    case 'n':
    case 'N':
      /* Do not install */

      s = catgets (cat, 4, 2, "SKIPPED");
      cputs (s);
      break;

    case 'y':
    case 'Y':
      /* Always install */

      s = catgets (cat, 4, 1, "REQUIRED");
      cputs (s);

      ret = unzip_file (dat_ary[i].name, fromdir, destdir);

      if (ret != 0) {
	/* Print an error message */

	s = catgets (cat, 3, 6, "ERROR!  Failed to install REQUIRED package.");
	cputs (s);

	/* Return an error */

	this.errors++;

	/* Does the user want to continue anyway? */

	gotoxy (1, 25);
	s = catgets (cat, 2, 3, "Continue installing this disk? [yn]");
	cputs (s);

	ch = getch_yn();

	if ((ch != 'y') && (ch != 'Y'))
	  {
	    return (this);
	  }
      }
      break;

    default:
      /* Optional */

      s = catgets (cat, 4, 0, "OPTIONAL");
      cputs (s);

      /* Ask the user if you want to install it */

      gotoxy (1, 23);
      s = catgets (cat, 2, 4, "Install this package? [yn]");
      cputs (s);

      ch = getch_yn();

      if ((ch == 'y') || (ch == 'Y'))
	{
	  ret = unzip_file (dat_ary[i].name, fromdir, destdir);

	  if (ret != 0)
	    {
	      /* Print a warning message */

	      gotoxy (1, 23);
	      s = catgets (cat, 3, 7, "WARNING!  Failed to install OPTIONAL package.");
	      cputs (s);

	      gotoxy (1, 25);
	      s = catgets (cat, 1, 0, "Press any key to continue");
	      cputs (s);

	      getch();
	      this.warnings++;
	    }
	}
      break;

    } /* switch */
  } /* for */

  /* Free memory for this disk */

  free (dat_ary);
  return (this);
}
Ejemplo n.º 8
0
/* Функция загрузки материала из файла (*.MTL).
 * АРГУМЕНТЫ:
 *   - имя файла материала:
 *       CHAR *FileName;
 * ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ:
 *   (INT) количество загруженных материалов.
 */
INT AK1_MtlLoad( CHAR *FileName )
{
  FILE *F;
  INT cnt = 0, i, j;
  ak1MATERIAL Mtl = AK1_MtlLib[0];
  static CHAR
    Buf[1000], Name[_MAX_PATH],
    path_buffer[_MAX_PATH],
    drive[_MAX_DRIVE],
    dir[_MAX_DIR],
    fname[_MAX_FNAME],
    ext[_MAX_EXT];

  _splitpath(FileName, drive, dir, fname, ext);

  if ((F = fopen(FileName, "r")) == NULL)
    return 0;

  while (fgets(Buf, sizeof(Buf), F) != NULL)
  {
    /* пропускаем лидирующие пробелы */
    i = 0;
    while (Buf[i] != 0 && isspace(Buf[i]))
      i++;

    /* обрабатываем команды материалов */
    if (strncmp(Buf + i, "Ka", 2) == 0)
      sscanf(Buf + i + 3, "%f %f %f", &Mtl.Ka.X, &Mtl.Ka.Y, &Mtl.Ka.Z);
    else if (strncmp(Buf + i, "Kd", 2) == 0)
      sscanf(Buf + i + 3, "%f %f %f", &Mtl.Kd.X, &Mtl.Kd.Y, &Mtl.Kd.Z);
    else if (strncmp(Buf + i, "Ks", 2) == 0)
      sscanf(Buf + i + 3, "%f %f %f", &Mtl.Ks.X, &Mtl.Ks.Y, &Mtl.Ks.Z);
    else if (strncmp(Buf + i, "Ns", 2) == 0)
      sscanf(Buf + i + 3, "%f", &Mtl.Kp);
    else if (Buf[i] == 'D' || Buf[i] == 'd')
      sscanf(Buf + i + 2, "%f", &Mtl.Kt);
    else if (strncmp(Buf + i, "newmtl", 6) == 0)
    {
      /* выделяем в строку остаток массива Buf */
      j = 0;
      i += 7;
      while (j < sizeof(Name) - 1 && Buf[i] != 0 && Buf[i] != '\n')
        Name[j++] = Buf[i++];
      Name[j] = 0;

      /* добавляем материал */
      if (cnt++ != 0)
        AK1_MtlAdd(&Mtl);
      /* создаем материал */
      Mtl = AK1_MtlLib[0];
      strcpy(Mtl.Name, Name);
    }
    else if (strncmp(Buf + i, "map_Kd", 6) == 0)
    {
      /* выделяем в строку остаток массива Buf */
      j = 0;
      i += 7;
      while (j < sizeof(Name) - 1 && Buf[i] != 0 && Buf[i] != '\n')
        Name[j++] = Buf[i++];
      Name[j] = 0;

      /* загружаем текстуру */
      _makepath(path_buffer, drive, dir, Name, "");
      Mtl.TexId = AK1_TextureLoad(path_buffer);
    }
  }
  /* добавляем материал */
  if (cnt != 0)
    AK1_MtlAdd(&Mtl);
  fclose(F);
  return cnt;
} /* End of 'AK1_MtlLoad' function */
void main(int argc, char* argv[])
{
	bool verbose=false;
	WORD deviceno=0;
	int i;
	
	HCLL_Template clt;
	clt.setOptionPrefix("-");
	clt.addOption("-debug", 0);	// Debug
	clt.addOption("-h", 0);		// Help
	clt.addOption("-v", 0);		// Be verbose
	clt.addOption("-nt", 0);	// Do not print program title
	clt.addOption("-t", 0);	    // Print program title
	clt.addOption("-d", 1);		// Dump banks to batfile
	clt.addOption("-dist", 1);	// Dump banks to batfile (distribution), Use filename only, not full path
	clt.addOption("-distm", 1);	// Dump banks to batfile (distribution), Use filename only, not full path, adds mediaplayer
//	clt.addOption("-bank0", 0);	// Include bank 0 when creating batfile
	clt.addOption("-c", 1);		// Clear one bank
	clt.addOption("-C", 0);		// Clear all banks
//	clt.addOption("-CA", 0);	// Clear all banks, including bank 0 (Default MIDI bank)
	clt.addOption("-n", 1);		// Set device number (for multiple devices)
	clt.addOption("-i", 0);		// Print a lot of info
	clt.addOption("-l", 0);		// List active soundfont names
	clt.addOption("-L", 0);		// List active soundfont names, including path names
	clt.addOption("-fx", 3);	// Load effect <type> <variation> <value>
	clt.addOption("-ea", 0);	// List all Synthesizer emulations
	clt.addOption("-es", 1);	// Set Synthesizer emulation
	clt.addOption("-ec", 0);	// List current Synthesizer emulation
	clt.addOption("-p", 1);		// list preset names for <bank>
	clt.addOption("-wl", 3);	// Load <wavefile> into <preset> in <bank>
	clt.addOption("-wc", 2);	// Clear wavefile loaded in <preset> in <bank>
	clt.addOption("-pl", 5);	// Load <sourcepreset> from <sourcebank> in <soundfont> into <destpreset> in <destbank>
	clt.addOption("-pc", 2);	// Clear <preset> in <bank>
	
	HCLL_CommandLine cl;
	cl.setTemplate(clt);
	HCLL_Result cl_res;
	cl_res=cl.parse(argc, argv);
	if (cl_res!=HCLL_RESULT_OK)
	{
		cout<<"Parse error: ";

		switch (cl_res)
		{
		case HCLL_RESULT_ERROR_TOO_FEW_OPTION_PARAMS :
			cout<<"too few parameters to the '"<<cl.getLastOptionParsed()<<"' option\n";
			break;
		case HCLL_RESULT_ERROR_UNRECOGNIZED_OPTION:
			cout<<"unrecognized option '"<<cl.getLastOptionParsed()<<"'\n";;
			break;
		default:
			cout<<"unknown error\n";
			break;
		};
		printf("SF2LOAD v2.2 (c) 1998-1999 Thomas Hammer  [email protected]\n");
		printf("                 http://listen.to/HammerSound\n");
		printf("\n");
		cout<<"usage:  SF2LOAD  [<options>] [<bank number> <soundfont name>] \n\n";
		cout<<"        SF2LOAD -h for help\n";
		return;
	}

	if (!cl.optionExists("-nt"))
	{
		printf("SF2LOAD v2.2 (c) 1998-1999 Thomas Hammer  [email protected]\n");
		printf("                 http://listen.to/HammerSound\n");
		printf("\n");
	};

	if (cl.optionExists("-v"))
	{
		verbose=true;
		cout <<"Verbose mode on\n";
	}

	if (cl.optionExists("-debug"))
	{
		if (verbose)
			cout<<"debug mode on\n";
		cl.dump();
		cout<<"Path: '"<<argv[0]<<"'"<<endl;
	}

	if (   ((cl.getNumOptions()==0) && (cl.getNumProgParams()==1))
		|| ((cl.getNumProgParams()==2) || (cl.getNumProgParams()>3))
		)
	{
		cout<<"usage:  SF2LOAD  [<option>] [<bank number> <soundfont name>] \n";
		cout<<"        SF2LOAD -h for help\n";
		return;
	}

	if (cl.optionExists("-h")) 
	{
		cout<<"usage:  SF2LOAD  [<option>] [<bank number> <soundfont filename>] \n\n";
		cout<<"-h                Help"<<endl;
		cout<<"-d <filename>     Create a bat-file for loading all soundfonts currently"<<endl;
		cout<<"                  in memory. Use full pathnames."<<endl;
		cout<<"-dist <filename>  Create a bat-file for loading all soundfonts currently"<<endl;
		cout<<"                  in memory. Use filenames only (suitable for distribution)"<<endl;
		cout<<"-distm <filename> Create a bat-file (filename.bat) for loading all soundfonts"<<endl;
		cout<<"                  in memory. Use filenames only and include a line to"<<endl;
		cout<<"                  play the MIDI file (filename.mid) using mediaplayer"<<endl;
//		cout<<"-bank0            Include bank 0 (Default MIDI bank) when creating bat-files"<<endl;
		cout<<"-c <bank>         Clear the specified soundbank (remove it from memory)"<<endl;
		cout<<"-C                Clear all soundbanks currently in memory"<<endl;
//		cout<<"-CA               Clear all soundbanks currently in memory (incl. bank 0)"<<endl;
		cout<<"-n <device>       Set SoundFont device number (for users with multiple devices)"<<endl;
		cout<<"-l                List all soundfonts currently in memory"<<endl;
		cout<<"-L                List all soundfonts currently in memory (with filenames)"<<endl;
		cout<<"-p <bankno>       List all (melodic) presets in bank"<<endl;
		cout<<"-wl <wavefile> <bank> <preset>"<<endl;
		cout<<"                  Load a wavefile (*.wav) into a preset in a bank."<<endl;
		cout<<"-wc <bank> <preset> Clear a waveform previously loaded into a preset in a bank"<<endl;
		cout<<"-pl <soundfont> <sourcebank> <sourcepreset> <destbank> <destpreset>"<<endl;
		cout<<"                  Load a preset from a soundfont into a preset in a bank"<<endl;
		cout<<"-pc <bank> <preset> Clear a preset in a bank"<<endl;
		cout<<"-ea               List all synthesizer emulations"<<endl;
		cout<<"-es <no>          Set synthesizer emulation"<<endl;
		cout<<"-ec               List current synthesizer emulation"<<endl;
		cout<<"-i                Print information about the SoundFont device"<<endl;
		cout<<"-v                Enable verbose mode"<<endl;
		cout<<"-nt               Do not print the program title"<<endl;
		cout<<"-t                Print the program title"<<endl;
		return;
	}


	if (cl.optionExists("-n"))
	{
		deviceno=cl.getOptionParam("-n",0).getInt();
		if (verbose)
			cout<<"deviceno set to "<<deviceno<<endl;
	}

	// Open the SoundFont Manager

	OSC_SFManager sfm;
	OSC_ERR res;

	res = sfm.Init();
	if (res!=OSC_ERR_OK)
	{
		cout<<"Error initializing the SoundFont Manager : "<<sfm.GetLastSFManErrorText()<<endl;
		cout<<"Make sure you have installed the SoundFont Manager, and that you use the latest drivers"<<endl;
		cout<<"for your SoundFont device"<<endl;
		return;
	}
	else
		if (verbose)
			cout<<"SoundFont Manager Initialized OK"<<endl;

	res = sfm.Open(deviceno);
	if (res!=OSC_ERR_OK)
	{
		cout<<"Error trying to open SoundFont device number "<<deviceno
			<<". "<<sfm.GetLastSFManErrorText()<<endl;
		return;
	};

//// -c
	if (cl.optionExists("-c"))
	{
		long bankno = cl.getOptionParam("-c",0).getInt();
		if (verbose)
			cout<<"Clearing SoundBank "<<bankno<<endl;
		if ( (bankno<0) || (bankno>127) )
		{
			cout<<"Error: Bank number out of range. The banknumber specified is "<<bankno<<", it should be in the range [0..127]\n";
		}
		else 
		{
			if (sfm.IsMIDIBankUsed(bankno)==-1)
				cout<<"Error: Bank number "<<bankno<<" is not in use and can not be cleared"<<endl;
			else if (sfm.IsMIDIBankUsed(bankno) != bankno)
				cout<<"Error: Bank number "<<bankno<<" is owned by bank "<<sfm.IsMIDIBankUsed(bankno)
				<<" and can not be cleared"<<endl;
			else
			{
				if ( (res=sfm.ClearLoadedBank(bankno)) != OSC_ERR_OK)
					cout<<"Error: Couldn't clear bank number "<<bankno<<". "<<sfm.GetLastSFManErrorText()<<endl;
				else
					if (verbose)
						cout<<"Bank number "<<bankno<<" has been cleared successfully\n";
			};
		};
	};

//// -es
	if (cl.optionExists("-es"))
	{
		// This function will set the current synthesizer emulation, but this 
		// only lasts until the device is closed (at the end of sf2load)
		// so it's really not much point in using it... :-(
		if (verbose)
			cout<<"Setting current Synthesizer Emulation..."<<endl;
		int index = cl.getOptionParam("-es",0).getInt();
		if ( (res=sfm.SelectSynthEmulation(index)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't set Synthesizer Emulation. "<<sfm.GetLastSFManErrorText()<<endl;
		else
			if (verbose)
				cout<<"Current Synthesizer Emulation has been set to "<<index<<endl;
	}

//// -ea
	if (cl.optionExists("-ea"))
	{
		if (verbose)
			cout<<"Listing all Synthesizer Emulations..."<<endl;
		OSC_StringArray list;
		if ( (res=sfm.GetAllSynthEmulations(list)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't list Synthesizer Emulations. "<<sfm.GetLastSFManErrorText()<<endl;
		else
		{
			int n=0;
			for (OSC_StringArray::iterator i = list.begin(); i!=list.end(); i++)
			{
				cout<<n++<<" "<<*i<<endl;
			}
		};
	}

//// -ec
	if (cl.optionExists("-ec"))
	{
		if (verbose)
			cout<<"Listing current Synthesizer Emulation..."<<endl;
		std::string name;
		int index;
		if ( (res=sfm.GetSynthEmulation(index, name)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't list Synthesizer Emulation. "<<sfm.GetLastSFManErrorText()<<endl;
		else
		{
			cout<<index<<" "<<name<<endl;
		};
	}

//// -wl
	if (cl.optionExists("-wl"))
	{
		std::string filename = cl.getOptionParam("-wl",0).getString();
		int bank = cl.getOptionParam("-wl",1).getInt();
		int preset = cl.getOptionParam("-wl",2).getInt();
		if (verbose)
			cout<<"Loading waveform '"<<filename<<"' into bank "<<bank<<", preset "<<preset<<endl;

		if ( (res=sfm.LoadWaveform(bank, preset, filename)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't load waveform. "<<sfm.GetLastSFManErrorText()<<endl;
	}

//// -wc
	if (cl.optionExists("-wc"))
	{
		int bank = cl.getOptionParam("-wc",0).getInt();
		int preset = cl.getOptionParam("-wc",1).getInt();
		if (verbose)
			cout<<"Clearing waveform from bank "<<bank<<", preset "<<preset<<endl;

		if ( (res=sfm.ClearLoadedWaveform(bank, preset)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't clear waveform. "<<sfm.GetLastSFManErrorText()<<endl;
	}

//// -pl
	if (cl.optionExists("-pl"))
	{
		std::string filename = cl.getOptionParam("-pl",0).getString();
		int sourcebank = cl.getOptionParam("-pl",1).getInt();
		int sourcepreset = cl.getOptionParam("-pl",2).getInt();
		int destbank = cl.getOptionParam("-pl",3).getInt();
		int destpreset = cl.getOptionParam("-pl",4).getInt();
		if (verbose)
			cout<<"Loading from soundfont '"<<filename<<"', bank "<<sourcebank<<", preset "<<sourcepreset
				<<", into bank "<<destbank<<", preset "<<destpreset<<endl;

		if ( (res=sfm.LoadPreset(sourcebank, sourcepreset, destbank, destpreset, filename)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't load preset. "<<sfm.GetLastSFManErrorText()<<endl;
	}

//// -pc
	if (cl.optionExists("-pc"))
	{
		int bank = cl.getOptionParam("-pc",0).getInt();
		int preset = cl.getOptionParam("-pc",1).getInt();
		if (verbose)
			cout<<"Clearing preset from bank "<<bank<<", preset "<<preset<<endl;

		if ( (res=sfm.ClearLoadedPreset(bank, preset)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't clear preset. "<<sfm.GetLastSFManErrorText()<<endl;
	}

//// -C
	if (cl.optionExists("-C"))
	{
		if (verbose)
			cout<<"Clearing all SoundBanks...";
		if ( (res=sfm.ClearAllLoadedBanks()) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't clear banks. "<<sfm.GetLastSFManErrorText()<<endl;
		else
			if (verbose)
				cout<<"All Soundbanks have been cleared successfully\n";
	}

/*
//// -CA
	if (cl.optionExists("-CA"))
	{
		if (verbose)
			cout<<"Clearing all SoundBanks (including bank 0)...";
		if ( (res=sfm.ClearAllLoadedBanks(true)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't clear banks. "<<sfm.GetLastSFManErrorText()<<endl;
		else
			if (verbose)
				cout<<"All Soundbanks have been cleared successfully\n";
	}
*/

//// -l | -L
	if (cl.optionExists("-l") || cl.optionExists("-L"))
	{
		if (verbose)
			cout<<"Listing SoundBanks\n";
		string name;
		string filename;

		for (i=0; i<128; i++)
		{
			if (sfm.IsMIDIBankUsed(i)==i)
			{
				if ( (res=sfm.GetLoadedBankDescriptor(i, name)) != OSC_ERR_OK)
					break;
				else
				{
					cout<<"[";
					if (i<100)
						cout<<" ";
					if (i<10)
						cout<<" ";
					cout<<i<<"] "<<name;
					if (cl.optionExists("-L"))
					{
						if ( (sfm.GetLoadedBankPathname(i, filename)) != OSC_ERR_OK)
							;
						else
							cout<<" ("<<filename<<")";
					}
					cout<<endl;
				};
			}
		};
		if (res!=OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't get bank name (bank "<<i<<"). "<<sfm.GetLastSFManErrorText()<<endl;
	};

//// -i
	if (cl.optionExists("-i"))
	{
		int numdevices = sfm.GetNumDevs();
		if (numdevices==0)
			cout<<"There are no SoundFont devices installed on this computer\n";
		else if (numdevices==1)
			cout<<"There is 1 SoundFont device installed on this computer\n";
		else
			cout<<"There are "<<numdevices<<" SoundFont devices installed on this computer\n";

		CSFCapsObject caps;
		int olddev;
		bool wasOpen = sfm.IsDeviceOpen();
		if (wasOpen)
		{
			olddev = sfm.GetCurrentOpenDevice();
			sfm.Close();
		}

		for (i=0; i<sfm.GetNumDevs(); i++)
		{
			cout<<"   ["<<i<<"] ";
			if (sfm.IsDeviceFree(i))
				cout<<"(free) ";
			else
				cout<<"(busy) ";
			if ( (res=sfm.Open(i)) != OSC_ERR_OK)
			{
				cout<<endl<<"Error: Couldn't open device "<<i<<". "<<sfm.GetLastSFManErrorText()<<endl;
				break;
			}
			if ( (res=sfm.GetDevCaps(&caps)) != OSC_ERR_OK)
			{
				cout<<endl<<"Error: Couldn't get device capabilities. "<<sfm.GetLastSFManErrorText()<<endl;
				break;
			};
			cout <<caps.m_DevName<<endl;
			sfm.Close();
		};

		if (wasOpen)
			if ( (res=sfm.Open(olddev)) != OSC_ERR_OK)
			{
				cout<<endl<<"Error: Couldn't open device "<<i<<". "<<sfm.GetLastSFManErrorText()<<endl;
			}

		if ( (res=sfm.GetDevCaps(&caps)) != OSC_ERR_OK)
			cout<<endl<<"Error: Couldn't get device capabilities. "<<sfm.GetLastSFManErrorText()<<endl;
		else
		{
			cout<<"The following information is for device "<<deviceno<<endl;
			cout<<"   Device name: "<<caps.m_DevName<<"    "
				<<"Device Manager: "<<caps.m_DevMgrName<<" ("<<caps.m_DevMgrEntry<<")"<<endl;

			if (caps.m_DevCaps & SFMANCAP_DYNAMIC_MEM_CAP)
				cout<<"   The device uses System Ram to store samples. ";
			else
				cout<<"   The device uses Dedicated Ram to store samples. ";

			int max, avail;
			sfm.QueryStaticSampleMemorySize(max, avail);
			cout<<std::setiosflags(ios::fixed)<<std::setprecision(1)
				<<"Available: "<<(double)avail/(1024.0*1024.0)<<"MB, "
				<<"Max: "<<(double)max/(1024.0*1024.0)<<"MB"<<endl;

			if (caps.m_DevCaps & SFMANCAP_SOFTWARE_SYNTH_CAP)
				cout<<"   The device has a Software Synth engine"<<endl;
			else
				cout<<"   The device has a Hardware Synth engine"<<endl;

			// rom id, rom version
			// synth emulations
		};
	};


//// -d, -dist, -distm
	// Create bat-file
	if (cl.optionExists("-d") || cl.optionExists("-dist") || cl.optionExists("-distm"))
	{	
		if (verbose)
			cout<<"Bat file creation\n";
		
		FILE *file;
		string batfilename;
		string midifilename;
		if (cl.optionExists("-d"))
			batfilename=cl.getOptionParam("-d",0).getString();
		else if (cl.optionExists("-dist"))
			batfilename=cl.getOptionParam("-dist",0).getString();
		else
			batfilename=cl.getOptionParam("-distm",0).getString();
		midifilename=batfilename;

		char fname[_MAX_FNAME];
		char ext[_MAX_EXT];
		char drive[_MAX_DRIVE];
		char dir[_MAX_DIR];
		char tmp[_MAX_PATH];
		_splitpath(batfilename.c_str(), drive, dir, fname, ext);
		_makepath(tmp, drive, dir, fname, ".bat");
		batfilename=string(tmp);
		_makepath(tmp, drive, dir, fname, ".mid");
		midifilename=string(tmp);


		file=fopen(batfilename.c_str(), "wt");
		if (file==NULL)
		{
			cout<<"Error: Couldn't open file '"<<batfilename.c_str()<<"' for writing";
		}
		else
		{
		
			if (verbose)
			{
				printf("Creating SF2LOAD compatible .bat file (%s) with the folowing soundfonts :\n", batfilename.c_str());
			};

			time_t ltime;
			_tzset();
			char timestr[128];
			time( &ltime );
			sprintf(timestr,"%s", ctime( &ltime ));
			timestr[24]=0;
	//		timestr[23]=0;
	//		if (strlen(timestr)>2)
	//			timestr[strlen(timestr)-3];

			fprintf(file,"@ECHO OFF\n");
			fprintf(file, "REM This bat file was created at %s by SF2LOAD v2.2\n", timestr);
			fprintf(file, "REM      SF2LOAD is (c) 1998-1999 Thomas Hammer  [email protected]\n");
			fprintf(file, "REM                 http://listen.to/HammerSound\n");
			fprintf(file,"\n");
			fprintf(file, "sf2load -t\n");
			fprintf(file,"\n");
			fprintf(file,"ECHO Clearing all User Banks\n");
			if (cl.optionExists("-bank0"))
				fprintf(file, "sf2load -nt -CA\n");
			else
				fprintf(file, "sf2load -nt -C\n");
			fprintf(file,"\n");
			fprintf(file,"ECHO \xff\n");

			// Load soundfonts
			fprintf(file,"ECHO Loading SoundFonts\n");

			string filename;
			int start;
//			start = cl.optionExists("-bank0") ? 0 : 1;
			start = 1;
			for (i=start; i<=127; i++)
			{
				if (sfm.IsMIDIBankUsed(i)==i)
				{
					if ( (res=sfm.GetLoadedBankPathname(i, filename)) != OSC_ERR_OK)
						break;

					if (cl.optionExists("-dist") || cl.optionExists("-distm")) // use filename only
					{
					   char fname[_MAX_FNAME];
					   char ext[_MAX_EXT];
					   _splitpath(filename.c_str(), NULL, NULL, fname, ext);
					   filename=string(fname)+string(ext);
					}
					fprintf(file, "sf2load -nt %3d \"%s\"\n", i, filename.c_str());
				}
				if (verbose)
					cout<<i<<"  "<<filename<<endl;
			};

			if (res==OSC_ERR_OK)
			{
				fprintf(file,"ECHO \xff\n");
				cout<<"Created-bat file '"<<batfilename<<"'"<<endl;

				if (cl.optionExists("-distm")) 
				{
		//			string midifilename=cl.getOptionParam("-distm",1).getString();
					fprintf(file,"ECHO Starting MediaPlayer for playing MIDI file %s\n", midifilename.c_str());
					fprintf(file,"start mplayer.exe %s\n", midifilename.c_str());
					fprintf(file,"ECHO \xff\n");
				};
			}

			fclose(file);
			
			if (res!=OSC_ERR_OK)
			{
				cout<<"Error creating .bat file. "<<sfm.GetLastSFManErrorText()<<endl;
			}
		};
	}

	if (cl.optionExists("-p"))
	{
		// print all preset names for <bank>
		int bank = cl.getOptionParam("-p",0).getInt();
		if (sfm.IsMIDIBankUsed(bank)!=bank)
			cout<<"<empty bank>"<<endl;
		else
		{
			std::string bankname;
			sfm.GetLoadedBankDescriptor(bank, bankname);
	//		cout<<"Melodic Presets for SoundFont: [";
			cout<<bankname<<endl<<endl;

			std::string presetname;
			for (int i=0; i<128; i++)
			{
				sfm.GetLoadedPresetDescriptor(bank, i, presetname);
				if (!presetname.empty())
				{
					cout<<"[";
					if (i<100)
						cout<<" ";
					if (i<10)
						cout<<" ";
					cout<<i<<"] "<<presetname<<endl;
				};
			}
		};
	}

	if (cl.getNumProgParams()==3)
	{
		if (verbose)
			cout<<"Loading SoundFont\n";
		//  we're supposed to load a bank

		// append .sf2 if needed
	   char fname[_MAX_FNAME];
	   char ext[_MAX_EXT];
	   string path=cl.getProgParam(2).getString();
	   _splitpath(path.c_str(), NULL, NULL, fname, ext);
	   if (ext[0]==0)
		   path+=string(".sf2");

		// make full path
		char fullpath[_MAX_PATH];
		if ( _fullpath( fullpath, path.c_str(), _MAX_PATH ) == NULL )
			cout<<"Error: Invalid SoundFont filename '"<<cl.getProgParam(2).getString()<<"'"<<endl;

		// load soundfont
		if ( (res=sfm.LoadBank(cl.getProgParam(1).getInt(), fullpath)) != OSC_ERR_OK)
				cout<<"Error: Couldn't load bank "<<cl.getProgParam(1).getInt()<<". "<<sfm.GetLastSFManErrorText()<<endl;
		else
			printf("[%3d]  %s\n", cl.getProgParam(1).getInt(), fullpath);

	};

	// Close the SoundFont Manager

	if ( (res=sfm.Close()) != OSC_ERR_OK)
		cout<<endl<<"Error: Couldn't close device. "<<sfm.GetLastSFManErrorText()<<endl;
	else
		if (verbose)
			cout<<"Device closed\n";
};
Ejemplo n.º 10
0
void RemoveName(char * str)
{
	_splitpath(str, _drv, _dir, _name, _ext);
	_makepath(str, _drv, _dir, NULL, NULL);
}
Ejemplo n.º 11
0
void CInputTablePage::OnChangeDatabase() 
{
	// TODO: Add your control notification handler code here
	try
	{
		ASSERT (NULL != m_pParams);
		if ((MdbTable == m_pParams -> m_tImportType) || 
			(MdbTableOld == m_pParams -> m_tImportType))
			m_bOpenTyp = TRUE;
		else
			m_bOpenTyp = FALSE;

	//	Datei-Auswahl-Diolog öffnen
		CString strExt, strFilter, strCaption;
		VERIFY (strExt.LoadString (m_bOpenTyp ? IDS_DATABASE_EXTENSION : IDS_FOXPRO_EXTENSION));
		VERIFY (strFilter.LoadString (m_bOpenTyp ? IDS_MDB_FILTER : IDS_FOXPRO_FILTER));
		VERIFY (strCaption.LoadString (IDS_SELECT_DB_CAPTION));

		DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;		// voreingest.
		CFileDialog Dlg (TRUE, strExt, NULL, dwFlags, strFilter, this);

	//	Datenpfad ermitteln
		CString strDataPath (((CGakApp *) AfxGetApp ()) -> DatabaseName ());
		CString strDrive, strDir, strNewPath;
		char *pDrive = strDrive.GetBuffer (_MAX_DRIVE); 
		char *pDir = strDir.GetBuffer (_MAX_DIR);
		char *pNewPath = strNewPath.GetBuffer (_MAX_PATH);
		_splitpath (strDataPath, pDrive, pDir, NULL, NULL);
		_makepath (pNewPath, pDrive, pDir, NULL, NULL);

		Dlg.m_ofn.lpstrInitialDir = pNewPath;	// Pfad setzen
		Dlg.m_ofn.lpstrTitle = strCaption;
		if (IDOK != Dlg.DoModal ())
			AfxThrowUserException ();			// alles bleibt beim alten

	//	alten Set ggf. schließen
		if (m_pParams -> m_SourceSet.IsOpen ())
			m_pParams -> m_SourceSet.Close ();
		if (m_pParams -> m_SourceDatabase.IsOpen ())
			m_pParams -> m_SourceDatabase.Close ();

	//	alten Infos löschen
		m_lbTables.ResetContent ();
		m_edDatabase.SetWindowText ("");

	//	Database öffnen
		if (m_bOpenTyp)	// MDB-Datei
		{
			m_pParams -> m_SourceDatabase.Open (Dlg.GetPathName ());
												// FALSE,	/* nicht exclusiv */
												// TRUE);	/* read only */
			SetTableInfo (m_pParams -> m_tImportType, m_pParams -> m_tTableType);
		}
		else		// FOXPRO
		{
			CString strConnect;
			VERIFY (strConnect.LoadString (IDS_FOXPRO_CONNECT));
			_splitpath (Dlg.GetPathName (), pDrive, pDir, NULL, NULL);
			_makepath (pNewPath, pDrive, pDir, NULL, NULL);
			m_pParams -> m_SourceDatabase.Open (pNewPath, 
												FALSE,	/* nicht exclusiv */
												TRUE,	/* read only */
												_T(strConnect));	
			SetTableInfo (m_pParams -> m_tImportType, m_pParams -> m_tTableType);
		}

	//	Tabellen ausgeben
		int iCnt = m_pParams -> m_SourceDatabase.GetTableDefCount();
		CDaoTableDefInfo Info;
		for (short iIndex = 0; iIndex < iCnt; iIndex++)
		{
		//	primary info
			m_pParams -> m_SourceDatabase.GetTableDefInfo (iIndex, Info);	
			if (Info.m_lAttributes & dbSystemObject)	// keine
				continue;								// Systemtabellen

			if (m_lbTables.AddString (Info.m_strName) < 0)
				AfxThrowMemoryException ();
		}

	//	bei FOXPRO gleich Set öffnen
		if (!m_bOpenTyp)
		{
			m_pParams -> m_SourceSet.m_pDatabase = &m_pParams -> m_SourceDatabase;
			CString strSQL, strFileName;
			char *pFileName = strFileName.GetBuffer (_MAX_FNAME);
			_splitpath (Dlg.GetFileName (), NULL, NULL, pFileName, NULL);			
			AfxFormatString1 (strSQL, IDS_SELECT_ALL, pFileName);
			m_pParams -> m_SourceSet.Open (dbOpenSnapshot, strSQL, dbReadOnly);
			m_pParams -> m_strInputTableName = pFileName;
			m_lbTables.SelectString (-1, pFileName);
		}
		
	//	Name der Datenbank ausgeben
		m_edDatabase.SetWindowText (m_bOpenTyp ? Dlg.GetPathName () : pNewPath);
	}
	catch (CUserException *ue)
	{
		ue -> Delete ();		// hier Abbruch
	}
	catch (CException *e)
	{
		if (e -> IsKindOf (RUNTIME_CLASS (CDaoException)))
			:: DisplayDaoException ((CDaoException *) e);
		else
			e -> ReportError ();
		e -> Delete ();

		if (m_pParams -> m_SourceDatabase.IsOpen ())
			m_pParams -> m_SourceDatabase.Close ();
	}

	SetWizardButton ();	
}
Ejemplo n.º 12
0
void AddToName(char * str, char * cat)
{
	_splitpath(str, _drv, _dir, _name, _ext);
	strcat(_name, cat);
	_makepath(str, _drv, _dir, _name, _ext);
}
Ejemplo n.º 13
0
void SetExt(char * str, char * new_ext)
{
	_splitpath(str, _drv, _dir, _name, _ext);
	_makepath(str, _drv, _dir, _name, new_ext);
}
Ejemplo n.º 14
0
static void set_out_file( void )
{
    char        cmd_outfile[_MAX_PATH2];
    char    *   cmd_drive;
    char    *   cmd_dir;
    char    *   cmd_ext;
    char    *   cmd_fname;
    char        dev_outfile[_MAX_PATH2];
    char    *   dev_drive;
    char    *   dev_dir;
    char    *   dev_ext;
    char    *   dev_fname;
    char        doc_spec[_MAX_PATH2];
    char    *   doc_drive;
    char    *   doc_dir;
    char    *   doc_ext;
    char    *   doc_fname;
    char        temp_outfile[_MAX_PATH];

    /* Split the possible source names into their component parts. */

    if( master_fname == NULL ) {
        doc_spec[0] = '\0';
        doc_drive = &doc_spec[0];
        doc_spec[1] = '\0';
        doc_dir = &doc_spec[1];
        doc_spec[2] = '\0';
        doc_fname = &doc_spec[2];
        doc_spec[3] = '\0';
        doc_ext = &doc_spec[3];
    } else {
        _splitpath2( master_fname, doc_spec, &doc_drive, &doc_dir, &doc_fname, &doc_ext );
    }

    if( out_file == NULL ) {
        cmd_outfile[0] = '\0';
        cmd_drive = &cmd_outfile[0];
        cmd_outfile[1] = '\0';
        cmd_dir = &cmd_outfile[1];
        cmd_outfile[2] = '\0';
        cmd_fname = &cmd_outfile[2];
        cmd_outfile[3] = '\0';
        cmd_ext = &cmd_outfile[3];
    } else {
        _splitpath2( out_file, cmd_outfile, &cmd_drive, &cmd_dir, &cmd_fname, &cmd_ext );
    }

    if( bin_device->output_name == NULL ) {
        dev_outfile[0] = '\0';
        dev_drive = &dev_outfile[0];
        dev_outfile[1] = '\0';
        dev_dir = &dev_outfile[1];
        dev_outfile[2] = '\0';
        dev_fname = &dev_outfile[2];
        dev_outfile[3] = '\0';
        dev_ext = &dev_outfile[3];
    } else {
        _splitpath2( bin_device->output_name, dev_outfile, &dev_drive, &dev_dir,
                     &dev_fname, &dev_ext );
    }

    /* Ensure it is possible to tell if a file name was constructed. */

    temp_outfile[0] = '\0';

    /* Construct the file name, if necessary. If the command-line option OUTput
     * was used and both a filename and and extension were given, then cmd_fname
     * will be used as-is and temp_outfile will not be touched.
     */

    if( *cmd_fname != '\0' ) {
        if( *cmd_fname != '*' ) {
            if( *cmd_ext != '\0' ) {

            /* If both name and extension were given on the command line, use
             * out_file as-is.
             */

            } else {

            /* If the name was given on the command line, use out_file with the
             * extension given in the :DEVICE block.
             */

                _makepath( temp_outfile, cmd_drive, cmd_dir, cmd_fname,
                           bin_device->output_extension );
            }
        } else {
            if( *cmd_ext != '\0' ) {

            /* If the name was not given but an extension was given on the command
             * line, use the document specification name with the extension given.
             */

                _makepath( temp_outfile, cmd_drive, cmd_dir, doc_fname, cmd_ext );
            } else {

            /* If neither a specific name nor an extension was given on the
             * command line, use use the document specification name with the
             * extension given in the :DEVICE block.
             */

                _makepath( temp_outfile, cmd_drive, cmd_dir, doc_fname,
                           bin_device->output_extension );
            }
        }
    } else {
        if( (*cmd_drive != '\0') || (*cmd_dir != '\0') ) {

            /* Command line OPTION was used with something like "c:" or "..\" but
             * with no filename or extension.
             */

                _makepath( temp_outfile, cmd_drive, cmd_dir, doc_fname,
                           bin_device->output_extension );
        } else {

            /* The situation here is that command-line option OUTPUT was not
             * used with only a drive letter and/or a path but with no file name,
             * not even "*", and no extension. In other words, it was not used
             * at all.
             */

            if( (*dev_fname != '*') && (*dev_fname != '\0') ) {

                /* If the :DEVICE block specified a file name then use the file
                 * name and any extension provided.
                 */

                _makepath( temp_outfile, "", "", bin_device->output_name,
                           bin_device->output_extension );
            } else {

                /* If the :DEVICE block did not specify a file name then use the
                 * document specification name with any extension provided.
                 */

                _makepath( temp_outfile, dev_drive, dev_dir, doc_fname,
                           bin_device->output_extension );
            }
        }
    }

    /* If a file name was constructed, update out_file with it. */

    if( temp_outfile[0] != '\0' ) {
        if( out_file != NULL ) mem_free( out_file );
        out_file = mem_alloc( strnlen_s( temp_outfile, _MAX_PATH ) + 1 );
        strcpy_s( out_file, _MAX_PATH, temp_outfile );
    }

    return;
}
Ejemplo n.º 15
0
/*
 * processFileName - process a new file name
 */
static process_rc processFileName( gui_window *gui )
{
    char        *tmp;
    char        *txt;
    size_t      len;
    char        path[_MAX_PATH];
    char        dir[_MAX_DIR];
    char        drive[_MAX_DRIVE];
    char        fname[_MAX_PATH];
    char        ext[_MAX_PATH];
    char        *buff;
    bool        has_wild;
    struct stat buf;
    int         rc;
    dlg_info            *dlg = GUIGetExtra( gui );

    tmp = GUIGetText( gui, CTL_EDIT );
    if( tmp == NULL ) {
        return( PROCESS_FALSE );
    }
    txt = alloca( strlen( tmp ) + 1 );
    if( txt == NULL ) {
        GUIMemFree( tmp );
        return( PROCESS_FALSE );
    }
    strcpy( txt, tmp );
    GUIMemFree( tmp );
    splitPath( txt, drive, dir, fname, ext );

    has_wild = hasWild( txt );
    if( has_wild && fname[0] == 0 ) {
        return( PROCESS_FALSE );
    }

    if( !has_wild ) {

        rc = stat( txt, &buf );
        if( !rc ) {
            if( S_ISDIR( buf.st_mode ) ) {
                goToDir( gui, txt );
                if( !initDialog( gui, dlg->fileExtensions[dlg->currExtIndex], NULL ) ) {
                    return( PROCESS_FAIL );
                }
                return( PROCESS_FALSE );
            }
        }
        _makepath( path, drive, dir, NULL, NULL );
        if( !goToDir( gui, path ) ) {
            return( PROCESS_FALSE );
        }
        if( !rc && (dlg->currOFN->flags & OFN_OVERWRITEPROMPT) ) {
            buff = alloca( strlen( txt ) + 100 );
            strcpy( buff, txt );
            strcat( buff, LIT( File_Exists_Replace ) );
            rc = GUIDisplayMessage( gui, buff, dlg->currOFN->title, GUI_YES_NO );
            if( rc == GUI_RET_NO ) {
                return( PROCESS_FALSE );
            }
        }
        _makepath( path, NULL, NULL, fname, ext );

        if( dlg->currOFN->base_file_name != NULL ) {
            len = strlen( txt );
            if( len >= dlg->currOFN->max_base_file_name ) {
                len = dlg->currOFN->max_base_file_name - 1;
            }
            memcpy( dlg->currOFN->base_file_name, txt, len );
            dlg->currOFN->base_file_name[len] = 0;
        }
        if( dlg->currOFN->file_name != NULL ) {
            getcwd( path, sizeof( path ) );
            len = strlen( path );
            if( path[len - 1] != FILE_SEP_CHAR ) {
                path[len] = FILE_SEP_CHAR;
                path[len + 1] = 0;
            }
            strcat( path, fname );
            strcat( path, ext );
            len = strlen( path );
            if( len >= dlg->currOFN->max_file_name ) {
                len = dlg->currOFN->max_file_name-1;
            }
            memcpy( dlg->currOFN->file_name, path, len );
            dlg->currOFN->file_name[len] = 0;
        }
        return( PROCESS_TRUE );
    }
    _makepath( path, drive, dir, NULL, NULL );
    if( !goToDir( gui, path ) ) {
        return( PROCESS_FALSE );
    }
    _makepath( path, NULL, NULL, fname, ext );
    if( !initDialog( gui, path, NULL ) ) {
        return( PROCESS_FAIL );
    }
    return( PROCESS_FALSE );

} /* processFileName */
Ejemplo n.º 16
0
STDMETHODIMP CLXWebSiteApp::SetSite(ILXAddinSite* pSite)
{
	m_spAddinSite = pSite;

	{
		TCHAR appdata[MAX_PATH];
		SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, appdata);

		TCHAR pathname[MAX_PATH];
		_makepath(pathname, NULL, appdata, "LXFramework", NULL);

		TCHAR filename[MAX_PATH];
		_makepath(filename, NULL, pathname, "servers.xml", NULL);

		CComPtr<ILDOMDocument> xmldocument;
		if (SUCCEEDED(xmldocument.CoCreateInstance(CLSID_LDOMDocument)))
		{
			VARIANT_BOOL success;
			xmldocument->load(A2BSTR(filename), &success);

			CComPtr<ILDOMElement> documentElement;
			xmldocument->get_documentElement(&documentElement);
			if (documentElement)
			{
				CComPtr<ILDOMNode> node;
				documentElement->get_firstChild(&node);
				while (node)
				{
					CComQIPtr<ILDOMElement> element = node;
					if (element)
					{
						CComBSTR tagName;
						element->get_tagName(&tagName);
						if (!wcscmp(tagName, L"server"))
						{
							CComObject<CServer>* pServer;
							CComObject<CServer>::CreateInstance(&pServer);
							pServer->AddRef();

							element->getAttribute(L"name", &pServer->m_name);
							element->getAttribute(L"serverName", &pServer->m_serverName);
							element->getAttribute(L"directory", &pServer->m_directory);
							element->getAttribute(L"userName", &pServer->m_userName);
							element->getAttribute(L"password", &pServer->m_password);

							m_servers.Add(pServer);
						}
					}
					CComPtr<ILDOMNode> nextSibling;
					node->get_nextSibling(&nextSibling);
					node = nextSibling;
				}
			}
		}
	}

	if (m_spAddinSite)
	{
		CComPtr<ILXFrameworkFrame> lxframe;
		m_spAddinSite->GetFrame(&lxframe);

		CComQIPtr<IUIFrame> frame = lxframe;

		CComPtr<IUIManager> uiManager;
		m_spAddinSite->GetUIManager((IUnknown**)&uiManager);

		{
			CComPtr<IUIMenuDlg> menuDlg;
			uiManager->CreateMenuDlg(&menuDlg);

			CComPtr<IMenuItem> menuItem;
			uiManager->FindMenu(_Module.GetResourceInstance(), IDR_MAINFRAME, &menuItem);

			CComPtr<IMenuItem> menuItem0 = menuItem;
			//menuItem->GetSubMenu(0, &menuItem0);

			menuDlg->InitMenu(menuItem0, this/*CComQIPtr<ICommandTarget>(GetFrame())*/, -1);

			CComPtr<IUIDlgSite> dlgsite;
			uiManager->CreateDlgSite(L"MenuBar", NULL, menuDlg, &dlgsite);

			frame->FloatControlBar(dlgsite, CPoint(0,0), CBRS_SIZE_DYNAMIC);
		}
#if 0
		{
			CComPtr<IUIRegisteredDlg> rdlg;
			uiManager->RegisterDlg(70/*TODO?IDR_MAINFRAME*/, L"Menubar", 0, &rdlg);

			CComPtr<IUIDlg> dlg;
			rdlg->CreateDlg(&dlg);

			CComPtr<IUIDlgSite> dlgsite;
			uiManager->CreateDlgSite(dlg, &dlgsite);

			frame->FloatControlBar(dlgsite, CPoint(0,0), CBRS_SIZE_DYNAMIC);
		}
#endif
	}

	return S_OK;
}
void	TargetNode::Wildcards()
{
	TargetNode	*pTarget, *pTargetFile;
	if ( GetType() == TARGET_PROJECT )
		{
		GetNodeC()->Wildcards();
		GetNodeH()->Wildcards();
		pTarget = GetFirstChildPRJ();
		while ( pTarget )
			{
			 pTarget->Wildcards();
			 pTarget= pTarget->GetNext();
			}
		}
	else if ( GetType() == NODE_FILE_C || GetType() == NODE_FILE_H )
		{
		 char		szDrive						[_MAX_DRIVE	+1],	szFoundDrive[_MAX_DRIVE	+1];
		 char		szDir							[_MAX_DIR		+1],	szFoundDir	[_MAX_DIR		+1];
		 char		szFname						[_MAX_PATH	+1],	szFoundFname[_MAX_PATH	+1];
		 char		szExt							[_MAX_EXT		+1],	szFoundExt	[_MAX_EXT		+1];
		 char		szWildcardsPath		[_MAX_PATH	+1],	szFoundFile	[_MAX_DIR		+1];
		 char		szEmpty[] = "";

		 WIN32_FIND_DATA	FileFindData;

		 SetAllWorkFlagsToTrue();
		 while ( TRUE )
			{
			 pTargetFile = GetFirstChildTarget();
			 while ( pTargetFile )
			 {
				if ( pTargetFile-> GetWorkFlag() )
					{
					 _splitpath( pTargetFile->GetFileName(), szDrive, szDir, szFname, szExt );
					 if ( szFname[0] != '*' )
							break;
					}
				pTargetFile= pTargetFile->GetNext();
			 }
			 if ( pTargetFile == NULL )
				 break;

			 pTargetFile->SetWorkFlagToFalse();
			 _splitpath( pTargetFile->GetFilePath(), szFoundDrive, szFoundDir, szFoundFname, szFoundExt );
			 strcpy( szFoundFname, "*" );
			 _makepath( szWildcardsPath, szFoundDrive, szFoundDir, szFoundFname, szFoundExt );

			 int		nMatchedFiles=0, nNoMatchedFiles = 0;
			 HANDLE hFindFile = FindFirstFile( szWildcardsPath, &FileFindData );
			 if ( hFindFile != INVALID_HANDLE_VALUE )
			 do
			 	{
					 _makepath( szFoundFile, szFoundDrive, szFoundDir, FileFindData.cFileName, szEmpty );
					 pTarget = GetFirstChildTarget();
					 while ( pTarget )
					 {
						 if ( stricmp( pTarget->GetFilePath(), szFoundFile ) == 0 )
								break;
						 pTarget= pTarget->GetNext();
					 }
					 if ( pTarget )
						{
						 nMatchedFiles++;
						 pTarget->SetWorkFlagToFalse();
						}
					 else
						 nNoMatchedFiles++;
				}
			 while ( FindNextFile( hFindFile, &FileFindData ) );

			 if ( nMatchedFiles && (nNoMatchedFiles==0 || (nNoMatchedFiles*100)/nMatchedFiles<=50) )
				{
				 hFindFile = FindFirstFile( szWildcardsPath, &FileFindData );
				 do
					{
					 _makepath( szFoundFile, szFoundDrive, szFoundDir, FileFindData.cFileName, szEmpty );
					 pTarget = GetFirstChildTarget();
					 while ( pTarget )
					 {
						 if ( stricmp( pTarget->GetFilePath(), szFoundFile ) == 0 )
								break;
						 pTarget= pTarget->GetNext();
					 }
					 if ( pTarget )
							pTarget->SetDeleteFlag();
					 else	// szFoundFile is not matched to project's files, insert new one
						{
						 char*		pszPath = GetParentPRJ()->GetFilePath();
						 int			nPathLen = strlen( pszPath );

						 pTargetFile = new TargetNode (szFoundFile, this, GetFirstChildTarget()->GetType());
						 if ( strstr( pTargetFile->GetFilePath(), pszPath) )
							 pTargetFile->SetFileName( pTargetFile->GetFilePath() + nPathLen);
						 else
							 pTargetFile->SetFileName( pTargetFile->GetFilePath() );
						 pTargetFile->SetExclusionFlag();
						 pTargetFile->SetWorkFlagToFalse();
						}
					}
					while ( FindNextFile( hFindFile, &FileFindData ) );

					// ----------------- delete matched files
					pTargetFile = GetFirstChildTarget();
					BOOL	bFirstFlag = TRUE;
					while ( pTargetFile )
					{
						pTarget = pTargetFile->GetNext();
						if ( pTargetFile-> GetDeleteFlag() )
							{
							 if ( bFirstFlag )
							 {
								 _splitpath( pTargetFile->GetFileName(), szDrive, szDir, szFname, szExt );
								 strcpy( szFname, "*" );
								 _makepath( pTargetFile->GetFileName(), szDrive, szDir, szFname, szExt );
								 _splitpath( pTargetFile->GetFilePath(), szDrive, szDir, szFname, szExt );
								 strcpy( szFname, "*" );
								 _makepath( pTargetFile->GetFilePath(), szDrive, szDir, szFname, szExt );
								 bFirstFlag = FALSE;
							 }
							 else
								 delete pTargetFile;
							}
						pTargetFile= pTarget;
					}

				}	// if ( bFindAllFilesFlag )
			}	// while (TRUE )
	}	// else if ( GetType() == NODE_FILE_C || GetType() == NODE_FILE_H )
}
Ejemplo n.º 18
0
LRESULT CLXWebSiteApp::OnFileServers(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	CComPtr<ILXFrameworkFrame> lxframe;
	m_spAddinSite->GetFrame(&lxframe);

	CComQIPtr<IUIWnd> wnd = lxframe;
	HWND hWnd;
	wnd->get_hwnd(&hWnd);

	CServersDlg dlg;

	for (int i = 0; i < m_servers.GetSize(); i++)
	{
		CComObject<CServer>* pServer;
		CComObject<CServer>::CreateInstance(&pServer);
		pServer->AddRef();

		*pServer = *m_servers[i];
		dlg.m_servers.Add(pServer);
	}

	if (dlg.DoModal() == IDOK)
	{
		int i;
		for (i = 0; i < m_servers.GetSize(); i++)
		{
			m_servers[i]->Release();
		}
		m_servers.RemoveAll();

		for (i = 0; i < dlg.m_servers.GetSize(); i++)
		{
			CComObject<CServer>* pServer;
			CComObject<CServer>::CreateInstance(&pServer);
			pServer->AddRef();

			*pServer = *dlg.m_servers[i];
			m_servers.Add(pServer);
		}

		TCHAR appdata[MAX_PATH];
		SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, appdata);

		TCHAR pathname[MAX_PATH];
		_makepath(pathname, NULL, appdata, "LXFramework", NULL);

		_mkdir(pathname);

		TCHAR filename[MAX_PATH];
		_makepath(filename, NULL, pathname, "servers.xml", NULL);

		CComPtr<ILDOMDocument> xmldocument;
		if (SUCCEEDED(xmldocument.CoCreateInstance(CLSID_LDOMDocument)))
		{
			VARIANT_BOOL success;
			xmldocument->loadXML(L"<servers/>", &success);
			if (success)
			{
				CComPtr<ILDOMElement> documentElement;
				xmldocument->get_documentElement(&documentElement);

				for (int i = 0; i < m_servers.GetSize(); i++)
				{
					CServer* pServer = m_servers[i];

					CComPtr<ILDOMElement> element;
					xmldocument->createElement(L"server", &element);
					if (element)
					{
						element->setAttribute(L"name", pServer->m_name);
						element->setAttribute(L"serverName", pServer->m_serverName);
						element->setAttribute(L"userName", pServer->m_userName);
						element->setAttribute(L"password", pServer->m_password);
						element->setAttribute(L"directory", pServer->m_directory);

						documentElement->appendChild(element, NULL);
					}
				}

				xmldocument->save(A2BSTR(filename), &success);
				if (success)
				{
					return 0;
				}
			}
		}

		MessageBox(hWnd, "Failed to save servers configuration", "LXWebSite", MB_OK);
	}

	return 0;
}
Ejemplo n.º 19
0
static void makepath( char* path, const char* drive, const char* dir, const char* fname, const char* ext )
{
    path[2] = '\0';     //avoid bug in _makepath
    _makepath( path, drive, dir, fname, ext );
}
Ejemplo n.º 20
0
LPCSTR PlugSetPath(LPSTR pBuff, LPCSTR prefix, LPCSTR FileName, LPCSTR defpath)
  {
  char newname[_MAX_PATH];
  char direc[_MAX_DIR], defdir[_MAX_DIR], tmpdir[_MAX_DIR];
  char fname[_MAX_FNAME];
  char ftype[_MAX_EXT];
#if defined(__WIN__)
  char drive[_MAX_DRIVE], defdrv[_MAX_DRIVE];
#else
  char *drive = NULL, *defdrv = NULL;
#endif

  if (!strncmp(FileName, "//", 2) || !strncmp(FileName, "\\\\", 2)) {
    strcpy(pBuff, FileName);       // Remote file
    return pBuff;
    } // endif

  if (PlugIsAbsolutePath(FileName))
  {
    strcpy(pBuff, FileName); // FileName includes absolute path
    return pBuff;
  } // endif
  
#if !defined(__WIN__)
  if (*FileName == '~') {
    if (_fullpath(pBuff, FileName, _MAX_PATH)) {
      if (trace > 1)
        htrc("pbuff='%s'\n", pBuff);

     return pBuff;
    } else
      return FileName;     // Error, return unchanged name
      
    } // endif FileName  
#endif   // !__WIN__
  
  if (prefix && strcmp(prefix, ".") && !PlugIsAbsolutePath(defpath))
  {
    char tmp[_MAX_PATH];
    int len= snprintf(tmp, sizeof(tmp) - 1, "%s%s%s",
                      prefix, defpath, FileName);
    memcpy(pBuff, tmp, (size_t) len);
    pBuff[len]= '\0';
    return pBuff;
  }

  _splitpath(FileName, drive, direc, fname, ftype);

  if (defpath) {
    char c = defpath[strlen(defpath) - 1];

    strcpy(tmpdir, defpath);

    if (c != '/' && c != '\\')
      strcat(tmpdir, "/");

  } else
    strcpy(tmpdir, "./");

  _splitpath(tmpdir, defdrv, defdir, NULL, NULL);

  if (trace > 1) {
    htrc("after _splitpath: FileName=%s\n", FileName);
#if defined(__WIN__)
    htrc("drive=%s dir=%s fname=%s ext=%s\n", drive, direc, fname, ftype);
    htrc("defdrv=%s defdir=%s\n", defdrv, defdir);
#else
    htrc("dir=%s fname=%s ext=%s\n", direc, fname, ftype);
#endif
    } // endif trace

  if (drive && !*drive)
    strcpy(drive, defdrv);

  switch (*direc) {
    case '\0':
      strcpy(direc, defdir);
      break;
    case '\\':
    case '/':
      break;
    default:
      // This supposes that defdir ends with a SLASH
      strcpy(direc, strcat(defdir, direc));
    } // endswitch

  _makepath(newname, drive, direc, fname, ftype);

  if (trace > 1)
    htrc("newname='%s'\n", newname);

  if (_fullpath(pBuff, newname, _MAX_PATH)) {
    if (trace > 1)
      htrc("pbuff='%s'\n", pBuff);

    return pBuff;
  } else
    return FileName;     // Error, return unchanged name

  } // end of PlugSetPath
Ejemplo n.º 21
0
inst_t
set_install (const char *diskset, char *fromdir, char *destdir)
{
  /* Variables */

  char *s;
  char endfile[_MAX_PATH];		/* marks end of series */
  char descfile[_MAX_PATH];		/* description file */
  char datfile[_MAX_PATH];		/* current DAT file */
  char ext[_MAX_EXT];			/* file extension */
  int disknum = 0;			/* current disk number */
  int ch;
  inst_t ret;				/* return: no. of errors,warnings */
  inst_t this;				/* no. of errors,warnings */

  /* Create the filenames */

  /* usage is _makepath(newpath, drive, dir, name, ext) */

  _makepath (endfile, "", fromdir, diskset, "END");
  _makepath (descfile, "", fromdir, diskset, "TXT");

  /* Print the name of the series we are working on */

  repaint_empty();
  gotoxy (1, 3);
  s = catgets (cat, 3, 2, "Installing series: ");
  cputs (s);
  gotoxy (1, 4);
  cputs (diskset);

  /* Install while we have disks to work from.  Since we will reach an
     exit condition within the loop, we use an infinite loop here. */

  ret.errors = 0;
  ret.warnings = 0;

  while (1) {
    /* Set the DAT file name */

    sprintf (ext, "%d", ++disknum);
    _makepath (datfile, "", fromdir, diskset, ext);

    /* Load the first disk */

    repaint_empty();

    /* First check that the datfile exists.  If it doesn't, check if
       the endfile was found. */

    if (!isfile (datfile)) {
      /* Does the endfile exist? */

      if (isfile (endfile)) {
	gotoxy (1, 10);
	s = catgets (cat, 3, 5, "Done installing this disk series.");
	cputs (s);

	gotoxy (1, 15);
	s = catgets (cat, 3, 10, "If you are installing other disk series, please insert");
	cputs (s);

	gotoxy (1, 16);
	s = catgets (cat, 3, 11, "disk #1 of the next series in the drive now.");
	cputs (s);

	gotoxy (1, 25);
	s = catgets (cat, 1, 0, "Press any key to continue");
	cputs (s);

	getch();
	return (ret);
      }

      /* The endfile was not found, so we know there is at least one
         more disk left to do.  Keep asking the user to insert the
         next disk. */

      do {
	gotoxy (1, 10);
	s = catgets (cat, 3, 4, "Can't find data file for this install disk!");
	cputs (s);

	gotoxy (1, 11);
	cputs (datfile);

	gotoxy (1, 15);
	s = catgets (cat, 3, 8, "You may not have the right install floppy in the drive.");
	cputs (s);

	gotoxy (1, 16);
	s = catgets (cat, 3, 9, "Double check that you have the right disk and try again.");
	cputs (s);

	gotoxy (1, 25);
	s = catgets (cat, 2, 3, "Continue installing this disk? [yn]");
	cputs (s);

	ch = getch_yn();

	if ((ch != 'y') && (ch != 'Y'))
	  {
	    /* user has decided to quit this series */
	    return (ret);
	  }
      } while (!isfile (datfile));

    } /* if no datfile */

    /* Install files from this disk */

    this = disk_install (datfile, descfile, fromdir, destdir);
    ret.errors += this.errors;
    ret.warnings += this.warnings;
  } /* while (1) */
}
Ejemplo n.º 22
0
int
S9xOpenROM (const char *rom_filename)
{
    uint32 flags;
    bool8  loaded;

    if (gui_config->rom_loaded)
    {
        S9xAutoSaveSRAM ();
    }

#ifdef NETPLAY_SUPPORT
    S9xNetplayDisconnect ();
#endif

    flags = CPU.Flags;

    loaded = FALSE;

    if (Settings.Multi)
        loaded = Memory.LoadMultiCart (Settings.CartAName, Settings.CartBName);
    else if (rom_filename)
        loaded = Memory.LoadROM (rom_filename);

    Settings.StopEmulation = !loaded;

    if (!loaded && rom_filename)
    {
        char dir [_MAX_DIR + 1];
        char drive [_MAX_DRIVE + 1];
        char name [_MAX_FNAME + 1];
        char ext [_MAX_EXT + 1];
        char fname [_MAX_PATH + 1];

        _splitpath (rom_filename, drive, dir, name, ext);
        _makepath (fname, drive, dir, name, ext);

        strcpy (fname, S9xGetDirectory (ROM_DIR));
        strcat (fname, SLASH_STR);
        strcat (fname, name);

        if (ext [0])
        {
            strcat (fname, ".");
            strcat (fname, ext);
        }

        _splitpath (fname, drive, dir, name, ext);
        _makepath (fname, drive, dir, name, ext);

        if ((Settings.StopEmulation = !Memory.LoadROM (fname)))
        {
            fprintf (stderr, _("Error opening: %s\n"), rom_filename);

            loaded = FALSE;
        }
        else
            loaded = TRUE;
    }

    if (loaded)
    {
        Memory.LoadSRAM (S9xGetFilename (".srm", SRAM_DIR));
    }
    else
    {
        CPU.Flags = flags;
        Settings.Paused = 1;

        S9xNoROMLoaded ();
        top_level->refresh ();

        return 1;
    }

    CPU.Flags = flags;

    if (stateMan.init (gui_config->rewind_buffer_size * 1024 * 1024))
    {
        printf ("Using rewind buffer of %uMB\n", gui_config->rewind_buffer_size);
    }

    S9xROMLoaded ();

    return 0;
}
Ejemplo n.º 23
0
int main( int argc, char *argv[] )
{
    char                *buff = NULL;
    char                *buff2, *buff3;
    char                *buffn, *buffs;
    int                 i, cnt, bytes, lines, j, k, sl;
    FILE                *f;
    struct stat         fs;
    char                drive[_MAX_DRIVE], dir[_MAX_DIR];
    char                fname[_MAX_FNAME], ext[_MAX_EXT];
    char                path[_MAX_PATH];
    char                tmppath[_MAX_PATH];
    char                tmpfname[_MAX_FNAME], tmpext[_MAX_EXT];

    j = argc - 1;
    while( j > 0 ) {
        if( argv[j][0] == '/' || argv[j][0] == '-' ) {
            sl = strlen( argv[j] );
            for( i = 1; i < sl; i++ ) {
                switch( argv[j][i] ) {
                case 's': sflag = TRUE; break;
                case 'q': qflag = TRUE; break;
                case 'd':
                    bindfile = &argv[j][i + 1];
                    i = sl;
                    break;
                case '?':
                    Banner();
                    Usage( NULL );
                default:
                    Banner();
                    Usage( "Invalid option" );
                }
            }
            for( i = j; i < (unsigned)argc; i++ ) {
                argv[i]= argv[i + 1];
            }
            argc--;
        }
        j--;
    }
    Banner();

    /*
     * now, check for null file name
     */
    if( argc < 2 ) {
        Usage( "No executable to bind" );
    }
    _splitpath( argv[1], drive, dir, fname, ext );
    if( ext[0] == 0 ) {
        _makepath( path, drive, dir, fname, ".exe" );
    } else {
        strcpy( path, argv[1] );
    }
    if( stat( path, &fs ) == -1 ) {
        Abort( "Could not find executable \"%s\"", path );
    }

    if( !sflag ) {

        buff = MyAlloc( 65000 );
        buff2 = MyAlloc( 32000 );
        buff3 = MyAlloc( MAX_LINE_LEN );

        /*
         * read in all data files
         */
        MyPrintf( "Getting data files from" );
        f = GetFromEnvAndOpen( bindfile );
        MyPrintf( "\n" );
        if( f == NULL ) {
            Abort( "Could not open %s", bindfile );
        }
        while( fgets( buff3, MAX_LINE_LEN, f ) != NULL ) {
            for( i = strlen( buff3 ); i && isWSorCtrlZ( buff3[i - 1] ); --i ) {
                buff3[i - 1] = '\0';
            }
            if( buff3[0] == '\0' ) {
                continue;
            }
            RemoveLeadingSpaces( buff3 );
            if( buff3[0] == '#' ) {
                continue;
            }
            dats[FileCount] = MyAlloc( strlen( buff3 ) + 1 );
            strcpy( dats[FileCount], buff3 );
            FileCount++;
            if( FileCount >= MAX_DATA_FILES ) {
                Abort( "Too many files to bind!" );
            }
        }
        fclose( f );
        index = MyAlloc( FileCount * sizeof( long ) );
        entries = MyAlloc( FileCount * sizeof( short ) );

        buffn = buff;
        cnt = 0;

        *(short *)buffn = FileCount;
        buffn += sizeof( short );
        cnt += sizeof( short );
        buffs = buffn;
        buffn += sizeof( short );
        cnt += sizeof( short );
        k = 0;
        for( i = 0; i < FileCount; i++ ) {
//          j = strlen( dats[i] ) + 1;
//          memcpy( buffn, dats[i], j );
            _splitpath( dats[i], NULL, NULL, tmpfname, tmpext );
            _makepath( tmppath, NULL, NULL, tmpfname, tmpext );
            j = strlen( tmppath ) + 1;
            memcpy( buffn, tmppath, j );
            buffn += j;
            cnt += j;
            k += j;
        }
        *(short *)buffs = k + 1;    /* size of token list */
        *buffn = 0;                 /* trailing zero */
        buffn++;
        cnt++;
        buffs = buffn;
        buffn += FileCount * (sizeof( short ) + sizeof( long ));
        cnt += FileCount * (sizeof( short ) + sizeof( long ));

        for( j = 0; j < FileCount; j++ ) {
            MyPrintf( "Loading" );
            f = GetFromEnvAndOpen( dats[j] );
            if( f == NULL ) {
                Abort( "\nLoad of %s failed!", dats[j] );
            }
            setvbuf( f, buff2, _IOFBF, 32000 );
            bytes = lines = 0;
            index[j] = (long)cnt;
            while( fgets( buff3, MAX_LINE_LEN, f ) != NULL ) {
                for( i = strlen( buff3 ); i && isWSorCtrlZ( buff3[i - 1] ); --i )
                    buff3[i - 1] = '\0';
                if( buff3[0] == '\0' ) {
                    continue;
                }
                RemoveLeadingSpaces( buff3 );
                if( buff3[0] == '#' ) {
                    continue;
                }
                i = strlen( buff3 );
                *buffn = (char)i;
                buffn++;
                memcpy( buffn, buff3, i );
                buffn += i;
                cnt += i + 1;
                lines++;
                bytes += i;
            }
            fclose( f );
            entries[j] = lines;
            MyPrintf( "Added %d lines (%d bytes)\n", lines, bytes );
        }
        i = FileCount;
        memcpy( buffs, index, FileCount * sizeof( long ) );
        buffs += FileCount * sizeof( long );
        memcpy( buffs, entries, FileCount * sizeof( short ) );
    }

    AddDataToEXE( path, buff, cnt, fs.st_size );
    if( !sflag ) {
        MyPrintf( "Added %d bytes to \"%s\"\n", cnt, path );
    } else {
        MyPrintf( "\"%s\" has been stripped of configuration information\n", path );
    }
    return( 0 );

} /* main */
Ejemplo n.º 24
0
static void _scanCurrArg(char *currArg) {
    char *saveCurrArg = currArg;

    switch (currArg[0]) {
    case '-':
    case '/':
        currArg++;
        switch (currArg++[0]) {
        case 'F': g_opt.structFieldsSep = currArg; break;
        case 'f': g_opt.targetLang = TLT_FORTRAN; break;
        case '?':
        case 'h':
            printUsageAndExit();
            break;
        case 'i': addIncPath(currArg, 0, 1); break;
        case 'I': _scanSize(currArg, &(g_opt.intSize)); break;
        case 'j': g_opt.signedChar = 1; break;
        case 'l':
            if (currArg[0] == '=') {
                currArg++;
            }
            sscanf(currArg, "%u", &(g_opt.outLineLen));
            if (!WITHIN_RANGE(g_opt.outLineLen, 30, MAX_OUT_LINE_LEN)) {
                reportError(ERR_LINE_LEN_OUT_OF_RANGE, g_opt.outLineLen);
                g_opt.outLineLen = 0;
            }
            break;
        case 'a':
            switch (currArg++[0]) {
            case 'd': g_opt.asmAttachD = 1; break;
            case 0: g_opt.targetLang = TLT_ASM; break;
            default:
                reportError(ERR_INV_CMD_LINE_OPTION, saveCurrArg);
                break;
            }
            break;
        case 's':
            switch (currArg++[0]) {
            case '-':
                g_opt.prefixStructFields = 0;
                _scanCurrArg("-F");
                break;
            case '+': g_opt.prefixStructFields = 1; break;
            case '0': g_opt.supressLevel = 0; break;
            case '1': g_opt.supressLevel = 1; break;
            case '2': g_opt.supressLevel = 2; break;
            case '3': g_opt.supressLevel = 3; break;
            default: g_opt.supressLevel = 0; break;
            }
            break;
        case '1':
            if (currArg[0] == '6') {
                _scanCurrArg("-P16");
                _scanCurrArg("-I16");
            }
            break;
        case '3':
            if (currArg[0] == '2') {
                _scanCurrArg("-P32");
                _scanCurrArg("-I32");
            }
            break;
        case 'p': g_opt.conflictPrefix = currArg; break;
        case 'P':
            if (currArg[0] == 'n') {
                _scanSize(currArg+1, &(g_opt.nearPtrSize));
            } else if (currArg[0] == 'p' || currArg[0] == 'd') {
                _scanSize(currArg+1, &(g_opt.ptrSize));
            } else if (currArg[0] == 'f') {
                _scanSize(currArg+1, &(g_opt.farPtrSize));
            } else if (currArg[0] == 'h') {
                _scanSize(currArg+1, &(g_opt.hugePtrSize));
            } else {
                SizeType temp = SIZE_MAX;
                _scanSize(currArg, &temp);
                if (temp == SIZE_16) {
                    _scanCurrArg("-Pn16");
                    _scanCurrArg("-Pd16");
                    _scanCurrArg("-Pf32");
                    _scanCurrArg("-Ph32");
                } else if (temp == SIZE_32) {
                    _scanCurrArg("-Pn32");
                    _scanCurrArg("-Pd32");
                    _scanCurrArg("-Pf32");
                    _scanCurrArg("-Ph48");
                }
            }
            break;

#ifndef NDEBUG
        case 'd':
            g_opt.debug = 1;
            break;
#endif
        default:
            reportError(ERR_INV_CMD_LINE_OPTION, saveCurrArg);
        }
        break;

    case '?':
        printUsageAndExit();
        break;

    default:
        {
            char driveDir[_MAX_DRIVE+_MAX_DIR+10];
            char drive[_MAX_DRIVE];
            char dir[_MAX_DIR];
            char name[_MAX_FNAME];
            char ext[_MAX_EXT];
            int len;

            _splitpath(currArg, drive, dir, name, ext);
            _makepath(driveDir, drive, dir, "", "");
            len = strlen(driveDir);
            if (len > 0) if (driveDir[len-1] == '\\') {
                driveDir[len-1] = 0;
            }

            addSLListElem(g_opt.fileNameList, wicStrdup(currArg));
            addIncPath(driveDir, 0, 0);  // Add at the beginning
        }
    }
}
Ejemplo n.º 25
0
STATIC const char *addFile( const char *str ) {

    DIR                 *parent;
    struct dirent       *direntp;
    char                sp_buf[ _MAX_PATH2 ];
    char                *drive;
    char                *dir;
    char                path[ _MAX_PATH ];
    char                *p;
    size_t              len;
    size_t              files_in_dir;

/**/myassert( str != NULL );
    getAct( 0 );
    p = getFile( &str );
    if( strpbrk( p, WILD_CARDS ) == NULL ) {
        curAct = MemRealloc( curAct, sizeof( act_grp_t ) +
            sizeof( const char * ) * curAct->num_files );
        curAct->files[ curAct->num_files ] = p;
        ++curAct->num_files;
        return( str );
    }
    /* process a wildcarded name */
    parent = opendir( p );
    if( parent == NULL ) {
        Fatal( MSG_UNABLE_TO_OPEN_FILE, p );
    }
    /*
        Since we must allocate memory for the filenames we shouldn't
        MemRealloc the curAct to a larger size at the same time.  So
        we count the number of files in the directory.
    */
    files_in_dir = 0;
    for(;;) {           /* count number of directory entries */
        direntp = readdir( parent );
        if( direntp == NULL ) break;
        ++files_in_dir;
    }
    closedir( parent );
    if( files_in_dir == 0 ) {
        Fatal( MSG_UNABLE_TO_OPEN_FILE, p );
    }
    curAct = MemRealloc( curAct, sizeof( act_grp_t ) +
        sizeof( const char * ) * ( curAct->num_files + files_in_dir - 1 ) );
    parent = opendir( p );
    if( parent == NULL ) {
        Fatal( MSG_UNABLE_TO_OPEN_FILE, p );
    }
    _splitpath2( p, sp_buf, &drive, &dir, NULL, NULL );
    MemFree( p );               /* no longer need this */
    for(;;) {
        /* we ignore any difference between the number of times we can
          loop here, and file_in_dir calc'd above */
        direntp = readdir( parent );
        if( direntp == NULL ) break;
        _makepath( path, drive, dir, direntp->d_name, NULL );
        len = strlen( path ) + 1;
        curAct->files[ curAct->num_files ] =
                                        memcpy( MemAlloc( len ), path, len );
        ++curAct->num_files;
        --files_in_dir;
        if( files_in_dir == 0 ) break;
    }
    closedir( parent );
    return( str );
}
Ejemplo n.º 26
0
int main(int nCountArg, char* lpszArg[], char* lpszEnv[])
{
//  EnableDebugPriv();
//  CSharedMemory cSharedMemory;
//
//  if (cSharedMemory.Open(HE4_CONTROL_DLL_SHARED_MEMORY, 4096, 100))
//  {
//    char Msg[2048];
//    PHE4_CONTROL_MSG pMsg = (PHE4_CONTROL_MSG) Msg;
//    
//    pMsg->m_dwMessageId = 2;
//    strcpy((char*)pMsg->m_MessageBody, "D:\\tmp\\guard\\He4HookInv.sys");
//    pMsg->m_dwSizeByBytes = SIZE_OF_HE4_CONTROL_MSG_REAL + strlen((char*) pMsg->m_MessageBody) + sizeof(char);
//
//    cSharedMemory.Write(pMsg, pMsg->m_dwSizeByBytes, 500);
//
//    memset(Msg, 0, sizeof(Msg));
//
//    cSharedMemory.Write(pMsg, pMsg->m_dwSizeByBytes, 500);
//
//
//
//    cSharedMemory.Close();
//    printf("[email protected]\n\n");
//  }
  
//  TEST_ALIGN  TestAlign;
//  PTEST_ALIGN pTestAlign = &TestAlign;
//  PCHAR pSymbol = (PCHAR)&(pTestAlign->m_Symbol);
//  PCHAR pLong = (PCHAR)&(pTestAlign->m_Long);
//  int nRest = pLong-pSymbol;

  printf("\nHe4HookControl v2.03 - control utility for He4HookInv\n");
  printf("Copyright (C) 2000 He4 developers team\n");
  printf("[email protected]\n\n");

  ShowDeviceCurrentVersion();

  if (nCountArg <= 1)
  {
    ShowHelp();
    return 0;
  }

  for (int i=1; i<nCountArg; i++)
  {
    if (!stricmp(lpszArg[i], "-h"))
    {
      ShowHelp();
    }
    if (!strnicmp(lpszArg[i], "-i:", 3))
    {
      if (strlen(lpszArg[i]) > 3)
        bForceLoadDriver = (BOOL)atoi(lpszArg[i]+3);
    }
    if (!stricmp(lpszArg[i], "-s"))
    {
      bShowProtectedFiles = TRUE;
    }
    if (!strnicmp(lpszArg[i], "-hk:", 4))
    {
      if (strlen(lpszArg[i]) > 4)
        bHookFileSystem = atoi(lpszArg[i]+4);
    }
    if (!strnicmp(lpszArg[i], "-c:", 3))
    {
      if (strlen(lpszArg[i]) > 3)  
      {
        dwFileAccessType = 0;
        char* pszAcc = lpszArg[i]+3;
        for (; *pszAcc; pszAcc++)
        {
          if (*pszAcc == 'R' || *pszAcc == 'r')
            dwFileAccessType |= ACC_TYPE_READ;
          if (*pszAcc == 'W' || *pszAcc == 'w')
            dwFileAccessType |= ACC_TYPE_WRITE;
          if (*pszAcc == 'D' || *pszAcc == 'd')
            dwFileAccessType |= ACC_TYPE_DELETE;
          if (*pszAcc == 'V' || *pszAcc == 'v')
            dwFileAccessType |= ACC_TYPE_VISIBLE;
          if (*pszAcc == 'E' || *pszAcc == 'e')
            dwFileAccessType |= FILE_ACC_TYPE_EXCHANGE;
        }
      }
    }
    if (!strnicmp(lpszArg[i], "-cp:", 4))
    {
      if (strlen(lpszArg[i]) > 4)  
      {
//        dwFileAccessType = 0;
        char* pszAcc = lpszArg[i]+4;
        dwProcessAccessType = 0;
        for (; *pszAcc; pszAcc++)
        {
          if (*pszAcc == 'R' || *pszAcc == 'r')
            dwProcessAccessType |= HE4_UNLOCK_READ;
          if (*pszAcc == 'W' || *pszAcc == 'w')
            dwProcessAccessType |= HE4_UNLOCK_WRITE;
          if (*pszAcc == 'D' || *pszAcc == 'd')
            dwProcessAccessType |= HE4_UNLOCK_DELETE;
          if (*pszAcc == 'V' || *pszAcc == 'v')
            dwProcessAccessType |= HE4_UNLOCK_VISIBLE;
        }
      }
    }
    if (!stricmp(lpszArg[i], "-la"))
      bLockSaveObjectsForAllThreads = TRUE;
    if (!stricmp(lpszArg[i], "-da"))
      bClearSaveList = TRUE;
    if (!stricmp(lpszArg[i], "-t"))
      bShowUnlockThreadInfo = TRUE;
    if (!stricmp(lpszArg[i], "-q"))
      bShowStatistic = TRUE;
  }


  TCHAR szExeFileName[2048];
  TCHAR szDeviceFileName[2048];

  GetModuleFileName(NULL, szExeFileName, 2048);

  TCHAR drive[_MAX_DRIVE];   
  TCHAR dir[_MAX_DIR];
  TCHAR fname[_MAX_FNAME];   
  TCHAR ext[_MAX_EXT];

  _splitpath(szExeFileName, drive, dir, fname, ext);
  lstrcpy(szDeviceFileName, _T("\\??\\"));
  _makepath(szDeviceFileName+sizeof(_T("\\??\\"))-sizeof(TCHAR), drive, dir, HE4_SERVICE_FILE_NAME, _T(""));

  pNtDriverControl = new He4HookDriverHide(szDeviceFileName);
  if (pNtDriverControl == NULL)
  {
    printf("\nNo memory for create class He4HookDriverHide!!!\n");
    return -1;
  }

  if (pNtDriverControl->Result == FALSE)
  {
    delete pNtDriverControl;
    printf("\nCreate class He4HookDriverHide - ERROR!!!\n");
    return -1;
  }

  if (bForceLoadDriver)
  {
    if (InstallNewDriver(pNtDriverControl) == FALSE)
    {
      delete pNtDriverControl;
      printf("\nLoad new driver - ERROR!!!\n");
      return -1;
    }

    bShowProtectedFiles = TRUE;
    
    printf("\nNew version driver:\n");
    ShowDeviceCurrentVersion();
  }

  if (bHookFileSystem != -1)
  {
    DWORD dwDrivesMaskReal;
    if ((dwDrivesMaskReal = pNtDriverControl->HookFileSystem((DWORD)bHookFileSystem)) == (DWORD)-1)
    {
      if (bHookFileSystem)
        printf("Hook file system - ERROR!!!\n");
      else
        printf("Unhook file system - ERROR!!!\n");
    }
    else
    {
      if (bHookFileSystem)
        printf("File system - hooked\n");
      else
        printf("File system - unhooked\n");
    }
  }

  if (bLockSaveObjectsForAllThreads == TRUE)
    pNtDriverControl->LockSaveObjectsForAllThreads();

  if (bClearSaveList == TRUE)
    pNtDriverControl->ClearSaveList();
  
  for (i=1; i<nCountArg; i++)
  {
    if (!strnicmp(lpszArg[i], "-u:", 3))
    {
      if (strlen(lpszArg[i]) > 3)
      {
        AddProcessToUnLockList(lpszArg[i]+3, pNtDriverControl);
        bShowUnlockThreadInfo = TRUE;
      }
    }
    if (!strnicmp(lpszArg[i], "-l:", 3))
    {
      if (strlen(lpszArg[i]) > 3)
      {
        DeleteProcessFromUnLockList(lpszArg[i]+3, pNtDriverControl);
        bShowUnlockThreadInfo = TRUE;
      }
    }
    
    if (!strnicmp(lpszArg[i], "-a:", 3))
    {
      if (strlen(lpszArg[i]) > 3)
      {
        if (dwFileAccessType & FILE_ACC_TYPE_EXCHANGE)
        {
          char* pszFirstFile = strtok(lpszArg[i]+3, "=");
          if (pszFirstFile != NULL)
            pNtDriverControl->AddToSaveList(pszFirstFile, dwFileAccessType, strtok(NULL, "="));
        }
        else
          pNtDriverControl->AddToSaveList(lpszArg[i]+3, dwFileAccessType);
        bShowProtectedFiles = TRUE;
      }
    }
    if (!strnicmp(lpszArg[i], "-d:", 3))
    {
      if (strlen(lpszArg[i]) > 3)
      {
        pNtDriverControl->DelFromSaveList(lpszArg[i]+3);
        bShowProtectedFiles = TRUE;
      }
    }
  }

  if (bShowProtectedFiles)
  {
    printf("\nProtected files list:\n");
    ShowProtectedFiles(pNtDriverControl);
  }

  if (bShowUnlockThreadInfo)
  {
    ShowUnlockThreads(pNtDriverControl);
  }
  
  if (bShowStatistic)
  {
    ShowStatistic(pNtDriverControl);
  }


  delete pNtDriverControl;

  return 0;
}
Ejemplo n.º 27
0
int dump_fntsys(const char *filename, uint32_t addr, textoffindex_struct *toi, uint32_t num_toi, char *out_dir)
{
	uint32_t i, j;
	long size;
	unsigned char *buf;

	FILE *fp = fopen(filename, "rb"), *output_fp;

	if (fp)
	{
		fseek(fp, 0, SEEK_END);
		size = ftell(fp);
		fseek(fp, 0, SEEK_SET);

		if ((buf = (unsigned char *)malloc(size)) == NULL)
		{
			printf("Error allocating memory\n");
			return -1;
		}		

		fread((void *)buf, 1, size, fp);
		fclose(fp);		

		for (i = 0; i < num_toi; i++)
		{
			long end;
			char drive[_MAX_DRIVE], dir[_MAX_DIR], fn[_MAX_FNAME];
			char output_filename[_MAX_PATH];
			uint32_t *off=buf;
			uint32_t tbl_off, text_off, num_tbl;

			_splitpath(out_dir, drive, dir, fn, NULL);
			strcat(dir, fn);
			_splitpath(filename, NULL, NULL, fn, NULL);
			itoa(i+1, fn+strlen(fn), 10);
			_makepath(output_filename, drive, dir, fn, ".sjs");

			printf("Writing %s...", output_filename);

			if ((output_fp = fopen(output_filename, "wt")) == NULL)
			{
				printf("Error opening %s for writing\n", output_filename);
				fclose(fp);
				return -2;
			}

			tbl_off=(DoubleWordSwap(off[toi[i].tbl_index])-addr);
			text_off=(DoubleWordSwap(off[toi[i].text_index])-addr);
			num_tbl=(text_off-tbl_off)/2;

			if (i != num_toi-1)				
				end = (DoubleWordSwap(off[toi[i+1].tbl_index])-addr);
			else
				end = size-1;

			fprintf(output_fp, "Langrisser III dumper [0x%x to 0x%x]\n\n", text_off, end);
			fprintf(output_fp, "Cyber Warrior X\n");
			fprintf(output_fp, "\n");			

			for (j = 0; j < num_tbl; j++)
			{
				uint32_t offset = text_off+(WordSwap(*(uint16_t *)(buf+tbl_off+(j*2)))*2);
				unsigned long counter=0;
				for (;;)
				{
					int data_size;
					unsigned char data[256];
					int ret = Table_Match_Code_To_Char(trans_table, buf + offset + counter, data, &data_size);

					if (ret > 0)
					{
						fwrite((void *)data, data_size, 1, output_fp);
						counter += ret;           
					}
					else
					{
						if (buf[offset + counter] == 0xFF && 
							buf[offset + counter + 1] == 0xFF)
						{
							// end of a string
							fprintf(output_fp, "<$FFFF>\n");
							break;
						}
						else
						{
							// just insert the character as <$hex>
							//printf("can't figure out character %02X%02X%02X%02X\n", temp_buffer[offset + counter], temp_buffer[offset + counter + 1], temp_buffer[offset + counter + 2], temp_buffer[offset + counter + 3]);
							fprintf(output_fp, "<$%02X>",  buf[offset + counter]);
						}

					}
				}
			}

			fclose(output_fp);
			printf("done.\n");
		}

		free(buf);
	}

	return 0;
}
Ejemplo n.º 28
0
DAQ_LINKAGE int daq_load_modules(const char *directory_list[])
{
    static const char *extension = MODULE_EXT;
#ifndef WIN32
    char dirpath[NAME_SIZE];
    DIR *dirp;
    struct dirent *de;
    char *p;
    int ret;

#ifdef STATIC_MODULE_LIST
    load_static_modules();
#endif

    for (; directory_list && *directory_list; directory_list++)
    {
        if (!(**directory_list))
            continue;
        if ((dirp = opendir(*directory_list)) == NULL)
        {
            fprintf(stderr,"Unable to open directory \"%s\"\n", *directory_list);
            continue;
        }

        DEBUG("Loading modules in: %s\n", *directory_list);

        while((de = readdir(dirp)) != NULL)
        {
            if (de->d_name == NULL)
                continue;
            p = strrchr(de->d_name, '.');
            if (!p || strcmp(p, extension))
                continue;
            snprintf(dirpath, sizeof(dirpath), "%s/%s", *directory_list, de->d_name);

            ret = daq_load_module(dirpath);
            if (ret == DAQ_SUCCESS)
            {
                DEBUG("Found module %s\n", de->d_name);
            }
            else if (ret == DAQ_ERROR_NOMEM)
            {
                closedir(dirp);
                return DAQ_ERROR_NOMEM;
            }
        }
        closedir(dirp);
    }
#else
    /* Find all shared library files in path */
    char path_buf[PATH_MAX];
    char dyn_lib_name[PATH_MAX];
    char drive[_MAX_DRIVE];
    char dir[_MAX_DIR];
    char fname[_MAX_FNAME];
    char ext[_MAX_EXT];
    HANDLE fSearch;
    WIN32_FIND_DATA FindFileData;
    int pathLen = 0;
    const char *directory;
    int useDrive = 0;

#ifdef STATIC_MODULE_LIST
    load_static_modules();
#endif

    for (; directory_list && *directory_list; directory_list++)
    {
        if (!(**directory_list))
            continue;

        if ((strncpy(path_buf, *directory_list, PATH_MAX) == NULL) ||
            (strlen(path_buf) != strlen(*directory_list)))
        {
            fprintf(stderr, "Path is too long: %s\n", *directory_list);
            continue;
        }

        pathLen = strlen(path_buf);
        if ((path_buf[pathLen - 1] == '\\') ||
            (path_buf[pathLen - 1] == '/'))
        {
            /* A directory was specified with trailing dir character */
            _splitpath(path_buf, drive, dir, fname, ext);
            _makepath(path_buf, drive, dir, "*", MODULE_EXT);
            directory = &dir[0];
            useDrive = 1;
        }
        else /* A directory was specified */
        {
            _splitpath(path_buf, drive, dir, fname, ext);
            if (strcmp(extension, ""))
            {
                fprintf(stderr, "Improperly formatted directory name: %s\n", *directory_list);
                continue;
            }

            _makepath(path_buf, "", path_buf, "*", MODULE_EXT);
            directory = *directory_list;
        }

        fSearch = FindFirstFile(path_buf, &FindFileData);
        while (fSearch != NULL && fSearch != (HANDLE)-1)
        {
            if (useDrive)
                _makepath(dyn_lib_name, drive, directory, FindFileData.cFileName, NULL);
            else
                _makepath(dyn_lib_name, NULL, directory, FindFileData.cFileName, NULL);

            daq_load_module(dyn_lib_name);

            if (!FindNextFile(fSearch, &FindFileData))
            {
                break;
            }
        }
        FindClose(fSearch);
    }
#endif
    return DAQ_SUCCESS;
}
int main ( int argc, char* argv[] )
{
	char		szProjectFilePath	[_MAX_PATH	+1];
	char		szSourceFilePath	[_MAX_PATH	+1];
	char		szDrive						[_MAX_DRIVE	+1];
	char		szDir							[_MAX_DIR		+1];
	char		szExt							[_MAX_EXT		+1];
	char		szFname						[_MAX_PATH	+1];
	char		szOldDirectory		[_MAX_PATH	+1];
	int			i;
	_OPTIONS	*pOptTarget		= sOptions,
						*pOptPlatform	= sOptions,
						*pOptOS				= sOptions,
						*pOptFile			= sOptions,
						*pOptOpt			= sOptions;

	szProjectFilePath	[0] = '\0';
	szSourceFilePath	[0] = '\0';

	BOOL		flagPrint = TRUE;
	if ( argc < 2 )
		return 0;

	for ( i=2; i< argc; i++ )
		{
		 if ( i < argc )
			 *(argv[i]-1) = ' ';
		}
	ParseOptions( argv[1], sOptions, sOptionsSubst );
	GetCurrentDirectory( MAX_PATH, szOldDirectory );
	_splitpath( argv[1], szDrive, szDir, szFname, szExt );
	_makepath( szProjectFilePath, szDrive, szDir, szFname, szExt );
	ChangeSlash( szProjectFilePath );

	if( szProjectFilePath && ! access( szProjectFilePath, 4 ) )	// if a specified file exists
	{																														// and we have read access right

		if( strlen( szDir ) )
		{
			char		szProjectDirectory[_MAX_PATH	+1];
		
			szProjectDirectory[0] = '\0';
			strcat( szProjectDirectory, szDrive );
			strcat( szProjectDirectory, szDir );
			SetCurrentDirectory( szProjectDirectory );
		}

	FILE*	file;
	if ( flagPrint )
		{
		file= fopen(LOG_FILE_NAME, "w+t");
		fprintf(file, "%s", "MakePDF\n" );
		fclose(file);
		}

	while ( stricmp(pOptTarget	->pszOptionText, "TARGET"	 ) ) pOptTarget		++;
	while ( stricmp(pOptPlatform->pszOptionText, "PLATFORM") ) pOptPlatform	++;
	while ( stricmp(pOptOS			->pszOptionText, "OS"			 ) ) pOptOS				++;
	while ( stricmp(pOptFile		->pszOptionText, "FILE"		 ) ) pOptFile			++;
	while ( stricmp(pOptOpt			->pszOptionText, "OPTIONS" ) ) pOptOpt			++;

	if ( pOptFile->bOptionOn && *(pOptFile->pszOptionVal) )
		InternalConvertFileName( pOptFile->pszOptionVal, szSourceFilePath );

	SetCommonVar( pOptOS->pszOptionVal, pOptPlatform->pszOptionVal, pOptTarget->pszOptionVal ); 

	TargetNode		Head( szProjectFilePath, NULL );
	TargetNode*		pProjectNode;
	TargetNode*		pTarget;

	Head.ProcessNMake(TARGET_PROJECT);
	pProjectNode = Head.GetFirstChildPRJ();
	while ( pProjectNode )
		{
		 pProjectNode->ProcessNMake(TARGET_FILE_C);
		 if ( *szSourceFilePath && ( pTarget=pProjectNode->FindByNameTargetC(szSourceFilePath) ) != NULL )
				{
				 OptionNode	*pOption = pTarget->GetCompileOptions();
				 if ( pOption )
					{
					 printf(" cl -n %s", szSourceFilePath);
					 while ( pOption )
							{
							 printf(" -%s", pOption->GetOptionText() );
							 pOption= pOption->GetNext();
							}
					 printf("\n" );
					}
				 break;
				}
		 pProjectNode = pProjectNode->GetNext();
		}


	if ( !pOptFile->bOptionOn )
		{
			Head.CreateProjectTree();
			Head.RaiseUpPathC();
			Head.PrintProjectTree(0);
			Head.SetProjectPath();
			Head.ProcessFileH();
			Head.RaiseUpPathH();
			Head.RaiseUpTargetH();
			if (pOptOpt->bOptionOn)
				{
					Head.RaiseUpOptions();
					Head.WritePDFOptions();
				}
			Head.Wildcards();
			Head.PullDownPath();
			Head.PrintProjectTree(0);
			Head.ConvertFileName();
			Head.WritePDF();
		}
	SetCurrentDirectory( szOldDirectory );
	}
	
	return 0;
}
Ejemplo n.º 30
0
STATIC RET_T imply( TARGET *targ, const char *drive, const char *dir,
    const char *fname, const char *ext, BOOLEAN must )
/********************************************************************
 * targ     is the target to be implied
 * drive    is the drive of the target
 * dir      is the path of the target
 * fname    is the portion of targ's name without the extension
 * ext      is the extension of targ's name
 * must     must we make this target?
 *
 * RET_SUCCESS - performed cmds,
 * RET_WARN unable to imply,
 * RET_ERROR - perform failed
 */
{
    SUFFIX      *srcsuf;
    CREATOR     *cur;
    SUFFIX      *cursuf;
    TARGET      *imptarg;
    RET_T       ret;
    BOOLEAN     newtarg;
    UINT32      startcount;
    char        *buf;
    SLIST       *curslist;
    SLIST       *slistCmd;  // Slist chosen for sufsuf
    SLIST       *slistDef;  // Slist that has dependent path = ""
    SLIST       *slistEmptyTargDepPath;
    BOOLEAN     UseDefaultSList;
    int         slistCount;

    srcsuf = FindSuffix( ext );
    if( srcsuf == NULL || srcsuf->creator == NULL ) {
        PrtMsg( DBG | INF | IMP_ENV_M, targ->node.name, M_HAS_NO_IMPLICIT );
        return( RET_WARN );
    }
    PrtMsg( DBG | INF | IMP_ENV_M, targ->node.name, M_CHECKING_IMPLICIT );
    startcount = cListCount;

    for( cur = srcsuf->creator; cur != NULL; cur = cur->next ) {
        cursuf = cur->suffix;

        /* allocate a buffer */
        buf = MallocSafe( _MAX_PATH );
        slistCmd = NULL;
        slistDef = NULL;
        slistEmptyTargDepPath = NULL;

        assert( cur->cretarg         != NULL );
        assert( cur->cretarg->depend != NULL );
        curslist = cur->cretarg->depend->slist;

        ret = RET_ERROR;

        UseDefaultSList = TRUE;
        slistCount = 0;
        /* find path in SLIST */
        while( curslist != NULL && ret != RET_SUCCESS ) {
            _makepath( buf, drive, dir, NULL, NULL );
            /*
             * note the path of the current target must match the
             * path as specified in the slist
             */
            if( strcmpi( buf, curslist->targ_path ) == 0 ) {
                /* build filename for implied target */
                _makepath( buf, NULL, curslist->dep_path,
                           fname, cursuf->node.name );
                /* try to find this file on path or in targets */
                ret = TrySufPath( buf, buf, &imptarg, FALSE );
                if( ret == RET_SUCCESS ) {
                    slistCmd = curslist;
                /* later on we need to check if implied target does not */
                /* exist we need to create it on the first directory we */
                /* see on the SLIST since                               */
                /* the first on the list is the one that was defined    */
                /* last in the makefile                                 */
                } else if( slistDef == NULL ) {
                    slistDef = curslist;
                }
            }
            if( curslist->targ_path[0] == NULLCHAR &&
                curslist->dep_path[0]  == NULLCHAR ) {
                slistEmptyTargDepPath = curslist;
            }

            if( slistCount > 0 && slistEmptyTargDepPath != NULL ) {
                UseDefaultSList = FALSE;
            }
            curslist = curslist->next ;
            ++slistCount;
        }

        if( UseDefaultSList && slistCmd  == NULL && !Glob.microsoft ) {
            _makepath( buf, NULL, NULL, fname, cursuf->node.name );
            /* try to find this file on path or in targets */
            ret = TrySufPath( buf, buf, &imptarg, FALSE );
            switch( ret ) {
            case RET_WARN:
                break;
            case RET_ERROR:
                if( !Glob.microsoft ) {
                    slistDef = slistEmptyTargDepPath;
                }
                break;
            case RET_SUCCESS:
                slistCmd = slistEmptyTargDepPath;
                break;
            }
        }


        if( (ret == RET_SUCCESS && imptarg == NULL) || ret == RET_ERROR ) {
            /* Either file doesn't exist, or it exists and we don't already
             * have a target for it.  Either way, we create a new target.
             */
            if( ret == RET_ERROR ) {
                /*
                 * No Default Slist found so must continue and find
                 * another slist
                 */
                if( slistDef == NULL ) {
                    FreeSafe( buf );
                    continue;
                } else {
                    slistCmd = slistDef;
                }
                    /* file doesn't exist, assume in directory */
                    /* pointed to by the slistDef              */
                _makepath( buf, NULL, slistCmd->dep_path,
                           fname, cursuf->node.name );

            }
            newtarg = TRUE;
            imptarg = NewTarget( buf );
            FreeSafe( buf );        /* don't need any more */
            getStats( imptarg );
            imptarg->busy = TRUE;   /* protect against recursion */
            if( imply( imptarg, NULL, slistCmd->dep_path,
                        fname, cursuf->node.name, FALSE ) ==
                RET_ERROR ) {
                imptarg->error = TRUE;
            }
            if( startcount != cListCount && (Glob.noexec || Glob.query) ) {
                imptarg->touched = TRUE;
                imptarg->executed = TRUE;       /* 29-oct-90 */
            }
            imptarg->updated = TRUE;
            imptarg->busy = FALSE;
        } else {
            /* We already know about imptarg, so just update it */
            assert( imptarg != NULL );
            FreeSafe( buf );        /* don't need any more */
            newtarg = FALSE;        /* this isn't a new target */
            Update( imptarg );
        }

        /* We've tried our best to make the imptarg, check if it exists
         * after our efforts.
         */
        if( targExists( imptarg ) ) {
            /* it exists - now we perform the implicit cmd list, and return */
            ret = implyMaybePerform( targ, imptarg, cur->cretarg, must,
                slistCmd );
            if( newtarg && !Glob.noexec ) {
                /* destroy the implied target, because the info in the target
                 * structure is nicely stored on disk (unless Glob.noexec)
                 */
                KillTarget( imptarg->node.name );
            }
            implyDebugInfo( targ, startcount );
            return( ret );
        } else if( newtarg ) {
            /* we created an unsuccessful target - so destroy it */
            KillTarget( imptarg->node.name );
        }

        /* We couldn't imply with this suffix... try next one */
    }
    implyDebugInfo( targ, startcount );
    return( RET_WARN );
}