コード例 #1
0
BOOL ReadObjData( LPSTR lpFileName, LPOBJECTLIST lpObjList, int outDepth,
		LPINT lpDataType, LPRECT lpScaleRect, LPINT lpFullFileX, LPINT lpFullFileY, LPINT lpFullResolution)

/************************************************************************/
{
LPFRAME lpFrame;
LPOBJECT lpObject;
int ifh;
LPLONG lngptr;
LPWORD shtptr;
int nObjects, i, idFileType, nPasses;
WORD wBytes, wByteOrder, wVersion;
long lObjSize, lObjStart;
LPOBJOFFSETS lpOffsets;
OBJECT Obj;
LFIXED xrate, yrate;
int opix, olin, baseW, baseH;
LPRECT lpLoadRect;

xrate = yrate = UNITY;
lpOffsets = NULL;

if ( !lpObjList )
	return( FALSE );

lpObjList->lpHead = lpObjList->lpTail = NULL;
if ( (ifh = _lopen(lpFileName, OF_READ)) < 0)
	{
	Message( IDS_EOPEN, lpFileName );
	return( FALSE );
	}

// Read in header info
wBytes = OBJ_HDR_SIZE;
if ( _lread(ifh, LineBuffer[0], wBytes) != wBytes )
	goto BadRead;
shtptr = (LPWORD)LineBuffer[0];
wByteOrder = GetNextWord(&shtptr);	/* byte order is LSB,MSB */
if (wByteOrder != TIF_II && wByteOrder != TIF_MM)
	goto BadRead;
wVersion  = GetNextWord(&shtptr);	/* Version Number */
nObjects  = GetNextWord(&shtptr);	/* Number of Objects */
lngptr    = (LPLONG)shtptr;
lObjSize  = GetNextLong(&lngptr);	/* size of object data */
lObjStart = GetNextLong(&lngptr);	/* start of object data */

if (!(lpOffsets = (LPOBJOFFSETS)Alloc(sizeof(OBJOFFSETS)*nObjects)))
	{
	Message(IDS_EMEMALLOC);
	return(FALSE);
	}
_llseek (ifh, lObjStart, 0);
wBytes = (WORD)lObjSize;
nPasses = 0;
for (i = 0; i < nObjects; ++i)
	{
	if ( _lread(ifh, LineBuffer[0], wBytes) != wBytes )
		goto BadRead;
	shtptr = (LPWORD)LineBuffer[0];

	Obj.ObjectType 		= (OBJECT_TYPE)GetNextWord(&shtptr);
	Obj.rObject.left 	= GetNextWord(&shtptr);
	Obj.rObject.top 	= GetNextWord(&shtptr);
	Obj.rObject.right 	= GetNextWord(&shtptr);
	Obj.rObject.bottom 	= GetNextWord(&shtptr);
	Obj.Opacity 		= GetNextWord(&shtptr);
	Obj.MergeMode 		= (MERGE_MODE)GetNextWord(&shtptr);
	Obj.wGroupID 		= GetNextWord(&shtptr);

	if (i==0 && lpScaleRect)
	{
		opix = RectWidth(lpScaleRect);
		olin = RectHeight(lpScaleRect);
		baseW = RectWidth(&Obj.rObject);
		baseH = RectHeight(&Obj.rObject);
		xrate = ScaleToFit(&opix, &olin, baseW, baseH);
		if (opix > baseW || olin > baseH)
		{ // No upsizing allowed
			opix = baseW;
			olin = baseH;
		}
		xrate = FGET( opix, baseW );
		yrate = FGET( olin, baseH );
	}
	// scale the object rect
	Obj.rObject.left	= FMUL(Obj.rObject.left, xrate);
	Obj.rObject.top 	= FMUL(Obj.rObject.top, yrate);
	Obj.rObject.right 	= FMUL(Obj.rObject.right, xrate);
	Obj.rObject.bottom 	= FMUL(Obj.rObject.bottom, yrate);

	if (!(lpObject = ObjCreateFromFrame(ST_PERMANENT, NULL, NULL, &Obj.rObject,
										Control.NoUndo)))
		{
		Message(IDS_EMEMALLOC);
		goto BadRead;
		}
	idFileType                = GetNextWord(&shtptr);
	lpOffsets[i].bInvert      = GetNextWord(&shtptr);
	lpOffsets[i].rMask.left   = GetNextWord(&shtptr);
	lpOffsets[i].rMask.top    = GetNextWord(&shtptr);
	lpOffsets[i].rMask.right  = GetNextWord(&shtptr);
	lpOffsets[i].rMask.bottom = GetNextWord(&shtptr);
	// scale the mask rect
	lpOffsets[i].rMask.left	  = FMUL(lpOffsets[i].rMask.left,   xrate);
	lpOffsets[i].rMask.top 	  = FMUL(lpOffsets[i].rMask.top,    yrate);
	lpOffsets[i].rMask.right  = FMUL(lpOffsets[i].rMask.right,  xrate);
	lpOffsets[i].rMask.bottom = FMUL(lpOffsets[i].rMask.bottom, yrate);
	lngptr = (LPLONG)shtptr;
	lpOffsets[i].lDataOffset  = GetNextLong(&lngptr);
	lpOffsets[i].lAlphaOffset = GetNextLong(&lngptr);
	shtptr = (LPWORD)lngptr;

	// versions after 1.1 saved selected state
	if (wVersion == 0x0101)
		Obj.fSelected = NO;
	else
		Obj.fSelected = GetNextWord(&shtptr);

    if (wVersion < 0x0103 || lObjSize == 41)
    {
        Obj.ObjectDataID = OBJECT_DATA_NONE;
        Obj.dwObjectData = 0;
    }
	else
    {
        Obj.ObjectDataID = GetNextWord(&shtptr);
        Obj.dwObjectData = *(LPDWORD)shtptr;
        shtptr += 2;
    }

	lpObject->ObjectType 	= Obj.ObjectType;
	lpObject->Opacity 		= Obj.Opacity;
	lpObject->MergeMode 	= Obj.MergeMode;
	lpObject->wGroupID 		= Obj.wGroupID;
	lpObject->fSelected 	= Obj.fSelected;
    lpObject->ObjectDataID 	= Obj.ObjectDataID;
    lpObject->dwObjectData 	= Obj.dwObjectData;

	ObjAddTail(lpObjList, (LPPRIMOBJECT)lpObject);

	++nPasses;
	if (lpOffsets[i].lAlphaOffset)
		++nPasses;
	}

ProgressBegin(nPasses, 0);
lpObject = NULL;
i = 0;
while (lpObject = (LPOBJECT)ObjGetNextObject(lpObjList, (LPPRIMOBJECT)lpObject, YES))
	{
	if (lpScaleRect && i!=0)
		{
		lpLoadRect = &lpObject->rObject;
		}
	else
		lpLoadRect = lpScaleRect;
	_llseek (ifh, lpOffsets[i].lDataOffset, 0);
	lpFrame = ReadTiffData(ifh, lpFileName, outDepth, lpDataType,
		NO/*bReadOnly*/, lpLoadRect, NO, lpFullFileX, lpFullFileY,
		lpFullResolution);
	if (i == 0)
		{
		lpDataType = NULL;
		lpFullFileX = NULL;
		lpFullFileY = NULL;
		lpFullResolution = NULL;
		}
	if (!lpFrame)
		goto BadRead;
	PixmapSetup(&lpObject->Pixmap, lpFrame, Control.NoUndo);
	if (!lpOffsets[i].lAlphaOffset)
		{
		++i;
		continue;
		}
	_llseek (ifh, lpOffsets[i].lAlphaOffset, 0);
	lpFrame = ReadTiffData(ifh, lpFileName, outDepth, lpDataType,
		NO/*bReadOnly*/, lpLoadRect, NO, NULL, NULL, NULL);
	if (!lpFrame)
		goto BadRead;
	lpObject->lpAlpha = MaskCreate(lpFrame, 0, 0, OFF, Control.NoUndo);
	if (!lpObject->lpAlpha)
		{
		Message(IDS_EMEMALLOC);
		goto BadRead;
		}
	lpObject->lpAlpha->bInvert = lpOffsets[i].bInvert;
	lpObject->lpAlpha->rMask = lpOffsets[i].rMask;
	++i;
	}

if ( lpOffsets )
	FreeUp( (LPTR)lpOffsets );
_lclose(ifh);
ProgressEnd();
return( TRUE );

BadRead:
while (lpObject = (LPOBJECT)ObjGetNextObject(lpObjList, NULL, YES))
	{
	ObjUnlinkObject(lpObjList, (LPPRIMOBJECT)lpObject);
	ObjFreeUp(lpObject);
	}
_lclose(ifh);
if ( lpOffsets )
	FreeUp( (LPTR)lpOffsets );
if (nPasses)
	ProgressEnd();
Message( IDS_EREAD, lpFileName );
return( FALSE );
}
コード例 #2
0
static int
_tiffCloseProc(thandle_t fd)
{
	return (_lclose(fd));
}
コード例 #3
0
BOOL WritePalette(
    /************************************************************************/
    LPSTR 		lpFileName,
    LPPALETTE 	lpPalette)
{
    int ofh;		/* file handle( unbuffered) */
    FILEBUF ofd;		/* file descriptor( buffered) */
    int i;
    VERSIONINFO	version;
    RECINFO rec;

    if (!lpPalette)
        return(FALSE);

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

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

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

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

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

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

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

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

    FileFlush(&ofd);

    _lclose(ofh);

    if ( ofd.err)
    {
        Message( IDS_EWRITE, lpFileName);
        return( NO);
    }
    return( YES);
}
コード例 #4
0
ファイル: Tmsrpt01.c プロジェクト: ems/TMS
BOOL FAR TMSRPT01(TMSRPTPassedDataDef *pPassedData)
{
  REPORTPARMSDef REPORTPARMS;
  HFILE hfOutputFile;
  BOOL  bKeepGoing = FALSE;
  BOOL  bRC;
  int   maxSelectedPatternNodes = 100;
  int   nI;
  int   nJ;
  int   nK;
  int   nL;
  int   numSelectedPatternNodes;
  int   rcode2;

  long  *pSelectedPatternNodes = NULL;

  pPassedData->nReportNumber = 0;
  pPassedData->numDataFiles = 1;
//
//  See what he wants
//
  REPORTPARMS.nReportNumber = pPassedData->nReportNumber;
  REPORTPARMS.ROUTESrecordID = m_RouteRecordID;
  REPORTPARMS.SERVICESrecordID = m_ServiceRecordID;
  REPORTPARMS.PATTERNNAMESrecordID = NO_RECORD;
  REPORTPARMS.COMMENTSrecordID = NO_RECORD;
  REPORTPARMS.pRouteList = NULL;
  REPORTPARMS.pServiceList = NULL;
  REPORTPARMS.flags = RPFLAG_ROUTES | RPFLAG_SERVICES | RPFLAG_PATTERNNAMES | RPFLAG_COMMENTS;
  bRC = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_RPTPARMS),
        hWndMain, (DLGPROC)RPTPARMSMsgProc, (LPARAM)&REPORTPARMS);
  if(!bRC)
  {
    return(FALSE);
  }
//
//  Check the list of routes and services
//
  if(REPORTPARMS.numRoutes == 0 || REPORTPARMS.numServices == 0)
  {
    goto deallocate;
  }
//
//  Open the output file
//
  strcpy(tempString, szReportsTempFolder);
  strcat(tempString, "\\tmsrpt01.txt");
  hfOutputFile = _lcreat(tempString, 0);
  if(hfOutputFile == HFILE_ERROR)
  {
    LoadString(hInst, ERROR_202, szFormatString, sizeof(szFormatString));
    sprintf(szarString, szFormatString, tempString);
    MessageBeep(MB_ICONSTOP);
    MessageBox((HWND)NULL, szarString, TMS, MB_ICONSTOP);
    goto deallocate;
  }
  strcpy(pPassedData->szReportDataFile[0], tempString);
//
//  Allocate the nodes arrays
//
  pSelectedPatternNodes = (long *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(long) * maxSelectedPatternNodes); 
  if(pSelectedPatternNodes == NULL)
  {
    AllocationError(__FILE__, __LINE__, FALSE);
    goto deallocate;
  }
//
//  Load any header and trailer special characters
//
  LoadHeadersAndTrailers01();
//
//  Loop through the routes
//
  SetCursor(hCursorWait);
  for(nI = 0; nI < REPORTPARMS.numRoutes; nI++)
  {
    ROUTESKey0.recordID = REPORTPARMS.pRouteList[nI];
    rcode2 = btrieve(B_GETEQUAL, TMS_ROUTES, &ROUTES, &ROUTESKey0, 0);
    if(rcode2 != 0)
    {
      continue;
    }
//
//  Loop through the services
//
    for(nJ = 0; nJ < REPORTPARMS.numServices; nJ++)
    {
      SERVICESKey0.recordID = REPORTPARMS.pServiceList[nJ];
      rcode2 = btrieve(B_GETEQUAL, TMS_SERVICES, &SERVICES, &SERVICESKey0, 0);
      if(rcode2 != 0)
      {
        continue;
      }
//
//  Loop through the directions
//
      for(nK = 0; nK < 2; nK++)
      {
        if(ROUTES.DIRECTIONSrecordID[nK] == NO_RECORD)
        {
          continue;
        }
//
//  Find the selected pattern nodes
//
        numSelectedPatternNodes = 0;
        PATTERNNAMESKey0.recordID = REPORTPARMS.PATTERNNAMESrecordID;
        rcode2 = btrieve(B_GETEQUAL, TMS_PATTERNNAMES, &PATTERNNAMES, &PATTERNNAMESKey0, 0);
        if(rcode2 == 0)
        {
          PATTERNSKey2.ROUTESrecordID = REPORTPARMS.pRouteList[nI];
          PATTERNSKey2.SERVICESrecordID = REPORTPARMS.pServiceList[nJ];
          PATTERNSKey2.directionIndex = nK;
          PATTERNSKey2.PATTERNNAMESrecordID = PATTERNNAMES.recordID;
          PATTERNSKey2.nodeSequence = NO_RECORD;
          rcode2 = btrieve(B_GETGREATEROREQUAL, TMS_PATTERNS, &PATTERNS, &PATTERNSKey2, 2);
          while(rcode2 == 0 &&
                PATTERNS.ROUTESrecordID == REPORTPARMS.pRouteList[nI] &&
                PATTERNS.SERVICESrecordID == REPORTPARMS.pServiceList[nJ] &&
                PATTERNS.directionIndex == nK &&
                PATTERNS.PATTERNNAMESrecordID == PATTERNNAMES.recordID)
          {
            if(!(PATTERNS.flags & PATTERNS_FLAG_BUSSTOP))
            {
              pSelectedPatternNodes[numSelectedPatternNodes++] = PATTERNS.NODESrecordID;
              if(numSelectedPatternNodes >= maxSelectedPatternNodes)
              {
                maxSelectedPatternNodes += 50;
                pSelectedPatternNodes = (long *)HeapReAlloc(GetProcessHeap(),
                      HEAP_ZERO_MEMORY, pSelectedPatternNodes, sizeof(long) * maxSelectedPatternNodes); 
                if(pSelectedPatternNodes == NULL)
                {
                  AllocationError(__FILE__, __LINE__, TRUE);
                  goto deallocate;
                }
              }
            }
            rcode2 = btrieve(B_GETNEXT, TMS_PATTERNS, &PATTERNS, &PATTERNSKey2, 2);
          }
        }
        if(numSelectedPatternNodes == 0)
        {
          continue;
        }
//
//  Write out the id record
//
        strcpy(tempString, szRSDHeader);
        strncpy(szarString, ROUTES.number, ROUTES_NUMBER_LENGTH);
        trim(szarString, ROUTES_NUMBER_LENGTH);
        strcat(tempString, szarString);
        strcat(tempString, " ");
        strncpy(szarString, ROUTES.name, ROUTES_NAME_LENGTH);
        trim(szarString, ROUTES_NAME_LENGTH);
        strcat(tempString, szarString);
        strcat(tempString, " ");
        DIRECTIONSKey0.recordID = ROUTES.DIRECTIONSrecordID[nK];
        btrieve(B_GETEQUAL, TMS_DIRECTIONS, &DIRECTIONS, &DIRECTIONSKey0, 0);
        strncpy(szarString, DIRECTIONS.abbrName, DIRECTIONS_ABBRNAME_LENGTH);
        trim(szarString, DIRECTIONS_ABBRNAME_LENGTH);
        strcat(tempString, szarString);
        strcat(tempString, " ");
        strncpy(szarString, SERVICES.name, SERVICES_NAME_LENGTH);
        trim(szarString, SERVICES_NAME_LENGTH);
        strcat(tempString, szarString);
        strcat(tempString, szRSDTrailer);
        strcat(tempString, "\r\n");
        _lwrite(hfOutputFile, tempString, strlen(tempString));
//
//  Write out the number of nodes record
//
        strcpy(tempString, szNumNodesHeader);
        if(strcmp(szNumNodesHeader, "") != 0)
        {
          strcat(tempString, " ");
        }
        sprintf(szarString, "%d", numSelectedPatternNodes);
        strcat(tempString, szarString);
        strcat(tempString, szNumNodesTrailer);
        strcat(tempString, "\r\n");
        _lwrite(hfOutputFile, tempString, strlen(tempString));
//
//  Cycle through, and write out, the pattern nodes
//
        for(nL = 0; nL < numSelectedPatternNodes; nL++)
        {
          strcpy(tempString, szEachNodeHeader);
          NODESKey0.recordID = pSelectedPatternNodes[nL];
          btrieve(B_GETEQUAL, TMS_NODES, &NODES, &NODESKey0, 0);
          strncpy(szarString, NODES.intersection, NODES_INTERSECTION_LENGTH);
          trim(szarString, NODES_INTERSECTION_LENGTH);
          strcat(tempString, szarString);
          strcat(tempString, szEachNodeTrailer);
          strcat(tempString, "\r\n");
          _lwrite(hfOutputFile, tempString, strlen(tempString));
        }  // nL
      }  // nK
    }  // nJ
  }  // nI
  bKeepGoing = TRUE;
//
//  Free allocated memory
//
  deallocate:
    TMSHeapFree(REPORTPARMS.pRouteList);
    TMSHeapFree(REPORTPARMS.pServiceList);
    TMSHeapFree(pSelectedPatternNodes);
    _lclose(hfOutputFile);
    SetCursor(hCursorArrow);
    if(!bKeepGoing)
    {
      return(FALSE);
    }
//
//  All done
//
  return(TRUE);
}
コード例 #5
0
ファイル: xmodem.c プロジェクト: lifangbo/teraterm
BOOL XSendPacket(PFileVar fv, PXVar xv, PComVar cv)
{
	BYTE b;
	int i;
	BOOL SendFlag;
	WORD Check;

	SendFlag = FALSE;
	if (xv->PktBufCount == 0) {
		i = XRead1Byte(fv, xv, cv, &b);
		do {
			if (i == 0)
				return TRUE;
			switch (b) {
			case ACK:
				if (!fv->FileOpen) {
					fv->Success = TRUE;
					return FALSE;
				} else if (xv->PktNumSent == (BYTE) (xv->PktNum + 1)) {
					xv->PktNum = xv->PktNumSent;
					if (xv->PktNum == 0)
						xv->PktNumOffset = xv->PktNumOffset + 256;
					SendFlag = TRUE;
				}
				break;
			case NAK:
				if (xv->PktNum == 0 && xv->XOpt == Xopt1K) {
					/* we wanted 1k with CRC, but the other end specified checksum */
					/* keep the 1k block, but move back to checksum mode.          */
					xv->XOpt = XoptCheck;
					xv->CheckLen = 1;
				}
				SendFlag = TRUE;
				break;
			case CAN:
				break;
			case 0x43:
				if ((xv->PktNum == 0) && (xv->PktNumOffset == 0) && (xv->PktNumSent == 0)) {
					 if ((xv->XOpt == XoptCheck))
						XSetOpt(fv, xv, XoptCRC);
					SendFlag = TRUE;
				}
				break;
			}
			if (!SendFlag)
				i = XRead1Byte(fv, xv, cv, &b);
		} while (!SendFlag);
		// reset timeout timer
		FTSetTimeOut(fv, TimeOutVeryLong);

		do {
			i = XRead1Byte(fv, xv, cv, &b);
		} while (i != 0);

		if (xv->PktNumSent == xv->PktNum) {	/* make a new packet */
			xv->PktNumSent++;
			if (xv->DataLen == 128)
				xv->PktOut[0] = SOH;
			else
				xv->PktOut[0] = STX;
			xv->PktOut[1] = xv->PktNumSent;
			xv->PktOut[2] = ~xv->PktNumSent;

			i = 1;
			while ((i <= xv->DataLen) && fv->FileOpen &&
				   (_lread(fv->FileHandle, &b, 1) == 1)) {
				xv->PktOut[2 + i] = b;
				i++;
				fv->ByteCount++;
			}

			if (i > 1) {
				while (i <= xv->DataLen) {
					xv->PktOut[2 + i] = 0x1A;
					i++;
				}

				Check = XCalcCheck(xv, xv->PktOut);
				if (xv->CheckLen == 1)	/* Checksum */
					xv->PktOut[xv->DataLen + 3] = (BYTE) Check;
				else {
					xv->PktOut[xv->DataLen + 3] = HIBYTE(Check);
					xv->PktOut[xv->DataLen + 4] = LOBYTE(Check);
				}
				xv->PktBufCount = 3 + xv->DataLen + xv->CheckLen;
			} else {			/* send EOT */
				if (fv->FileOpen) {
					_lclose(fv->FileHandle);
					fv->FileHandle = 0;
					fv->FileOpen = FALSE;
				}
				xv->PktOut[0] = EOT;
				xv->PktBufCount = 1;
			}
		} else {				/* resend packet */
			if (xv->PktOut[0] == EOT) {
				xv->PktBufCount = 1;
			} else {
				xv->PktBufCount = 3 + xv->DataLen + xv->CheckLen;
			}
		}
		xv->PktBufPtr = 0;
	}
	/* a NAK or C could have arrived while we were buffering.  Consume it. */
	do {
		i = XRead1Byte(fv, xv, cv, &b);
	} while (i != 0);

	i = 1;
	while ((xv->PktBufCount > 0) && (i > 0)) {
		b = xv->PktOut[xv->PktBufPtr];
		i = XWrite(fv, xv, cv, &b, 1);
		if (i > 0) {
			xv->PktBufCount--;
			xv->PktBufPtr++;
		}
	}

	if (xv->PktBufCount == 0) {
		if (xv->PktNumSent == 0) {
			SetDlgNum(fv->HWin, IDC_PROTOPKTNUM, xv->PktNumOffset + 256);
		}
		else {
			SetDlgNum(fv->HWin, IDC_PROTOPKTNUM, xv->PktNumOffset + xv->PktNumSent);
		}
		SetDlgNum(fv->HWin, IDC_PROTOBYTECOUNT, fv->ByteCount);
		SetDlgPercent(fv->HWin, IDC_PROTOPERCENT, IDC_PROTOPROGRESS,
		              fv->ByteCount, fv->FileSize, &fv->ProgStat);
		SetDlgTime(fv->HWin, IDC_PROTOELAPSEDTIME, fv->StartTime, fv->ByteCount);
	}

	return TRUE;
}
コード例 #6
0
ファイル: OPEN.C プロジェクト: dtison/imageprep
int OpenImage (int nFlags, LONG lParam)
{
    FARPROC   lpfnOpenDlg;
    int       hInFile = 0;                   
    int       nError = EC_ERROR;             
    int       nFileType;                
    OFSTRUCT  Of;
    ATOM  Atom;
    WORD  wBytes;
    int         hTempFile;
    int         nErr = FALSE;

    /*  First get szOpenFileName filled in   */

    switch (nFlags)
    {
        case SCAN_OPEN:
            CleanFiles ();
            Atom = (ATOM) LOWORD (lParam);
            wBytes = GlobalGetAtomName (Atom, szOpenFileName, 128);
            GlobalDeleteAtom (Atom);
            GetNameFromPath ((LPSTR) szImageName, (LPSTR) szOpenFileName);
            bIsCurrTemp = FALSE;
            bImageModified = FALSE;
        break;

        case USER_OPEN:
    //      CleanFiles ();  BUG HERE????
            lpfnOpenDlg = MakeProcInstance ((FARPROC)OpenDlgProc, hInstIP);
            hInFile = DialogBox (hInstIP, "FILEDLG", hWndIP, lpfnOpenDlg);
            FreeProcInstance (lpfnOpenDlg);
            if (hInFile)
            {
                CleanFiles ();          // Put here instead of before call to dialog
                _lclose (hInFile);      // Kludge..

                /*  Always get image name from path.  Optionally also update the szOpenDir  */

                GetNameFromPath ((LPSTR) szImageName, (LPSTR) szOpenFileName);

                if (szOpenFileName [1] == ':')  // Look for A: or B:, if neither, remember open drive/directory
                {
                    if (! (szOpenFileName [0] == 'A' || szOpenFileName[0] == 'B' || szOpenFileName[0] == 'a' || szOpenFileName[0] == 'b'))
                    {
                        SeparateFile ((LPSTR) szOpenDir, (LPSTR) szImageName, (LPSTR)szOpenFileName);
                        _fstrcpy ((LPSTR) szSaveDir, (LPSTR) szOpenDir);
                    }
                }

                bIsCurrTemp = FALSE;


            }
            else
                nErr = USER_ABANDON;
            bImageModified = FALSE;
        break;

        case COMMAND_LINE_OPEN:
            CleanFiles ();
            _fstrcpy ((LPSTR)szOpenFileName, (LPSTR) lParam);
            GetNameFromPath ((LPSTR) szImageName, (LPSTR) szOpenFileName);
            bIsCurrTemp = FALSE;
            bImageModified = FALSE;
        break;

        case TOOLS_OPEN:
            _fstrcpy ((LPSTR)szOpenFileName, (LPSTR) lParam);
            bIsCurrTemp = TRUE;
        break;

        case OIC_OPEN:
        case AUTO_CONVERT_OPEN:
            _fstrcpy ((LPSTR)szOpenFileName, (LPSTR) lParam);
            bIsCurrTemp = TRUE;
            bImageModified = FALSE;
        break;

        case CLIPBOARD_OPEN:
            CleanFiles ();
            Atom = (ATOM) LOWORD (lParam);
            wBytes = GlobalGetAtomName (Atom, szOpenFileName, 128);
            GlobalDeleteAtom (Atom);
            _fstrcpy ((LPSTR) szImageName, (LPSTR) "Untitled");
            bIsCurrTemp = TRUE;
            bImageModified = FALSE;
        break;

        case GENERIC_OPEN:
        case UNDO_OPEN:
            _fstrcpy ((LPSTR)szOpenFileName, (LPSTR) lParam);
        break;

    }

    if (nErr != 0)
        return (nErr);

    hInFile = OpenFile ((LPSTR)szOpenFileName, (LPOFSTRUCT)&Of, OF_READWRITE);

    if (hInFile <= 0)
    {
        if (hInFile == 0)
        hInFile = IDCANCEL;
        nError = hInFile;
        return (nError);
    }

    /* Identify and Import File    */

    if (image_active)
    {
        _fstrcpy ((LPSTR) szTempPath,  (LPSTR) szOpenFileName);     // Store it somewhere

        SendMessage (hWndDisplay, WM_CLOSE, 0, 0);    // Close that baby down!

        if (nFlags == USER_OPEN)                      // So we don't re-display dialog
            nFlags = COMMAND_LINE_OPEN;
        else
            if (nFlags == CLIPBOARD_OPEN)
                nFlags = GENERIC_OPEN;                   

        _lclose (hInFile);

        PostMessage (hWndIP, WM_SHOWIMAGE, nFlags, (LONG) (LPSTR) szTempPath); // Re-prime the pump

        return (0);
    }

    _fstrcpy ((LPSTR) szCurrFileName, (LPSTR) szOpenFileName);  // For having UNDO cap.  5/91

    _llseek (hInFile, 0L, 0);

    nFileType = IdentFormat (hInFile, (LPSTR) szOpenFileName);
    if (nFileType < 0)
    {
        /* File type unknown    */

        _lclose (hInFile);
        hImportFile = 0; 
        return (nFileType);
    }

        switch (nFileType)
        {
            case IDFMT_CCPI:
            {
                char Buffer [128];

                GetTempFileName (0, (LPSTR) "OIC", 0, (LPSTR) Buffer);
                #ifndef DECIPHER
                /* If file type is compressed cpi, decompress first, then re-open     */
                hTempFile = DecompressCPI (hInFile ,(LPSTR) Buffer);
                if (hTempFile > 0)
                {
                    _lclose (hInFile);
                    return (OpenImage (OIC_OPEN, (LONG) (LPSTR) Buffer));
                }
                else
                    return (hTempFile);
    
            }
                #else
            return (EC_UFILETYPE);
                #endif
            break;
    
            case IDFMT_WMF:
            {
                char Buffer [128];
                WORD Retval;

                wUserImportType = (WORD) nFileType;
                GetTempFileName (0, (LPSTR) "WMF", 0, (LPSTR) Buffer);
                Retval = wmfImportMetaFile (hWndIP, hInFile, (LPSTR) Buffer);
                if (Retval == 0)
                {
                    _lclose (hInFile);
                    return (OpenImage (OIC_OPEN, (LONG) (LPSTR) Buffer));
                }
                else
                    return (USER_ABANDON);
    
            }
            break;

            case IDFMT_CPI:
            break;
    
            default:
    
            if (bDoDisplay)           // If we are going to actually display the thing, we may need to do some stuff first..
            if (bAutoConvert)
            {
                /*  Now if opened image is not CPI, save as CPI and re-open as CPI  */
    
                if (wImportType != IDFMT_CPI)
                    if (bAutoConvert)
                    {
                        wUserImportType = (WORD) nFileType;
                        hImportFile = hInFile;
                        SetState (IMPORT_TYPE, nFileType);  
                        nError = ImportFile();
                        if (nError != 0)
                            return (nError);
                        else
                            return (DoSave (SAVE_TO_CPI)); 
                    }
            }
            break;
        }

    hImportFile = hInFile;      
    SetState (IMPORT_TYPE, nFileType);  
    if (! wUserImportType)
        wUserImportType = wImportType;
    nError = ImportFile();

    if (nError >= 0)
        if (! bDoDisplay)
            PostMessage (hWndIP, WM_COMMAND, IDM_SAVE, 0L);

    return (nError);
}
コード例 #7
0
ファイル: FILE.CPP プロジェクト: chrisoldwood/WIN16
CFile::~CFile(void)
{
	if (m_hFile != HFILE_ERROR)
		_lclose(m_hFile);
}
コード例 #8
0
ファイル: ACKPCX.C プロジェクト: meh2481/ACK-3D-GCC
//=============================================================================
//  This routine loads a 256 color PCX file. The file can be a standalone
// PCX file or it can be combined with a resource. If the data is part
// of a resource, the rshandle flag will be set. The bitmap data is read
// into a buffer that is the size of the bitmap + 4 bytes. The first 4
// bytes in the buffer contain the width and height of the bitmap.
//=============================================================================
unsigned char *AckReadPCX(char *filename)
{
    int32_t i;
    int mode=NORMAL,nbytes;
    char abyte,*p;
    short   handle;
    PcxFile *pcx;

pcx = &pcxGlobal;
// Open the file since no resource is open.
if (!rsHandle)
    {
    handle = _lopen(filename,OF_READ); // Open the file for reading
    if (handle == HFILE_ERROR) // Make sure file is opened
        {
        ErrorCode = ERR_BADFILE;
        return NULL;
        }
    }
else // Use the resource instead
    {
    handle = rsHandle; // Use the handle to the resource file
    // Move to the location in the resource where the data is stored
    _llseek(handle,(int)(rbaTable[(int64_t)filename]),SEEK_SET);
    }


_lread(handle,&pcx->hdr,sizeof(PcxHeader)); // Read in the header data
pcx->width=1+pcx->hdr.xmax-pcx->hdr.xmin;   // Store width and height
pcx->height=1+pcx->hdr.ymax-pcx->hdr.ymin;
// Store number of bytes used for image
pcx->imagebytes=(unsigned int)(pcx->width*pcx->height);

// Make sure bitmap is correct size
if (pcx->imagebytes > PCX_MAX_SIZE)
    {
    if (!rsHandle)
        _lclose(handle);
    ErrorCode = ERR_INVALIDFORM;
    return(NULL);
    }

// Allocate size for bitmap. 4 extra bytes are included to give
// room to store bitmap width and height info.
pcx->bitmap=(UCHAR*)AckMalloc(pcx->imagebytes+4);

if (pcx->bitmap == NULL)    // Make sure memory is allocated
    {
    if (!rsHandle)
        _lclose(handle);
    ErrorCode = ERR_NOMEMORY;
    return(NULL);
    }
p=(char*)(&pcx->bitmap[4]);      // Get address of data area

// Loop and read in pixel data for bitmap
// Uses RLE decompression
for (i=0;i<pcx->imagebytes;i++)
    {
    if (mode == NORMAL)     // Normal color read mode
        {
        _lread(handle,&abyte,1);    // Read in pixel value from file
        if ((unsigned char)abyte > 0xbf) // Value read > 191
            {
            nbytes=abyte & 0x3f;    // Get the RLE counter
            _lread(handle,&abyte,1);
            if (--nbytes > 0)       // Is counter greater than 1?
                mode=RLE;           // Yes, we're in RLE mode
            }
        }
    else if (--nbytes == 0)         // When counter down to 0
            mode=NORMAL;            // return to color read mode
    *p++=abyte;                     // Store pixel value
    }

// Get palette from PCX file, 256 color palette store 768 bytes from
// end of file. For a resource file we need to find the position where
// the next file starts and then backup 768 bytes
if (rsHandle)
    _llseek(handle,(int)(rbaTable[(int64_t)(filename + 1)])-768,SEEK_CUR);
else
    _llseek(handle,-768,SEEK_END);

// Store the palette data in our global colordat array
_lread(handle,colordat,768);
p=(char*)colordat;
for (i=0;i<768;i++)            // bit shift palette
    *p++ = *p >> 2;

if (!rsHandle)                  // Close pcx file if not using a resource
    _lclose(handle);

// Add in bitmap width and height to first 4 bytes of buffer
p = (char*)pcx->bitmap;
(*(short *)p) = pcx->width;
p += sizeof(short);
(*(short *)p) = pcx->height;

return(pcx->bitmap);         // return bitmap buffer
}
コード例 #9
0
ファイル: TMSRpt73.c プロジェクト: ems/TMS
BOOL FAR TMSRPT73(TMSRPTPassedDataDef *pPassedData)
{
  CombinedDef Combined[TMSRPT73_MAXROUTES];
  HFILE hfOutputFile;
  BOOL  bKeepGoing = FALSE;
  BOOL  bFound;
  char  outputString[512];
  long  tempLong;
  long  fromDate, toDate;
  long  year, month,day;
  int   nI;
  int   nJ;
  int   nK;
  int   rcode2;
  int   numCombined;

  pPassedData->nReportNumber = 72;
  pPassedData->numDataFiles = 1;
//
//  See what he wants
//
  if(!GetDateRange(&fromDate, &toDate))
  {
    return(FALSE);
  }
//
//  Open the output file
//
  strcpy(tempString, szReportsTempFolder);
  strcat(tempString, "\\TMSRPT73.txt");
  hfOutputFile = _lcreat(tempString, 0);
  if(hfOutputFile == HFILE_ERROR)
  {
    LoadString(hInst, ERROR_202, szFormatString, sizeof(szFormatString));
    sprintf(szarString, szFormatString, tempString);
    MessageBeep(MB_ICONSTOP);
    MessageBox((HWND)NULL, szarString, TMS, MB_ICONSTOP);
    goto deallocate;
  }
  strcpy(pPassedData->szReportDataFile[0], tempString);
//
//  Go through the audit trail to get the ridership numbers
//
  StatusBarStart(hWndMain, "Unloading Ridership Data");
  for(tempLong = fromDate; tempLong <= toDate; tempLong++)
  {
    if(StatusBarAbort())
    {
      bKeepGoing = FALSE;
      goto deallocate;
    }
    for(nI = 0; nI < TMSRPT73_MAXROUTES; nI++)
    {
      Combined[nI].ROUTESrecordID = NO_RECORD;
      Combined[nI].RUNSrecordID = NO_RECORD;
      for(nJ = 0; nJ < 4; nJ++)
      {
        Combined[nI].numFares[nJ] = 0;
        Combined[nI].fareValue[nJ] = 0;
      }
      Combined[nI].mileageOut = 0.0;
      Combined[nI].mileageIn  = 0.0;
    }
    numCombined = 0;
    DAILYOPSKey1.recordTypeFlag = DAILYOPS_FLAG_RIDERSHIP;
    DAILYOPSKey1.pertainsToDate = tempLong;
    DAILYOPSKey1.pertainsToTime = 0;
    DAILYOPSKey1.recordFlags = 0;
    bFound = FALSE;
    rcode2 = btrieve(B_GETGREATEROREQUAL, TMS_DAILYOPS, &DAILYOPS, &DAILYOPSKey1, 1);
    while(rcode2 == 0 &&
          (DAILYOPS.recordTypeFlag & DAILYOPS_FLAG_RIDERSHIP) &&
           DAILYOPS.pertainsToDate == tempLong)
    {
      if(DAILYOPS.recordFlags & DAILYOPS_FLAG_SETRIDERSHIP)
      {
        if(!ANegatedRecord(DAILYOPS.recordID, 1))
        {
          TRIPSKey0.recordID = DAILYOPS.DOPS.Ridership.R.TRIPSrecordID;
          rcode2 = btrieve(B_GETEQUAL, TMS_TRIPS, &TRIPS, &TRIPSKey0, 0);
          for(nI = 0; nI < numCombined; nI++)
          {
            if(Combined[nI].ROUTESrecordID == TRIPS.ROUTESrecordID)
            {
              bFound = TRUE;
              break;
            }
          }
          if(!bFound)
          {
            nI = numCombined;
            Combined[nI].ROUTESrecordID = TRIPS.ROUTESrecordID;
            Combined[nI].RUNSrecordID = DAILYOPS.DOPS.Ridership.R.RUNSrecordID;
            numCombined++;
          }
          for(nJ = 0; nJ < 4; nJ++)
          {
            Combined[nI].numFares[nJ] += DAILYOPS.DOPS.Ridership.R.numFares[nJ];
          }
        }
      }
      rcode2 = btrieve(B_GETNEXT, TMS_DAILYOPS, &DAILYOPS, &DAILYOPSKey1, 1);
    }
//
//  Get the fare values for each of the routes
//
    for(nI = 0; nI < numCombined; nI++)
    {
      for(bFound = FALSE, nJ = 0; nJ < m_numFareTypesByRoute; nJ++)
      {
        if(Combined[nI].ROUTESrecordID == m_FareTypesByRoute[nJ].ROUTESrecordID)
        {
          bFound = TRUE;
          break;
        }
      }
      if(bFound)
      {
        for(nK = 0; nK < 4; nK++)
        {
          Combined[nI].fareValue[nK] = m_FareTypesByRoute[nJ].fareValue[nK];
        }
      } 
    }
//
//  Get the mileage for this run
//
    DAILYOPSKey1.recordTypeFlag = DAILYOPS_FLAG_RIDERSHIP;
    DAILYOPSKey1.pertainsToDate = tempLong;
    DAILYOPSKey1.pertainsToTime = 0;
    DAILYOPSKey1.recordFlags = 0;
    bFound = FALSE;
    rcode2 = btrieve(B_GETGREATEROREQUAL, TMS_DAILYOPS, &DAILYOPS, &DAILYOPSKey1, 1);
    while(rcode2 == 0 &&
          (DAILYOPS.recordTypeFlag & DAILYOPS_FLAG_RIDERSHIP) &&
           DAILYOPS.pertainsToDate == tempLong)
    {
      if(DAILYOPS.recordFlags & DAILYOPS_FLAG_SETMILEAGE)
      {
        if(!ANegatedRecord(DAILYOPS.recordID, 1))
        {
          for(nI = 0; nI < numCombined; nI++)
          {
            if(Combined[nI].RUNSrecordID == DAILYOPS.DOPS.Ridership.M.RUNSrecordID)
            {
              bFound = TRUE;
              break;
            }
          }
          if(bFound)
          {
            Combined[nI].mileageOut = DAILYOPS.DOPS.Ridership.M.mileageOut;
            Combined[nI].mileageIn = DAILYOPS.DOPS.Ridership.M.mileageIn;
          }
        }
      }
      rcode2 = btrieve(B_GETNEXT, TMS_DAILYOPS, &DAILYOPS, &DAILYOPSKey1, 1);
    }
//
//  Loop through Combined
//
    for(nI = 0; nI < numCombined; nI++)
    {
//
//  Route number
//
      ROUTESKey0.recordID = Combined[nI].ROUTESrecordID;
      rcode2 = btrieve(B_GETEQUAL, TMS_ROUTES, &ROUTES, &ROUTESKey0, 0);
      strncpy(tempString, ROUTES.number, ROUTES_NUMBER_LENGTH);
      trim(tempString, ROUTES_NUMBER_LENGTH);
      strcpy(outputString, tempString);
      strcat(outputString, "\t");
//
//  Route name
//
      strncpy(tempString, ROUTES.name, ROUTES_NAME_LENGTH);
      trim(tempString, ROUTES_NAME_LENGTH);
      strcat(outputString, tempString);
      strcat(outputString, "\t");
//
//  Date
//
      GetYMD(tempLong, &year, &month, &day);
      sprintf(tempString, "%02ld/%02ld/%ld", month, day, year);
      strcat(outputString, tempString);
      strcat(outputString, "\t");
//
//  Cash received
//
      for(nJ = 0; nJ < 4; nJ++)
      {
        sprintf(tempString, "%6.02f", Combined[nI].numFares[nJ] * Combined[nI].fareValue[nJ]);
        strcat(outputString, tempString);
        strcat(outputString, "\t");
      }
//
//  Number of fares
//
      for(nJ = 0; nJ < 4; nJ++)
      {
        sprintf(tempString, "%d", Combined[nI].numFares[nJ]);
        strcat(outputString, tempString);
        strcat(outputString, "\t");
      }
//
//  Mileage
//
      sprintf(tempString, "%8.1f", Combined[nI].mileageOut);
      strcat(outputString, tempString);
      strcat(outputString, "\t");
      sprintf(tempString, "%8.1f", Combined[nI].mileageIn);
      strcat(outputString, tempString);
      strcat(outputString, "\r\n");
//
//  Write it out
//
      _lwrite(hfOutputFile, outputString, strlen(outputString));
    }
  } // tempLong

  bKeepGoing = TRUE;
//
//  Free allocated memory
//
  deallocate:
    _lclose(hfOutputFile);
    StatusBarEnd();
    if(!bKeepGoing)
    {
      return(FALSE);
    }
//
//  All done
//
  return(TRUE);
}
コード例 #10
0
ファイル: diamond.c プロジェクト: mingpen/OpenNT
int
DIAMONDAPI
DiamondNotifyFunction(
    IN FDINOTIFICATIONTYPE Operation,
    IN PFDINOTIFICATION    Parameters
    )
{
    switch(Operation) {

    case fdintCABINET_INFO:
    case fdintNEXT_CABINET:
    case fdintPARTIAL_FILE:

        //
        // Cabinet management functions which we don't use.
        // Return success.
        //
        return(0);

    case fdintCOPY_FILE:

        //
        // Diamond is asking us whether we want to copy the file.
        //
        {
            PDIAMOND_INFO Info = (PDIAMOND_INFO)Parameters->pv;
            HFILE h;

            //
            // If we need to rename the target file, do that here.
            // The name stored in the cabinet file will be used as
            // the uncompressed name.
            //
            if(Info->RenameTargetFile) {

                PSTR p,q;

                //
                // Find the start of the filename part of the target.
                //
                if(p = StringRevChar(Info->TargetFileName,'\\')) {
                    p++;
                } else {
                    p = Info->TargetFileName;
                }

                //
                // Find the start of the filename part of the name in the cabinet.
                //
                if(q = StringRevChar(Parameters->psz1,'\\')) {
                    q++;
                } else {
                    q = Parameters->psz1;
                }

                //
                // Copy the filename part of the name in the cabinet over
                // the filename part of the name in the target spec.
                //
                lstrcpy(p,q);
            }

            //
            // Inform the expand callback what we are doing.
            //
            if(!Info->ExpandNotify(Info->SourceFileName,Info->TargetFileName,NOTIFY_START_EXPAND)) {
                return(0);  // skip this file.
            }

            //
            // Remember the uncompressed size and open the file.
            // Returns -1 if an error occurs opening the file.
            //
            Info->pLZI->cblOutSize = Parameters->cb;
            h = _lcreat(Info->TargetFileName,0);
            if(h == HFILE_ERROR) {
                DiamondLastIoError = LZERROR_BADOUTHANDLE;
                return(-1);
            }
            return(h);
        }

    case fdintCLOSE_FILE_INFO:

        //
        // Diamond is done with the target file and wants us to close it.
        // (ie, this is the counterpart to fdint_COPY_FILE).
        //
        {
            PDIAMOND_INFO Info = (PDIAMOND_INFO)Parameters->pv;

            CopyDateTimeStamp(Info->SourceFileHandle,Parameters->hf);
            _lclose(Parameters->hf);
        }
        return(TRUE);
    }
}
コード例 #11
0
ファイル: FILE.C プロジェクト: willmomo/ry2kojima
WORD FAR SaveDIB(HDIB hDib, LPSTR lpFileName)
{
   BITMAPFILEHEADER bmfHdr; // Header for Bitmap file
   LPBITMAPINFOHEADER lpBI;   // Pointer to DIB info structure
   int fh;     // file handle for opened file
   OFSTRUCT of;     // OpenFile structure
   DWORD dwDIBSize;
   DWORD dwError;   // Error return from MyWrite

   if (!hDib)
      return ERR_INVALIDHANDLE;
   fh = OpenFile(lpFileName, &of, OF_CREATE | OF_READWRITE);
   if (fh == -1)
      return ERR_OPEN;

   /*
    * Get a pointer to the DIB memory, the first of which contains
    * a BITMAPINFO structure
    */
   lpBI = (LPBITMAPINFOHEADER)GlobalLock(hDib);
   if (!lpBI)
      return ERR_LOCK;

   // Check to see if we're dealing with an OS/2 DIB.  If so, don't
   // save it because our functions aren't written to deal with these
   // DIBs.

   if (lpBI->biSize != sizeof(BITMAPINFOHEADER))
   {
     GlobalUnlock(hDib);
     return ERR_NOT_DIB;
   }

   /*
    * Fill in the fields of the file header
    */

   /* Fill in file type (first 2 bytes must be "BM" for a bitmap) */
   bmfHdr.bfType = DIB_HEADER_MARKER;  // "BM"

   // Calculating the size of the DIB is a bit tricky (if we want to
   // do it right).  The easiest way to do this is to call GlobalSize()
   // on our global handle, but since the size of our global memory may have
   // been padded a few bytes, we may end up writing out a few too
   // many bytes to the file (which may cause problems with some apps,
   // like HC 3.0).
   //
   // So, instead let's calculate the size manually.
   //
   // To do this, find size of header plus size of color table.  Since the
   // first DWORD in both BITMAPINFOHEADER and BITMAPCOREHEADER conains
   // the size of the structure, let's use this.

   dwDIBSize = *(LPDWORD)lpBI + PaletteSize((LPSTR)lpBI);  // Partial Calculation

   // Now calculate the size of the image

   if ((lpBI->biCompression == BI_RLE8) || (lpBI->biCompression == BI_RLE4)) {

      // It's an RLE bitmap, we can't calculate size, so trust the
      // biSizeImage field

      dwDIBSize += lpBI->biSizeImage;
      }
   else {
      DWORD dwBmBitsSize;  // Size of Bitmap Bits only

      // It's not RLE, so size is Width (DWORD aligned) * Height

      dwBmBitsSize = WIDTHBYTES((lpBI->biWidth)*((DWORD)lpBI->biBitCount)) * lpBI->biHeight;

      dwDIBSize += dwBmBitsSize;
      
      // Now, since we have calculated the correct size, why don't we
      // fill in the biSizeImage field (this will fix any .BMP files which 
      // have this field incorrect).

      lpBI->biSizeImage = dwBmBitsSize;
      }


   // Calculate the file size by adding the DIB size to sizeof(BITMAPFILEHEADER)
                   
   bmfHdr.bfSize = dwDIBSize + sizeof(BITMAPFILEHEADER);
   bmfHdr.bfReserved1 = 0;
   bmfHdr.bfReserved2 = 0;

   /*
    * Now, calculate the offset the actual bitmap bits will be in
    * the file -- It's the Bitmap file header plus the DIB header,
    * plus the size of the color table.
    */
   bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + lpBI->biSize +
                      PaletteSize((LPSTR)lpBI);

   /* Write the file header */
   _lwrite(fh, (LPSTR)&bmfHdr, sizeof(BITMAPFILEHEADER));

   /*
    * Write the DIB header and the bits -- use local version of
    * MyWrite, so we can write more than 32767 bytes of data
    */
   dwError = MyWrite(fh, (LPSTR)lpBI, dwDIBSize);
   GlobalUnlock(hDib);
   _lclose(fh);

   if (dwError == 0)
     return ERR_OPEN; // oops, something happened in the write
   else
     return 0; // Success code
}
コード例 #12
0
BOOL CDDB::ConstructDDBFromFile(		// build a CDDB object from a DIB in a file
	LPCSTR lpszFileName,						// name of file containing DIB data
	HDC hDC,										// device context to use for call to CreateDIBitmap()
	BOOL fUseDIBPalette,						// flag indicating if DIB bitmap should be used for conversion
	HPALETTE hPalette)
{
	/*
	// Attempt to open the file and read in the BITMAPFILEHEADER structure.
	*/
		
	OFSTRUCT of;
	HFILE hfDIB;
		
	if ((hfDIB = OpenFile(lpszFileName, &of, OF_READ|OF_SHARE_DENY_WRITE)) != HFILE_ERROR)
	{
		BITMAPFILEHEADER BitmapFileHeader;
			
		if (_lread(hfDIB, &BitmapFileHeader, sizeof(BitmapFileHeader)) == sizeof(BitmapFileHeader))
		{
			/*
			// Validate the header.
			*/
				
			if (BitmapFileHeader.bfType == 0x4d42)
			{
				/*
				// Read in the rest of the file.
				*/
					
				HGLOBAL hDIB;
				long dwDIBSize;
					
				dwDIBSize = BitmapFileHeader.bfSize-sizeof(BitmapFileHeader);
					
				if ((hDIB = GlobalAlloc(GMEM_MOVEABLE, dwDIBSize)) != NULL)
				{
					LPBITMAPINFOHEADER lpHeader;
			
					if ((lpHeader = (LPBITMAPINFOHEADER)GlobalLock(hDIB)) != NULL)
					{
						if (_hread(hfDIB, lpHeader, dwDIBSize) == dwDIBSize)
						{
							/*
							// Validate the header size.
							*/
								
							if (lpHeader->biSize == sizeof(BITMAPINFOHEADER))
							{
								/*
								// Create the DDB.
								*/
									
								ConstructDDB(			// construct a DDB from the DIB data
									lpHeader,				// pointer to BITMAPINFOHEADER structure
									hDC,						// device context to use for call to CreateDIBitmap()
									fUseDIBPalette,		// flag indicating if DIB bitmap should be used for conversion
									hPalette);
							}
						}
							
						GlobalUnlock(hDIB);
						lpHeader = NULL;
					}
						
					GlobalFree(hDIB);
					hDIB = NULL;
				}
			}
		}
			
		_lclose(hfDIB);
		hfDIB = HFILE_ERROR;
	}
	
	return IsValid();
}
コード例 #13
0
ファイル: PisteDraw.cpp プロジェクト: piotrulos/PK2remakes
int PisteDraw_Load_Bitmap(BITMAP_FILE_PTR bitmap, char *filename)
{
	int file_handle,  
		index;				

	UCHAR   *temp_buffer = NULL; 
	OFSTRUCT file_data; 

	if ((file_handle = OpenFile(filename,&file_data,OF_READ)) == -1)
		return 1; 

	_lread(file_handle, &bitmap->bitmapfileheader,sizeof(BITMAPFILEHEADER));
	
	if (bitmap->bitmapfileheader.bfType!=BITMAP_ID)
	{
		_lclose(file_handle);
		return 2;
	}

	_lread(file_handle, &bitmap->bitmapinfoheader,sizeof(BITMAPINFOHEADER));

	if (bitmap->bitmapinfoheader.biBitCount == 8)
	{
		_lread(file_handle, &bitmap->paletti, PD_max_varit*sizeof(PALETTEENTRY));

		for (index=0; index < PD_max_varit; index++)
		{
			// reverse the red and green fields
			int temp_color                = bitmap->paletti[index].peRed;
			bitmap->paletti[index].peRed  = bitmap->paletti[index].peBlue;
			bitmap->paletti[index].peBlue = temp_color;
       
			bitmap->paletti[index].peFlags = PC_NOCOLLAPSE;
		} 

    } 

	_lseek(file_handle,-(int)(bitmap->bitmapinfoheader.biSizeImage),SEEK_END);

	if (bitmap->bitmapinfoheader.biBitCount==8 || bitmap->bitmapinfoheader.biBitCount==16 || 
		bitmap->bitmapinfoheader.biBitCount==24)
	{

		if (!(bitmap->buffer = (UCHAR *)malloc(bitmap->bitmapinfoheader.biSizeImage)))
		{
			_lclose(file_handle);

			return 3;
		} 

		_lread(file_handle,bitmap->buffer,bitmap->bitmapinfoheader.biSizeImage);

	}
	else
		return 4;

	_lclose(file_handle);

	PisteDraw_Flip_Bitmap(bitmap->buffer, 
				bitmap->bitmapinfoheader.biWidth*(bitmap->bitmapinfoheader.biBitCount/8), 
				bitmap->bitmapinfoheader.biHeight);
	return 0;
} 
コード例 #14
0
ファイル: wprinter.c プロジェクト: mojca/gnuplot-new
/* Print File to port */
void WDPROC
DumpPrinter(HWND hwnd, LPSTR szAppName, LPSTR szFileName)
{
#define PRINT_BUF_SIZE 4096
    char *buffer;
    char *portname;
    int i, iport;
    DLGPROC lpfnSpoolProc;
    HPJOB hJob;
    UINT count;
    HFILE hf;
    int error = FALSE;
    DLGPROC lpfnCancelProc;
    long lsize;
    long ldone;
    char pcdone[10];
    MSG msg;
    HWND hDlgModeless;

    if ((buffer = LocalAllocPtr(LHND, PRINT_BUF_SIZE)) == (char *)NULL)
	return;
    /* get list of ports */
    GetProfileString("ports", NULL, "", buffer, PRINT_BUF_SIZE);
    /* select a port */
    lpfnSpoolProc = (DLGPROC)MakeProcInstance((FARPROC)SpoolDlgProc, hdllInstance);
    iport = DialogBoxParam(hdllInstance, "SpoolDlgBox", hwnd, lpfnSpoolProc, (LPARAM)buffer);
    FreeProcInstance((FARPROC)lpfnSpoolProc);
    if (!iport) {
	LocalFreePtr((void NEAR *)buffer);
	return;
    }
    portname = buffer;
    for (i=1; i<iport && lstrlen(portname)!=0; i++)
	portname += lstrlen(portname)+1;

    /* open file and get length */
    hf = _lopen(szFileName, OF_READ);
    if (hf == HFILE_ERROR) {
	LocalFreePtr((void NEAR *)buffer);
	return;
    }
    lsize = _llseek(hf, 0L, 2);
    (void) _llseek(hf, 0L, 0);
    if (lsize <= 0)
	lsize = 1;

    hJob = OpenJob(portname, szFileName, (HDC)NULL);
    switch ((int)hJob) {
    case SP_APPABORT:
    case SP_ERROR:
    case SP_OUTOFDISK:
    case SP_OUTOFMEMORY:
    case SP_USERABORT:
	_lclose(hf);
	LocalFreePtr((void NEAR *)buffer);
	return;
    }
    if (StartSpoolPage(hJob) < 0)
	error = TRUE;

    ldone = 0;
    lpfnCancelProc = (DLGPROC)MakeProcInstance((FARPROC)CancelDlgProc, hdllInstance);
    hDlgModeless = CreateDialogParam(hdllInstance, "CancelDlgBox", hwnd, lpfnCancelProc, (LPARAM)szAppName);

    while (!error && hDlgModeless && IsWindow(hDlgModeless)
	   && ((count = _lread(hf, buffer, PRINT_BUF_SIZE))!= 0) ) {
	wsprintf(pcdone, "%d%% done", (int)(ldone * 100 / lsize));
	SetWindowText(GetDlgItem(hDlgModeless, CANCEL_PCDONE), pcdone);
	if (WriteSpool(hJob, buffer, count) < 0)
	    error = TRUE;
	ldone += count;
	while (IsWindow(hDlgModeless) && PeekMessage(&msg, hDlgModeless, 0, 0, PM_REMOVE)) {
	    if (!IsDialogMessage(hDlgModeless, &msg)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	    }
	}
    }
    LocalFreePtr((void NEAR *)buffer);
    _lclose(hf);

    if (!hDlgModeless || !IsWindow(hDlgModeless))
	error=TRUE;
    if (IsWindow(hDlgModeless))
	DestroyWindow(hDlgModeless);
    hDlgModeless = 0;
    FreeProcInstance((FARPROC)lpfnCancelProc);
    EndSpoolPage(hJob);
    if (error)
	DeleteJob(hJob, 0);
    else
	CloseJob(hJob);
}
コード例 #15
0
ファイル: spy.c プロジェクト: mingpen/OpenNT
LRESULT CALLBACK
SpyWndProc(
    HWND hwnd,
    UINT msg,
    WPARAM wParam,
    LPARAM lParam
    )
{
    switch (msg)
    {
        case WM_CREATE:
            MyCreatePrintfWin(hwnd);
            return 0;

        case WM_INITMENU:
            if (GetMenu(ghwndSpyApp) == (HMENU)wParam)
                InitMenu((HMENU)wParam);

            break;

        case WM_COMMAND:
            return SpyCommand(hwnd, LOWORD(wParam), HIWORD(wParam));

        case WM_ACTIVATE:
            /*
             * Set the focus to the printf window if we are being activated.
             */
            if (LOWORD(wParam))
                SetFocus(ghwndPrintf);

            break;

        case WM_SIZE:
            /*
             * Size the printf window to fit into the new client area size.
             */
            MoveWindow(ghwndPrintf, -gcxBorder, -gcyBorder,
                LOWORD(lParam) + (2 * gcxBorder),
                HIWORD(lParam) + (2 * gcyBorder), TRUE);
            break;

        case WM_CLOSE:
            SetSpyHook(FALSE);

#ifdef JAPAN    // DBCS_FIX
            if (gfhCom1 != INVALID_HANDLE_VALUE)
                CloseHandle(gfhCom1);
#endif
            if (gfhFile)
                _lclose(gfhFile);

            SendMessage(ghwndSpyHook, WM_CLOSE, 0, 0);
            WriteRegistry();
            WaitForSingleObject(ghHookThread, INFINITE);
            DestroyWindow(ghwndSpyApp);
            break;

        case WM_DESTROY:
            PostQuitMessage(0);   /* Kill the main window */
            ghwndSpyApp = NULL;
            ghwndPrintf = NULL;
            break;

        case WM_EXECINSTANCE:
            /*
             * another instance of spy has been started.
             */
            if (IsIconic(hwnd))
                ShowWindow(hwnd,SW_SHOWNORMAL);

            SetForegroundWindow(hwnd);
            BringWindowToTop(hwnd);

            break;

        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }

    return 0;
}
コード例 #16
0
ファイル: CDIB.CPP プロジェクト: WWAWing/WinWwaWingmk
///////////////////////////////////////
// read in the DIB file format (256 color BMP)
///////////////////////////////////////
BOOL CDib::ReadFile(LPSTR lpszFilename)
{
	BITMAPINFOHEADER   bih;
	OFSTRUCT           of;
	HFILE              fh;
	DWORD              dwFileStart;
	BITMAPFILEHEADER   bif;
	UINT               rgbQuadTableSize;
	UINT               lpbitsSize;
	UINT               nPalEntries;
    
	// open the DIB file to initialize OFSTRUCT
	fh = OpenFile(lpszFilename, &of, OF_READ);
	if (fh == -1)
	{ 
	  SetCDibState(FAIL_DIB_OPEN);
	  return FALSE;
	}

    // find the beginning of the DIB file	
 	dwFileStart = _llseek(fh, 0L, FILE_BEGIN);

	// BITMAPFILEHEADER

	// read in the BITMAPFILEHEADER
    if ((_lread(fh,&bif, sizeof(bif))) != sizeof(bif)) 
    {
		SetCDibState(FAIL_FHDR_READ);
		_lclose(fh);
		return FALSE;
    }

    // is the BITMAPFILEHEADER field bfType = 'BM' ?
    if (bif.bfType != 0x4D42) 
    {
		SetCDibState(FAIL_BFTYPE_INVALID);
		_lclose(fh);
		return FALSE;
    }
	

	// BITMAPINFOHEADER

	// read in the BITMAPINFOHEADER
    if ((_lread(fh, &bih, sizeof(bih))) != sizeof(bih)) 
    {
		SetCDibState(FAIL_IHDR_READ);
		_lclose(fh);
		return FALSE;
    }

    // BITMAPINFO

    CreateBITMAPINFO();      

	if (lpbinfo == NULL)
	{
	  _lclose(fh);
	  return FALSE;
	}

    // Copy the header we already have.
    memcpy(lpbinfo, &bih, sizeof(BITMAPINFOHEADER));

	// RGBQUAD

	// determine the RGBQUAD array size
    nPalEntries = NumberOfColorEntries((LPBITMAPINFO) &bih);
    rgbQuadTableSize = nPalEntries * sizeof(RGBQUAD);

    // Read the color table from the file.
    if ((_lread(fh,((LPBYTE) lpbinfo) + sizeof(BITMAPINFOHEADER),rgbQuadTableSize)) != rgbQuadTableSize) 
    {			   // 
        SetCDibState(FAIL_FORMAT_INVALID);
		_lclose(fh);
		return FALSE;
    }

	// assign the LPRGBQUAD pointer to the RGBQUAD array
	lprgb = GetLPRGBPtr();

	// Image Bits

    // Free any previous garbage
	if (lpBits != NULL) 
       GlobalFreePtr(lpBits);

	// determine the size of the image in the file
	lpbitsSize = bif.bfSize - bif.bfOffBits;

	// allocate memory to hold the image
    lpBits = (LPBYTE) GlobalAllocPtr(GMEM_MOVEABLE,lpbitsSize);
    if (lpBits == NULL) 
    {
		SetCDibState(FAIL_BITS_ALLOC);
		_lclose(fh);
		return FALSE;
    }

    // move the file handle to the start of the image
	_llseek(fh, dwFileStart + bif.bfOffBits, FILE_BEGIN);
	
    // read the image into memory
    if ((_lread(fh, lpBits, lpbitsSize)) != lpbitsSize) 
    {
		SetCDibState(FAIL_BITS_READ);
		_lclose(fh);
		return FALSE;
    }

	// all done, close the file
	_lclose(fh);
    return TRUE;
}
コード例 #17
0
ファイル: mmio.c プロジェクト: hoangduit/reactos
/**************************************************************************
 *               	mmioDosIOProc           		[internal]
 */
static LRESULT CALLBACK mmioDosIOProc(LPMMIOINFO lpmmioinfo, UINT uMessage,
				      LPARAM lParam1, LPARAM lParam2)
{
    LRESULT	ret = MMSYSERR_NOERROR;

    TRACE("(%p, %X, 0x%lx, 0x%lx);\n", lpmmioinfo, uMessage, lParam1, lParam2);

    switch (uMessage) {
    case MMIOM_OPEN:
	{
	    /* Parameters:
	     * lParam1 = szFileName parameter from mmioOpen
	     * lParam2 = reserved
	     * Returns: zero on success, error code on error
	     * NOTE: lDiskOffset automatically set to zero
	     */
	    LPCSTR      szFileName = (LPCSTR)lParam1;

	    if (lpmmioinfo->dwFlags & MMIO_GETTEMP) {
		FIXME("MMIO_GETTEMP not implemented\n");
		return MMIOERR_CANNOTOPEN;
	    }

	    /* if filename NULL, assume open file handle in adwInfo[0] */
	    if (szFileName) {
                OFSTRUCT    ofs;
                lpmmioinfo->adwInfo[0] = (DWORD)OpenFile(szFileName, &ofs, lpmmioinfo->dwFlags & 0xFFFF);
            }
	    if (lpmmioinfo->adwInfo[0] == (DWORD)HFILE_ERROR)
		ret = MMIOERR_CANNOTOPEN;
	}
	break;

    case MMIOM_CLOSE:
	/* Parameters:
	 * lParam1 = wFlags parameter from mmioClose
	 * lParam2 = unused
	 * Returns: zero on success, error code on error
	 */
	if (!(lParam1 & MMIO_FHOPEN))
	    _lclose((HFILE)lpmmioinfo->adwInfo[0]);
	break;

    case MMIOM_READ:
	/* Parameters:
	 * lParam1 = huge pointer to read buffer
	 * lParam2 = number of bytes to read
	 * Returns: number of bytes read, 0 for EOF, -1 for error (error code
	 *	   in wErrorRet)
	 */
	ret = _lread((HFILE)lpmmioinfo->adwInfo[0], (HPSTR)lParam1, (LONG)lParam2);
	if (ret != -1)
	    lpmmioinfo->lDiskOffset += ret;

	break;

    case MMIOM_WRITE:
    case MMIOM_WRITEFLUSH:
	/* no internal buffering, so WRITEFLUSH handled same as WRITE */

	/* Parameters:
	 * lParam1 = huge pointer to write buffer
	 * lParam2 = number of bytes to write
	 * Returns: number of bytes written, -1 for error (error code in
	 *		wErrorRet)
	 */
	ret = _hwrite((HFILE)lpmmioinfo->adwInfo[0], (HPSTR)lParam1, (LONG)lParam2);
	if (ret != -1)
	    lpmmioinfo->lDiskOffset += ret;
	break;

    case MMIOM_SEEK:
	/* Parameters:
	 * lParam1 = new position
	 * lParam2 = from whence to seek (SEEK_SET, SEEK_CUR, SEEK_END)
	 * Returns: new file postion, -1 on error
	 */
	ret = _llseek((HFILE)lpmmioinfo->adwInfo[0], (LONG)lParam1, (LONG)lParam2);
	if (ret != -1)
	    lpmmioinfo->lDiskOffset = ret;
	return ret;

    case MMIOM_RENAME:
	/* Parameters:
	 * lParam1 = old name
	 * lParam2 = new name
	 * Returns: zero on success, non-zero on failure
	 */
 	 if (!MoveFileA((const char*)lParam1, (const char*)lParam2))
	     ret = MMIOERR_FILENOTFOUND;
	 break;

    default:
	FIXME("unexpected message %u\n", uMessage);
	return 0;
    }

    return ret;
}
コード例 #18
0
ファイル: lzexpand.c プロジェクト: farp90/nativecmd
INT WINAPI GetExpandedNameA( LPSTR in, LPSTR out )
{
	struct lzfileheader	head;
	HFILE		fd;
	OFSTRUCT	ofs;
	INT		fnislowercased,ret,len;
	LPSTR		s,t;

	DPRINT("(%s)\n",in);
	fd=OpenFile(in,&ofs,OF_READ);
	if (fd==HFILE_ERROR)
		return (INT)(INT16)LZERROR_BADINHANDLE;
	strcpy(out,in);
	ret=read_header(fd,&head);
	if (ret<=0) {
		/* not a LZ compressed file, so the expanded name is the same
		 * as the input name */
		_lclose(fd);
		return 1;
	}


	/* look for directory prefix and skip it. */
	s=out;
	while (NULL!=(t=strpbrk(s,"/\\:")))
		s=t+1;

	/* now mangle the basename */
	if (!*s) {
		/* FIXME: hmm. shouldn't happen? */
		DPRINT("Specified a directory or what? (%s)\n",in);
		_lclose(fd);
		return 1;
	}
	/* see if we should use lowercase or uppercase on the last char */
	fnislowercased=1;
	t=s+strlen(s)-1;
	while (t>=out) {
		if (!isalpha(*t)) {
			t--;
			continue;
		}
		fnislowercased=islower(*t);
		break;
	}
	if (isalpha(head.lastchar)) {
		if (fnislowercased)
			head.lastchar=(CHAR)tolower(head.lastchar);
		else
			head.lastchar=(CHAR)toupper(head.lastchar);
	}

	/* now look where to replace the last character */
	if (NULL!=(t=strchr(s,'.'))) {
		if (t[1]=='\0') {
			t[0]='\0';
		} else {
			len=strlen(t)-1;
			if (t[len]=='_')
				t[len]=head.lastchar;
		}
	} /* else no modification necessary */
	_lclose(fd);
	return 1;
}
コード例 #19
0
ファイル: gfx.cpp プロジェクト: domino14/SpaceWars2
int Load_Bitmap_File(BITMAP_FILE_PTR bitmap, char *filename)
{
// this function opens a bitmap file and loads the data into bitmap

int file_handle,  // the file handle
    index;        // looping index


UCHAR   *temp_buffer = NULL; // used to convert 24 bit images to 16 bit
OFSTRUCT file_data;          // the file data information

// open the file if it exists
if ((file_handle = OpenFile(filename,&file_data,OF_READ))==-1)
   return(0);


// now load the bitmap file header
_lread(file_handle, &bitmap->bitmapfileheader,sizeof(BITMAPFILEHEADER));

// test if this is a bitmap file
if (bitmap->bitmapfileheader.bfType!=0x4D42)
   {
   // close the file
   _lclose(file_handle);

   // return error
   return(0);

   } // end if

// now we know this is a bitmap, so read in all the sections

// first the bitmap infoheader

// now load the bitmap file header
_lread(file_handle, &bitmap->bitmapinfoheader,sizeof(BITMAPINFOHEADER));

// now load the color palette if there is one
if (bitmap->bitmapinfoheader.biBitCount == 8)
   {
   _lread(file_handle, &bitmap->palette,256*sizeof(PALETTEENTRY));

   // now set all the flags in the palette correctly and fix the reversed 
   // BGR RGBQUAD data format
   for (index=0; index < 256; index++)
       {
       // reverse the red and green fields
       int temp_color                = bitmap->palette[index].peRed;
       bitmap->palette[index].peRed  = bitmap->palette[index].peBlue;
       bitmap->palette[index].peBlue = temp_color;
       
       // always set the flags word to this
       bitmap->palette[index].peFlags = PC_NOCOLLAPSE;
       } // end for index

    } // end if

// finally the image data itself
_lseek(file_handle,-(int)(bitmap->bitmapinfoheader.biSizeImage),SEEK_END);

// now read in the image, if the image is 8 or 16 bit then simply read it
// but if its 24 bit then read it into a temporary area and then convert
// it to a 16 bit image

if (bitmap->bitmapinfoheader.biBitCount==8 || bitmap->bitmapinfoheader.biBitCount==16 || 
    bitmap->bitmapinfoheader.biBitCount==24)
   {
   // delete the last image if there was one
   if (bitmap->buffer)
       free(bitmap->buffer);

   // allocate the memory for the image
   if (!(bitmap->buffer = (UCHAR *)malloc(bitmap->bitmapinfoheader.biSizeImage)))
      {
      // close the file
      _lclose(file_handle);

      // return error
      return(0);
      } // end if

   // now read it in
   _lread(file_handle,bitmap->buffer,bitmap->bitmapinfoheader.biSizeImage);

   } // end if
else
   {
   // serious problem
   return(0);

   } // end else

#if 0
// write the file info out 
printf("\nfilename:%s \nsize=%d \nwidth=%d \nheight=%d \nbitsperpixel=%d \ncolors=%d \nimpcolors=%d",
        filename,
        bitmap->bitmapinfoheader.biSizeImage,
        bitmap->bitmapinfoheader.biWidth,
        bitmap->bitmapinfoheader.biHeight,
		bitmap->bitmapinfoheader.biBitCount,
        bitmap->bitmapinfoheader.biClrUsed,
        bitmap->bitmapinfoheader.biClrImportant);

#endif

// close the file
_lclose(file_handle);

// flip the bitmap
Flip_Bitmap(bitmap->buffer, 
            bitmap->bitmapinfoheader.biWidth*(bitmap->bitmapinfoheader.biBitCount/8), 
            bitmap->bitmapinfoheader.biHeight);

// return success

return(1);

} // end Load_Bitmap_File
コード例 #20
0
ファイル: vxd.c プロジェクト: NVIDIA/winex_lgpl
void WINAPI VXD_Win32s( CONTEXT86 *context )
{
    switch (AX_reg(context))
    {
    case 0x0000: /* Get Version */
        /*
         * Input:   None
         *
         * Output:  EAX: LoWord: Win32s Version (1.30)
         *               HiWord: VxD Version (200)
         *
         *          EBX: Build (172)
         *
         *          ECX: ???   (1)
         *
         *          EDX: Debugging Flags
         *
         *          EDI: Error Flag
         *               0 if OK,
         *               1 if VMCPD VxD not found
         */

        TRACE("GetVersion()\n");

	context->Eax = VXD_WinVersion() | (200 << 16);
        context->Ebx = 0;
        context->Ecx = 0;
        context->Edx = 0;
        context->Edi = 0;

        /*
         * If this is the first time we are called for this process,
         * hack the memory image of WIN32S16 so that it doesn't try
         * to access the GDT directly ...
         *
         * The first code segment of WIN32S16 (version 1.30) contains
         * an unexported function somewhere between the exported functions
         * SetFS and StackLinearToSegmented that tries to find a selector
         * in the LDT that maps to the memory image of the LDT itself.
         * If it succeeds, it stores this selector into a global variable
         * which will be used to speed up execution by using this selector
         * to modify the LDT directly instead of using the DPMI calls.
         *
         * To perform this search of the LDT, this function uses the
         * sgdt and sldt instructions to find the linear address of
         * the (GDT and then) LDT. While those instructions themselves
         * execute without problem, the linear address that sgdt returns
         * points (at least under Linux) to the kernel address space, so
         * that any subsequent access leads to a segfault.
         *
         * Fortunately, WIN32S16 still contains as a fallback option the
         * mechanism of using DPMI calls to modify LDT selectors instead
         * of direct writes to the LDT. Thus we can circumvent the problem
         * by simply replacing the first byte of the offending function
         * with an 'retf' instruction. This means that the global variable
         * supposed to contain the LDT alias selector will remain zero,
         * and hence WIN32S16 will fall back to using DPMI calls.
         *
         * The heuristic we employ to _find_ that function is as follows:
         * We search between the addresses of the exported symbols SetFS
         * and StackLinearToSegmented for the byte sequence '0F 01 04'
         * (this is the opcode of 'sgdt [si]'). We then search backwards
         * from this address for the last occurrence of 'CB' (retf) that marks
         * the end of the preceeding function. The following byte (which
         * should now be the first byte of the function we are looking for)
         * will be replaced by 'CB' (retf).
         *
         * This heuristic works for the retail as well as the debug version
         * of Win32s version 1.30. For versions earlier than that this
         * hack should not be necessary at all, since the whole mechanism
         * ('PERF130') was introduced only in 1.30 to improve the overall
         * performance of Win32s.
         */

        if (!W32S_offset)
        {
            HMODULE16 hModule = GetModuleHandle16("win32s16");
            SEGPTR func1 = (SEGPTR)GetProcAddress16(hModule, "SetFS");
            SEGPTR func2 = (SEGPTR)GetProcAddress16(hModule, "StackLinearToSegmented");

            if (   hModule && func1 && func2
                && SELECTOROF(func1) == SELECTOROF(func2))
            {
                BYTE *start = MapSL(func1);
                BYTE *end   = MapSL(func2);
                BYTE *p, *retv = NULL;
                int found = 0;

                for (p = start; p < end; p++)
                    if (*p == 0xCB) found = 0, retv = p;
                    else if (*p == 0x0F) found = 1;
                    else if (*p == 0x01 && found == 1) found = 2;
                    else if (*p == 0x04 && found == 2) { found = 3; break; }
                    else found = 0;

                if (found == 3 && retv)
                {
                    TRACE("PERF130 hack: "
                               "Replacing byte %02X at offset %04X:%04X\n",
                               *(retv+1), SELECTOROF(func1),
                                          OFFSETOF(func1) + retv+1-start);

                    *(retv+1) = (BYTE)0xCB;
                }
            }
        }

        /*
         * Mark process as Win32s, so that subsequent DPMI calls
         * will perform the W32S_APP2WINE/W32S_WINE2APP address shift.
         */
        W32S_offset = 0x10000;
        break;


    case 0x0001: /* Install Exception Handling */
        /*
         * Input:   EBX: Flat address of W32SKRNL Exception Data
         *
         *          ECX: LoWord: Flat Code Selector
         *               HiWord: Flat Data Selector
         *
         *          EDX: Flat address of W32SKRNL Exception Handler
         *               (this is equal to W32S_BackTo32 + 0x40)
         *
         *          ESI: SEGPTR KERNEL.HASGPHANDLER
         *
         *          EDI: SEGPTR phCurrentTask (KERNEL.THHOOK + 0x10)
         *
         * Output:  EAX: 0 if OK
         */

        TRACE("[0001] EBX=%lx ECX=%lx EDX=%lx ESI=%lx EDI=%lx\n",
                   context->Ebx, context->Ecx, context->Edx,
                   context->Esi, context->Edi);

        /* FIXME */

        context->Eax = 0;
        break;


    case 0x0002: /* Set Page Access Flags */
        /*
         * Input:   EBX: New access flags
         *               Bit 2: User Page if set, Supervisor Page if clear
         *               Bit 1: Read-Write if set, Read-Only if clear
         *
         *          ECX: Size of memory area to change
         *
         *          EDX: Flat start address of memory area
         *
         * Output:  EAX: Size of area changed
         */

        TRACE("[0002] EBX=%lx ECX=%lx EDX=%lx\n",
                   context->Ebx, context->Ecx, context->Edx);

        /* FIXME */

        context->Eax = context->Ecx;
        break;


    case 0x0003: /* Get Page Access Flags */
        /*
         * Input:   EDX: Flat address of page to query
         *
         * Output:  EAX: Page access flags
         *               Bit 2: User Page if set, Supervisor Page if clear
         *               Bit 1: Read-Write if set, Read-Only if clear
         */

        TRACE("[0003] EDX=%lx\n", context->Edx);

        /* FIXME */

        context->Eax = 6;
        break;


    case 0x0004: /* Map Module */
        /*
         * Input:   ECX: IMTE (offset in Module Table) of new module
         *
         *          EDX: Flat address of Win32s Module Table
         *
         * Output:  EAX: 0 if OK
         */

    if (!context->Edx || CX_reg(context) == 0xFFFF)
    {
        TRACE("MapModule: Initialization call\n");
        context->Eax = 0;
    }
    else
    {
        /*
         * Structure of a Win32s Module Table Entry:
         */
        struct Win32sModule
        {
            DWORD  flags;
            DWORD  flatBaseAddr;
            LPCSTR moduleName;
            LPCSTR pathName;
            LPCSTR unknown;
            LPBYTE baseAddr;
            DWORD  hModule;
            DWORD  relocDelta;
        };

        /*
         * Note: This function should set up a demand-paged memory image
         *       of the given module. Since mmap does not allow file offsets
         *       not aligned at 1024 bytes, we simply load the image fully
         *       into memory.
         */

        struct Win32sModule *moduleTable =
                            (struct Win32sModule *)W32S_APP2WINE(context->Edx);
        struct Win32sModule *module = moduleTable + context->Ecx;

        IMAGE_NT_HEADERS *nt_header = PE_HEADER(module->baseAddr);
        IMAGE_SECTION_HEADER *pe_seg = PE_SECTIONS(module->baseAddr);

        HFILE image = _lopen(module->pathName, OF_READ);
        BOOL error = (image == HFILE_ERROR);
        UINT i;

        TRACE("MapModule: Loading %s\n", module->pathName);

        for (i = 0;
             !error && i < nt_header->FileHeader.NumberOfSections;
             i++, pe_seg++)
            if(!(pe_seg->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA))
            {
                DWORD  off  = pe_seg->PointerToRawData;
                DWORD  len  = pe_seg->SizeOfRawData;
                LPBYTE addr = module->baseAddr + pe_seg->VirtualAddress;

                TRACE("MapModule: "
                           "Section %d at %08lx from %08lx len %08lx\n",
                           i, (DWORD)addr, off, len);

                if (   _llseek(image, off, SEEK_SET) != off
                    || _lread(image, addr, len) != len)
                    error = TRUE;
            }

        _lclose(image);

        if (error)
            ERR("MapModule: Unable to load %s\n", module->pathName);

        else if (module->relocDelta != 0)
        {
            IMAGE_DATA_DIRECTORY *dir = nt_header->OptionalHeader.DataDirectory
                                      + IMAGE_DIRECTORY_ENTRY_BASERELOC;
            IMAGE_BASE_RELOCATION *r = (IMAGE_BASE_RELOCATION *)
                (dir->Size? module->baseAddr + dir->VirtualAddress : 0);

            TRACE("MapModule: Reloc delta %08lx\n", module->relocDelta);

            while (r && r->VirtualAddress)
            {
                LPBYTE page  = module->baseAddr + r->VirtualAddress;
                WORD *TypeOffset = (WORD *)(r + 1);
                int count = (r->SizeOfBlock - sizeof(*r)) / sizeof(*TypeOffset);

                TRACE("MapModule: %d relocations for page %08lx\n",
                           count, (DWORD)page);

                for(i = 0; i < count; i++)
                {
                    int offset = TypeOffset[i] & 0xFFF;
                    int type   = TypeOffset[i] >> 12;
                    switch(type)
                    {
                    case IMAGE_REL_BASED_ABSOLUTE:
                        break;
                    case IMAGE_REL_BASED_HIGH:
                        *(WORD *)(page+offset) += HIWORD(module->relocDelta);
                        break;
                    case IMAGE_REL_BASED_LOW:
                        *(WORD *)(page+offset) += LOWORD(module->relocDelta);
                        break;
                    case IMAGE_REL_BASED_HIGHLOW:
                        *(DWORD*)(page+offset) += module->relocDelta;
                        break;
                    default:
                        WARN("MapModule: Unsupported fixup type\n");
                        break;
                    }
                }

                r = (IMAGE_BASE_RELOCATION *)((LPBYTE)r + r->SizeOfBlock);
            }
        }

        context->Eax = 0;
        RESET_CFLAG(context);
    }
    break;


    case 0x0005: /* UnMap Module */
        /*
         * Input:   EDX: Flat address of module image
         *
         * Output:  EAX: 1 if OK
         */

        TRACE("UnMapModule: %lx\n", (DWORD)W32S_APP2WINE(context->Edx));

        /* As we didn't map anything, there's nothing to unmap ... */

        context->Eax = 1;
        break;


    case 0x0006: /* VirtualAlloc */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] Flat base address of allocated region
         *   LPVOID base     [in]  Flat address of region to reserve/commit
         *   DWORD  size     [in]  Size of region
         *   DWORD  type     [in]  Type of allocation
         *   DWORD  prot     [in]  Type of access protection
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size   = stack[2];
        DWORD  type   = stack[3];
        DWORD  prot   = stack[4];
        DWORD  result;

        TRACE("VirtualAlloc(%lx, %lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size, type, prot);

        if (type & 0x80000000)
        {
            WARN("VirtualAlloc: strange type %lx\n", type);
            type &= 0x7fffffff;
        }

        if (!base && (type & MEM_COMMIT) && prot == PAGE_READONLY)
        {
            WARN("VirtualAlloc: NLS hack, allowing write access!\n");
            prot = PAGE_READWRITE;
        }

        result = (DWORD)VirtualAlloc(base, size, type, prot);

        if (W32S_WINE2APP(result))
            *retv            = W32S_WINE2APP(result),
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = 0,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x0007: /* VirtualFree */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] TRUE if success, FALSE if failure
         *   LPVOID base     [in]  Flat address of region
         *   DWORD  size     [in]  Size of region
         *   DWORD  type     [in]  Type of operation
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size   = stack[2];
        DWORD  type   = stack[3];
        DWORD  result;

        TRACE("VirtualFree(%lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size, type);

        result = VirtualFree(base, size, type);

        if (result)
            *retv            = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x0008: /* VirtualProtect */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] TRUE if success, FALSE if failure
         *   LPVOID base     [in]  Flat address of region
         *   DWORD  size     [in]  Size of region
         *   DWORD  new_prot [in]  Desired access protection
         *   DWORD *old_prot [out] Previous access protection
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv     = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base     = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size     = stack[2];
        DWORD  new_prot = stack[3];
        DWORD *old_prot = (DWORD *)W32S_APP2WINE(stack[4]);
        DWORD  result;

        TRACE("VirtualProtect(%lx, %lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size, new_prot, (DWORD)old_prot);

        result = VirtualProtect(base, size, new_prot, old_prot);

        if (result)
            *retv            = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x0009: /* VirtualQuery */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv                     [out] Nr. bytes returned
         *   LPVOID base                     [in]  Flat address of region
         *   LPMEMORY_BASIC_INFORMATION info [out] Info buffer
         *   DWORD  len                      [in]  Size of buffer
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        LPMEMORY_BASIC_INFORMATION info =
                        (LPMEMORY_BASIC_INFORMATION)W32S_APP2WINE(stack[2]);
        DWORD  len    = stack[3];
        DWORD  result;

        TRACE("VirtualQuery(%lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, (DWORD)info, len);

        result = VirtualQuery(base, info, len);

        *retv            = result;
        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x000A: /* SetVirtMemProcess */
        /*
         * Input:   ECX: Process Handle
         *
         *          EDX: Flat address of region
         *
         * Output:  EAX: NtStatus
         */

        TRACE("[000a] ECX=%lx EDX=%lx\n",
                   context->Ecx, context->Edx);

        /* FIXME */

        context->Eax = STATUS_SUCCESS;
        break;


    case 0x000B: /* ??? some kind of cleanup */
        /*
         * Input:   ECX: Process Handle
         *
         * Output:  EAX: NtStatus
         */

        TRACE("[000b] ECX=%lx\n", context->Ecx);

        /* FIXME */

        context->Eax = STATUS_SUCCESS;
        break;


    case 0x000C: /* Set Debug Flags */
        /*
         * Input:   EDX: Debug Flags
         *
         * Output:  EDX: Previous Debug Flags
         */

        FIXME("[000c] EDX=%lx\n", context->Edx);

        /* FIXME */

        context->Edx = 0;
        break;


    case 0x000D: /* NtCreateSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 *retv      [out] Handle of Section created
         *   DWORD  flags1       [in]  (?? unknown ??)
         *   DWORD  atom         [in]  Name of Section to create
         *   LARGE_INTEGER *size [in]  Size of Section
         *   DWORD  protect      [in]  Access protection
         *   DWORD  flags2       [in]  (?? unknown ??)
         *   HFILE32 hFile       [in]  Handle of file to map
         *   DWORD  psp          [in]  (Win32s: PSP that hFile belongs to)
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)   W32S_APP2WINE(context->Edx);
        HANDLE *retv  = (HANDLE *)W32S_APP2WINE(stack[0]);
        DWORD  flags1   = stack[1];
        DWORD  atom     = stack[2];
        LARGE_INTEGER *size = (LARGE_INTEGER *)W32S_APP2WINE(stack[3]);
        DWORD  protect  = stack[4];
        DWORD  flags2   = stack[5];
        HANDLE hFile    = DosFileHandleToWin32Handle(stack[6]);
        DWORD  psp      = stack[7];

        HANDLE result = INVALID_HANDLE_VALUE;
        char name[128];

        TRACE("NtCreateSection(%lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, flags1, atom, (DWORD)size, protect, flags2,
                   (DWORD)hFile, psp);

        if (!atom || GlobalGetAtomNameA(atom, name, sizeof(name)))
        {
            TRACE("NtCreateSection: name=%s\n", atom? name : NULL);

            result = CreateFileMappingA(hFile, NULL, protect,
                                          size? size->s.HighPart : 0,
                                          size? size->s.LowPart  : 0,
                                          atom? name : NULL);
        }

        if (result == INVALID_HANDLE_VALUE)
            WARN("NtCreateSection: failed!\n");
        else
            TRACE("NtCreateSection: returned %lx\n", (DWORD)result);

        if (result != INVALID_HANDLE_VALUE)
            *retv            = result,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = result,
            context->Eax = STATUS_NO_MEMORY;   /* FIXME */
    }
    break;


    case 0x000E: /* NtOpenSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 *retv  [out] Handle of Section opened
         *   DWORD  protect  [in]  Access protection
         *   DWORD  atom     [in]  Name of Section to create
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)W32S_APP2WINE(context->Edx);
        HANDLE *retv  = (HANDLE *)W32S_APP2WINE(stack[0]);
        DWORD  protect  = stack[1];
        DWORD  atom     = stack[2];

        HANDLE result = INVALID_HANDLE_VALUE;
        char name[128];

        TRACE("NtOpenSection(%lx, %lx, %lx)\n",
                   (DWORD)retv, protect, atom);

        if (atom && GlobalGetAtomNameA(atom, name, sizeof(name)))
        {
            TRACE("NtOpenSection: name=%s\n", name);

            result = OpenFileMappingA(protect, FALSE, name);
        }

        if (result == INVALID_HANDLE_VALUE)
            WARN("NtOpenSection: failed!\n");
        else
            TRACE("NtOpenSection: returned %lx\n", (DWORD)result);

        if (result != INVALID_HANDLE_VALUE)
            *retv            = result,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = result,
            context->Eax = STATUS_NO_MEMORY;   /* FIXME */
    }
    break;


    case 0x000F: /* NtCloseSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 handle  [in]  Handle of Section to close
         *   DWORD *id        [out] Unique ID  (?? unclear ??)
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)W32S_APP2WINE(context->Edx);
        HANDLE handle = stack[0];
        DWORD *id       = (DWORD *)W32S_APP2WINE(stack[1]);

        TRACE("NtCloseSection(%lx, %lx)\n", (DWORD)handle, (DWORD)id);

        CloseHandle(handle);
        if (id) *id = 0; /* FIXME */

        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x0010: /* NtDupSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 handle  [in]  Handle of Section to duplicate
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)W32S_APP2WINE(context->Edx);
        HANDLE handle = stack[0];
        HANDLE new_handle;

        TRACE("NtDupSection(%lx)\n", (DWORD)handle);

        DuplicateHandle( GetCurrentProcess(), handle,
                         GetCurrentProcess(), &new_handle,
                         0, FALSE, DUPLICATE_SAME_ACCESS );
        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x0011: /* NtMapViewOfSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 SectionHandle       [in]     Section to be mapped
         *   DWORD    ProcessHandle       [in]     Process to be mapped into
         *   DWORD *  BaseAddress         [in/out] Address to be mapped at
         *   DWORD    ZeroBits            [in]     (?? unclear ??)
         *   DWORD    CommitSize          [in]     (?? unclear ??)
         *   LARGE_INTEGER *SectionOffset [in]     Offset within section
         *   DWORD *  ViewSize            [in]     Size of view
         *   DWORD    InheritDisposition  [in]     (?? unclear ??)
         *   DWORD    AllocationType      [in]     (?? unclear ??)
         *   DWORD    Protect             [in]     Access protection
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *  stack          = (DWORD *)W32S_APP2WINE(context->Edx);
        HANDLE SectionHandle  = stack[0];
        DWORD    ProcessHandle  = stack[1]; /* ignored */
        DWORD *  BaseAddress    = (DWORD *)W32S_APP2WINE(stack[2]);
        DWORD    ZeroBits       = stack[3];
        DWORD    CommitSize     = stack[4];
        LARGE_INTEGER *SectionOffset = (LARGE_INTEGER *)W32S_APP2WINE(stack[5]);
        DWORD *  ViewSize       = (DWORD *)W32S_APP2WINE(stack[6]);
        DWORD    InheritDisposition = stack[7];
        DWORD    AllocationType = stack[8];
        DWORD    Protect        = stack[9];

        LPBYTE address = (LPBYTE)(BaseAddress?
			W32S_APP2WINE(*BaseAddress) : 0);
        DWORD  access = 0, result;

        switch (Protect & ~(PAGE_GUARD|PAGE_NOCACHE))
        {
            case PAGE_READONLY:           access = FILE_MAP_READ;  break;
            case PAGE_READWRITE:          access = FILE_MAP_WRITE; break;
            case PAGE_WRITECOPY:          access = FILE_MAP_COPY;  break;

            case PAGE_EXECUTE_READ:       access = FILE_MAP_READ;  break;
            case PAGE_EXECUTE_READWRITE:  access = FILE_MAP_WRITE; break;
            case PAGE_EXECUTE_WRITECOPY:  access = FILE_MAP_COPY;  break;
        }

        TRACE("NtMapViewOfSection"
                   "(%lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx)\n",
                   (DWORD)SectionHandle, ProcessHandle, (DWORD)BaseAddress,
                   ZeroBits, CommitSize, (DWORD)SectionOffset, (DWORD)ViewSize,
                   InheritDisposition, AllocationType, Protect);
        TRACE("NtMapViewOfSection: "
                   "base=%lx, offset=%lx, size=%lx, access=%lx\n",
                   (DWORD)address, SectionOffset? SectionOffset->s.LowPart : 0,
                   ViewSize? *ViewSize : 0, access);

        result = (DWORD)MapViewOfFileEx(SectionHandle, access,
                            SectionOffset? SectionOffset->s.HighPart : 0,
                            SectionOffset? SectionOffset->s.LowPart  : 0,
                            ViewSize? *ViewSize : 0, address);

        TRACE("NtMapViewOfSection: result=%lx\n", result);

        if (W32S_WINE2APP(result))
        {
            if (BaseAddress) *BaseAddress = W32S_WINE2APP(result);
            context->Eax = STATUS_SUCCESS;
        }
        else
            context->Eax = STATUS_NO_MEMORY; /* FIXME */
    }
    break;


    case 0x0012: /* NtUnmapViewOfSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   DWORD  ProcessHandle  [in]  Process (defining address space)
         *   LPBYTE BaseAddress    [in]  Base address of view to be unmapped
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack          = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD  ProcessHandle  = stack[0]; /* ignored */
        LPBYTE BaseAddress    = (LPBYTE)W32S_APP2WINE(stack[1]);

        TRACE("NtUnmapViewOfSection(%lx, %lx)\n",
                   ProcessHandle, (DWORD)BaseAddress);

        UnmapViewOfFile(BaseAddress);

        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x0013: /* NtFlushVirtualMemory */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   DWORD   ProcessHandle  [in]  Process (defining address space)
         *   LPBYTE *BaseAddress    [in?] Base address of range to be flushed
         *   DWORD  *ViewSize       [in?] Number of bytes to be flushed
         *   DWORD  *unknown        [???] (?? unknown ??)
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack          = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD  ProcessHandle  = stack[0]; /* ignored */
        DWORD *BaseAddress    = (DWORD *)W32S_APP2WINE(stack[1]);
        DWORD *ViewSize       = (DWORD *)W32S_APP2WINE(stack[2]);
        DWORD *unknown        = (DWORD *)W32S_APP2WINE(stack[3]);

        LPBYTE address = (LPBYTE)(BaseAddress? W32S_APP2WINE(*BaseAddress) : 0);
        DWORD  size    = ViewSize? *ViewSize : 0;

        TRACE("NtFlushVirtualMemory(%lx, %lx, %lx, %lx)\n",
                   ProcessHandle, (DWORD)BaseAddress, (DWORD)ViewSize,
                   (DWORD)unknown);
        TRACE("NtFlushVirtualMemory: base=%lx, size=%lx\n",
                   (DWORD)address, size);

        FlushViewOfFile(address, size);

        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x0014: /* Get/Set Debug Registers */
        /*
         * Input:   ECX: 0 if Get, 1 if Set
         *
         *          EDX: Get: Flat address of buffer to receive values of
         *                    debug registers DR0 .. DR7
         *               Set: Flat address of buffer containing values of
         *                    debug registers DR0 .. DR7 to be set
         * Output:  None
         */

        FIXME("[0014] ECX=%lx EDX=%lx\n",
                   context->Ecx, context->Edx);

        /* FIXME */
        break;


    case 0x0015: /* Set Coprocessor Emulation Flag */
        /*
         * Input:   EDX: 0 to deactivate, 1 to activate coprocessor emulation
         *
         * Output:  None
         */

        TRACE("[0015] EDX=%lx\n", context->Edx);

        /* We don't care, as we always have a coprocessor anyway */
        break;


    case 0x0016: /* Init Win32S VxD PSP */
        /*
         * If called to query required PSP size:
         *
         *     Input:  EBX: 0
         *     Output: EDX: Required size of Win32s VxD PSP
         *
         * If called to initialize allocated PSP:
         *
         *     Input:  EBX: LoWord: Selector of Win32s VxD PSP
         *                  HiWord: Paragraph of Win32s VxD PSP (DOSMEM)
         *     Output: None
         */

        if (context->Ebx == 0)
            context->Edx = 0x80;
        else
        {
            PDB16 *psp = MapSL( MAKESEGPTR( BX_reg(context), 0 ));
            psp->nbFiles = 32;
            psp->fileHandlesPtr = MAKELONG(HIWORD(context->Ebx), 0x5c);
            memset((LPBYTE)psp + 0x5c, '\xFF', 32);
        }
        break;


    case 0x0017: /* Set Break Point */
        /*
         * Input:   EBX: Offset of Break Point
         *          CX:  Selector of Break Point
         *
         * Output:  None
         */

        FIXME("[0017] EBX=%lx CX=%x\n",
                   context->Ebx, CX_reg(context));

        /* FIXME */
        break;


    case 0x0018: /* VirtualLock */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] TRUE if success, FALSE if failure
         *   LPVOID base     [in]  Flat address of range to lock
         *   DWORD  size     [in]  Size of range
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size   = stack[2];
        DWORD  result;

        TRACE("VirtualLock(%lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size);

        result = VirtualLock(base, size);

        if (result)
            *retv            = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x0019: /* VirtualUnlock */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] TRUE if success, FALSE if failure
         *   LPVOID base     [in]  Flat address of range to unlock
         *   DWORD  size     [in]  Size of range
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size   = stack[2];
        DWORD  result;

        TRACE("VirtualUnlock(%lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size);

        result = VirtualUnlock(base, size);

        if (result)
            *retv            = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x001A: /* KGetSystemInfo */
        /*
         * Input:   None
         *
         * Output:  ECX:  Start of sparse memory arena
         *          EDX:  End of sparse memory arena
         */

        TRACE("KGetSystemInfo()\n");

        /*
         * Note: Win32s reserves 0GB - 2GB for Win 3.1 and uses 2GB - 4GB as
         *       sparse memory arena. We do it the other way around, since
         *       we have to reserve 3GB - 4GB for Linux, and thus use
         *       0GB - 3GB as sparse memory arena.
         *
         *       FIXME: What about other OSes ?
         */

        context->Ecx = W32S_WINE2APP(0x00000000);
        context->Edx = W32S_WINE2APP(0xbfffffff);
        break;


    case 0x001B: /* KGlobalMemStat */
        /*
         * Input:   ESI: Flat address of buffer to receive memory info
         *
         * Output:  None
         */
    {
        struct Win32sMemoryInfo
        {
            DWORD DIPhys_Count;       /* Total physical pages */
            DWORD DIFree_Count;       /* Free physical pages */
            DWORD DILin_Total_Count;  /* Total virtual pages (private arena) */
            DWORD DILin_Total_Free;   /* Free virtual pages (private arena) */

            DWORD SparseTotal;        /* Total size of sparse arena (bytes ?) */
            DWORD SparseFree;         /* Free size of sparse arena (bytes ?) */
        };

        struct Win32sMemoryInfo *info =
                       (struct Win32sMemoryInfo *)W32S_APP2WINE(context->Esi);

        FIXME("KGlobalMemStat(%lx)\n", (DWORD)info);

        /* FIXME */
    }
    break;


    case 0x001C: /* Enable/Disable Exceptions */
        /*
         * Input:   ECX: 0 to disable, 1 to enable exception handling
         *
         * Output:  None
         */

        TRACE("[001c] ECX=%lx\n", context->Ecx);

        /* FIXME */
        break;


    case 0x001D: /* VirtualAlloc called from 16-bit code */
        /*
         * Input:   EDX: Segmented address of arguments on stack
         *
         *   LPVOID base     [in]  Flat address of region to reserve/commit
         *   DWORD  size     [in]  Size of region
         *   DWORD  type     [in]  Type of allocation
         *   DWORD  prot     [in]  Type of access protection
         *
         * Output:  EAX: NtStatus
         *          EDX: Flat base address of allocated region
         */
    {
        DWORD *stack  = MapSL( MAKESEGPTR( LOWORD(context->Edx), HIWORD(context->Edx) ));
        LPVOID base   = (LPVOID)W32S_APP2WINE(stack[0]);
        DWORD  size   = stack[1];
        DWORD  type   = stack[2];
        DWORD  prot   = stack[3];
        DWORD  result;

        TRACE("VirtualAlloc16(%lx, %lx, %lx, %lx)\n",
                   (DWORD)base, size, type, prot);

        if (type & 0x80000000)
        {
            WARN("VirtualAlloc16: strange type %lx\n", type);
            type &= 0x7fffffff;
        }

        result = (DWORD)VirtualAlloc(base, size, type, prot);

        if (W32S_WINE2APP(result))
            context->Edx = W32S_WINE2APP(result),
            context->Eax = STATUS_SUCCESS;
        else
            context->Edx = 0,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
	TRACE("VirtualAlloc16: returning base %lx\n", context->Edx);
    }
    break;


    case 0x001E: /* VirtualFree called from 16-bit code */
        /*
         * Input:   EDX: Segmented address of arguments on stack
         *
         *   LPVOID base     [in]  Flat address of region
         *   DWORD  size     [in]  Size of region
         *   DWORD  type     [in]  Type of operation
         *
         * Output:  EAX: NtStatus
         *          EDX: TRUE if success, FALSE if failure
         */
    {
        DWORD *stack  = MapSL( MAKESEGPTR( LOWORD(context->Edx), HIWORD(context->Edx) ));
        LPVOID base   = (LPVOID)W32S_APP2WINE(stack[0]);
        DWORD  size   = stack[1];
        DWORD  type   = stack[2];
        DWORD  result;

        TRACE("VirtualFree16(%lx, %lx, %lx)\n",
                   (DWORD)base, size, type);

        result = VirtualFree(base, size, type);

        if (result)
            context->Edx = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            context->Edx = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x001F: /* FWorkingSetSize */
        /*
         * Input:   EDX: 0 if Get, 1 if Set
         *
         *          ECX: Get: Buffer to receive Working Set Size
         *               Set: Buffer containing Working Set Size
         *
         * Output:  NtStatus
         */
    {
        DWORD *ptr = (DWORD *)W32S_APP2WINE(context->Ecx);
        BOOL set = context->Edx;

        TRACE("FWorkingSetSize(%lx, %lx)\n", (DWORD)ptr, (DWORD)set);

        if (set)
            /* We do it differently ... */;
        else
            *ptr = 0x100;

        context->Eax = STATUS_SUCCESS;
    }
    break;


    default:
	VXD_BARF( context, "W32S" );
    }
コード例 #21
0
ファイル: KrnFileIO.c プロジェクト: ErisBlastar/osfree
int WINAPI
OpenFile(LPCSTR lpszFileName,OFSTRUCT *lpofs,UINT wFunction)
{
    int   fd;
    const char *lpstr = lpszFileName;

    /*
     *  The "lpstr" variable is needed as a workaround to a bug
     *  in the SunOS "acc" compiler, which treats the LPCSTR typedef
     *  as type "const char * const" rather than the requested
     *  "const char *".
     */

    APISTR((LF_APICALL,"OpenFile(LPCSTR=%s,OFSTRUCT=%p,UINT=%x)\n",
	lpszFileName,lpofs,wFunction));

    if ((wFunction & OF_REOPEN)) {
	lpstr = lpofs->szPathName;
    }
    if (!lpstr) {
           APISTR((LF_APIFAIL,"OpenFile: returns int HFILE_ERROR\n"));
           return HFILE_ERROR;
    }

    if(wFunction & OF_PARSE) {
	memset((LPSTR)lpofs,0,sizeof(OFSTRUCT));
	MFS_ALTPATH(lpofs->szPathName, lpstr);
        APISTR((LF_APIFAIL,"OpenFile: returns int 0\n"));
	return 0;
    }

    lpofs->fFixedDisk = 1;

    if(wFunction & OF_DELETE) {
	fd = _ldelete(lpstr);
	if(fd == 0) {
          APISTR((LF_APIRET,"OpenFile: returns int 1\n"));
	  return 1;
	} else {
          APISTR((LF_APIFAIL,"OpenFile: returns int HFILE_ERROR\n"));
	  return HFILE_ERROR;
	}
    }

    if(wFunction & OF_CREATE)
	fd = _lcreat(lpstr, 0);
    else
	fd = OpenEngine(lpstr,lpofs,wFunction);		

#ifdef LATER
    if(fd < 0) {
	if((wFunction & (OF_PROMPT|OF_CREATE)) == OF_PROMPT) {
	    printf("prompting user for file %s cancel...\n",
					wFunction&OF_CANCEL?"w/":"w/o ");
	}
    }
    if((wFunction & (OF_READ|OF_VERIFY)) == (OF_READ|OF_VERIFY)) {
	printf("checking for date/time...\n");
    }
#endif

    if(fd < 0) {
    	APISTR((LF_APIFAIL,"OpenFile: returns int %d\n",fd));
	return fd;	
    }

    if(wFunction & OF_EXIST)
	_lclose(fd);

    APISTR((LF_APIRET,"OpenFile: returns int %d\n",fd));
    return fd;
}
コード例 #22
0
ファイル: TMSRpt86.c プロジェクト: ems/TMS
BOOL FAR TMSRPT86(TMSRPTPassedDataDef *pPassedData)
{
  GenerateTripDef GTResults;
  HFILE hfOutputFile;
  BOOL  bKeepGoing = FALSE;
  BOOL  bFound;
  char  dummy[256];
  char  outputString[512];
  long  statbarTotal;
  long  saveTimeFormat;
  long  lastTripNumber;
  long  maxTrips;
  long  patternNodes[MAXTRIPTIMES];
  long  tempLong;
  int   nI;
  int   nJ;
  int   currentRoute;
  int   currentService;
  int   numRoutes;
  int   numServices;
  int   rcode2;
  int   numNodes;

  saveTimeFormat = timeFormat;
  timeFormat = PREFERENCES_MILITARY;
//
//  Create the sub-folder for the output files and chdir into it
//
  nI = (_mkdir(OUTPUT_FOLDER_NAME) == 0) ? TEXT_333 : TEXT_334;
  LoadString(hInst, nI, szFormatString, SZFORMATSTRING_LENGTH);
  sprintf(tempString, szFormatString, OUTPUT_FOLDER_NAME);
  MessageBeep(MB_ICONINFORMATION);
  MessageBox(NULL, tempString, TMS, MB_OK);
  chdir(OUTPUT_FOLDER_NAME);
//
//  Open the output file
//
  hfOutputFile = _lcreat("tripschedule.csv", 0);
  if(hfOutputFile == HFILE_ERROR)
  {
    LoadString(hInst, ERROR_202, szFormatString, sizeof(szFormatString));
    sprintf(szarString, szFormatString, tempString);
    MessageBeep(MB_ICONSTOP);
    MessageBox((HWND)NULL, szarString, TMS, MB_ICONSTOP);
    goto deallocate;
  }
//
//  Get the number of routes and services
//  for the benefit of the status bar
//
  rcode2 = btrieve(B_STAT, TMS_ROUTES, &BSTAT, dummy, 0);
  if(rcode2 != 0 || BSTAT.numRecords == 0)
  {
    TMSError(NULL, MB_ICONSTOP, ERROR_008, (HANDLE)NULL);
    goto deallocate;
  }
  numRoutes = BSTAT.numRecords;
  rcode2 = btrieve(B_STAT, TMS_SERVICES, &BSTAT, dummy, 0);
  if(rcode2 != 0 || BSTAT.numRecords == 0)
  {
    TMSError(NULL, MB_ICONSTOP, ERROR_007, (HANDLE)NULL);
    goto deallocate;
  }
  numServices = BSTAT.numRecords;
//
//  maxTrips
//
  rcode2 = btrieve(B_STAT, TMS_TRIPS, &BSTAT, dummy, 0);
  maxTrips = rcode2 == 0 ? BSTAT.numRecords : 0;
//
//  Verify that all trips in the system are numbered
//
  StatusBarText("Checking if all trips are numbered");
  rcode2 = btrieve(B_GETFIRST, TMS_TRIPS, &TRIPS, &TRIPSKey0, 0);
  nI = 0;
  bFound = FALSE;
  lastTripNumber = NO_RECORD;
  while(rcode2 == 0)
  {
    if(StatusBarAbort())
    {
      goto deallocate;
    }
    StatusBar((long)nI, (long)maxTrips);
    if(TRIPS.tripNumber <= 0)
    {
      MessageBeep(MB_ICONQUESTION);
      LoadString(hInst, ERROR_344, tempString, TEMPSTRING_LENGTH);
      if(MessageBox(NULL, tempString, TMS, MB_ICONQUESTION | MB_OK) != IDOK)
      {
        goto deallocate;
      }
      bFound = TRUE;
      break;
    }
    if(TRIPS.tripNumber > lastTripNumber)
    {
      lastTripNumber = TRIPS.tripNumber;
    }
    nI++;
    rcode2 = btrieve(B_GETNEXT, TMS_TRIPS, &TRIPS, &TRIPSKey0, 0);
  }
  if(bFound)
  {
    StatusBarText("Renumbering Trips");
    rcode2 = btrieve(B_GETFIRST, TMS_TRIPS, &TRIPS, &TRIPSKey0, 0);
    nI = 1;
    while(rcode2 == 0)
    {
      if(StatusBarAbort())
      {
        goto deallocate;
      }
      StatusBar((long)nI, (long)maxTrips);
      TRIPS.tripNumber = (long)nI;
      nI++;
      rcode2 = btrieve(B_UPDATE, TMS_TRIPS, &TRIPS, &TRIPSKey0, 0);
      rcode2 = btrieve(B_GETNEXT, TMS_TRIPS, &TRIPS, &TRIPSKey0, 0);
    }
    lastTripNumber = nI;
  }
//
//  Loop through the routes
//
  LoadString(hInst, TEXT_117, tempString, TEMPSTRING_LENGTH);
  StatusBarStart(hWndMain, tempString);
  statbarTotal = numRoutes * numServices;
  currentRoute = 0;
  rcode2 = btrieve(B_GETFIRST, TMS_ROUTES, &ROUTES, &ROUTESKey1, 1);
  while(rcode2 == 0)
  {
    if(StatusBarAbort())
    {
      bKeepGoing = FALSE;
      goto deallocate;
    }
//
//  Do not process employee shuttles
//
    if(!(ROUTES.flags & ROUTES_FLAG_EMPSHUTTLE))
    {
//
//  Loop through the services
//
      currentService = 1;
      rcode2 = btrieve(B_GETFIRST, TMS_SERVICES, &SERVICES, &SERVICESKey1, 1);
      while(rcode2 == 0)
      {
        if(StatusBarAbort())
        {
          bKeepGoing = FALSE;
          goto deallocate;
        }
//
//  Loop through all the trips on this route/service/direction
//
        for(nI = 0; nI < 2; nI++)
        {
          if(ROUTES.DIRECTIONSrecordID[nI] == NO_RECORD)
          {
            continue;
          }
//
//  Get the trips
//
          TRIPSKey1.ROUTESrecordID = ROUTES.recordID;
          TRIPSKey1.SERVICESrecordID = SERVICES.recordID;
          TRIPSKey1.directionIndex = nI;
          TRIPSKey1.tripSequence = NO_TIME;
          rcode2 = btrieve(B_GETGREATEROREQUAL, TMS_TRIPS, &TRIPS, &TRIPSKey1, 1);
          while(rcode2 == 0 &&
                TRIPS.ROUTESrecordID == ROUTES.recordID &&
                TRIPS.SERVICESrecordID == SERVICES.recordID &&
                TRIPS.directionIndex == nI)
          {
            DIRECTIONSKey0.recordID = ROUTES.DIRECTIONSrecordID[nI];
            btrieve(B_GETEQUAL, TMS_DIRECTIONS, &DIRECTIONS, &DIRECTIONSKey0, 0);
//
//  Display where we are in the status bar
//
            strncpy(tempString, ROUTES.number, ROUTES_NUMBER_LENGTH);
            trim(tempString, ROUTES_NUMBER_LENGTH);
            strcat(tempString, " - ");
            strncpy(szarString, ROUTES.name, ROUTES_NAME_LENGTH);
            trim(szarString, ROUTES_NAME_LENGTH);
            strcat(tempString, szarString);
            strcat(tempString, "\n");
            strncpy(szarString, SERVICES.name, SERVICES_NAME_LENGTH);
            trim(szarString, SERVICES_NAME_LENGTH);
            strcat(tempString, szarString);
            strcat(tempString, " - ");
            strncpy(szarString, DIRECTIONS.longName, DIRECTIONS_LONGNAME_LENGTH);
            trim(szarString, DIRECTIONS_LONGNAME_LENGTH);
            strcat(tempString, szarString);
            StatusBarText(tempString);
            StatusBar((long)(currentRoute * (numServices - 1) + currentService), (long)statbarTotal);
            if(StatusBarAbort())
            {
              bKeepGoing = FALSE;
              goto deallocate;
            }
//
//  Build up the output string
//
//  Company Id
//
            sprintf(outputString, "%s,", COMPANY_ID);
//
//  Service name
//
            strncpy(tempString, SERVICES.name, SERVICES_NAME_LENGTH);
            trim(tempString, SERVICES_NAME_LENGTH);
            strcat(outputString, tempString);
            strcat(outputString, ",");
//
//  Trip number
//
            sprintf(tempString, "%ld,", TRIPS.tripNumber);
            strcat(outputString, tempString);
//
//  Block number
//
            sprintf(tempString, "%ld,", TRIPS.standard.blockNumber);
            strcat(outputString, tempString);
//
//  Duty number (currently unused)
//
            strcat(outputString, ",");
//
//  Pattern name
//
            PATTERNNAMESKey0.recordID = TRIPS.PATTERNNAMESrecordID;
            btrieve(B_GETEQUAL, TMS_PATTERNNAMES, &PATTERNNAMES, &PATTERNNAMESKey0, 0);
            strncpy(tempString, PATTERNNAMES.name, PATTERNNAMES_NAME_LENGTH);
            trim(tempString, PATTERNNAMES_NAME_LENGTH);
            strcat(outputString, tempString);
            strcat(outputString, ",");
//
//  Sign code
//
            SIGNCODESKey0.recordID = TRIPS.SIGNCODESrecordID;
            rcode2 = btrieve(B_GETEQUAL, TMS_SIGNCODES, &SIGNCODES, &SIGNCODESKey0, 0);
            if(rcode2 != 0)
            {
              strcpy(tempString, "");
            }
            else
            {
              strncpy(tempString, SIGNCODES.code, SIGNCODES_CODE_LENGTH);
              trim(tempString, SIGNCODES_CODE_LENGTH);
            }
            strcat(outputString, tempString);
            strcat(outputString, ",");
//
//  Nodes times
//
//  Generate the trip
//
            GenerateTrip(TRIPS.ROUTESrecordID, TRIPS.SERVICESrecordID,
                  TRIPS.directionIndex, TRIPS.PATTERNNAMESrecordID,
                  TRIPS.timeAtMLP, GENERATETRIP_FLAG_DISPLAYERRORS, &GTResults);
//
//  Get the pattern nodes
//
            PATTERNSKey2.ROUTESrecordID = TRIPS.ROUTESrecordID;
            PATTERNSKey2.SERVICESrecordID = TRIPS.SERVICESrecordID;
            PATTERNSKey2.PATTERNNAMESrecordID = TRIPS.PATTERNNAMESrecordID;
            PATTERNSKey2.directionIndex = TRIPS.directionIndex;
            PATTERNSKey2.nodeSequence = NO_RECORD;
            numNodes = 0;
            rcode2 = btrieve(B_GETGREATER, TMS_PATTERNS, &PATTERNS, &PATTERNSKey2, 2);
            while(rcode2 == 0 &&
                  PATTERNS.ROUTESrecordID == TRIPS.ROUTESrecordID &&
                  PATTERNS.SERVICESrecordID == TRIPS.SERVICESrecordID &&
                  PATTERNS.PATTERNNAMESrecordID == TRIPS.PATTERNNAMESrecordID &&
                  PATTERNS.directionIndex == TRIPS.directionIndex)
            {
              if(!(PATTERNS.flags & PATTERNS_FLAG_BUSSTOP))
              {
                patternNodes[numNodes] = PATTERNS.NODESrecordID;
                numNodes++;
              }
              rcode2 = btrieve(B_GETNEXT, TMS_PATTERNS, &PATTERNS, &PATTERNSKey2, 2);
            }
//
//  tripTimes[] contains the times at the timepoints in this pattern
//
//  We're only interested in departure times, so if we
//  run into an arrive/leave, skip over the arrive time
//
            for(nJ = 0; nJ < numNodes; nJ++)
            {
              if(nJ < numNodes - 1)
              {
                if(NodesEquivalent(patternNodes[nJ], patternNodes[nJ + 1], &tempLong))
                {
                  continue;
                }
              }
              strcat(outputString, Tchar(GTResults.tripTimes[nJ]));
              strcat(outputString, " ");
            }
//
//  End of record
//
            strcat(outputString, "\r\n");
//
//  Write it out
//
            _lwrite(hfOutputFile, outputString, strlen(outputString));
//
//  Next trip
//
            rcode2 = btrieve(B_GETNEXT, TMS_TRIPS, &TRIPS, &TRIPSKey1, 1);
          }
//
//  Next direction
//
        }  // nI
//
//  Next service
//
        currentService++;
        rcode2 = btrieve(B_GETNEXT, TMS_SERVICES, &SERVICES, &SERVICESKey1, 1);
      }
//
//  Not a shuttle
//
    }
//
//  Next route
//
    currentRoute++;
    rcode2 = btrieve(B_GETNEXT, TMS_ROUTES, &ROUTES, &ROUTESKey1, 1);
  }
  bKeepGoing = TRUE;
//
//  Free allocated memory
//
  deallocate:
    timeFormat = saveTimeFormat;
    _lclose(hfOutputFile);
    StatusBarEnd();
    chdir("..");
//
//  Let him know
//
  strcpy(tempString, "Download of tripschedule.csv complete\n");
  MessageBox(hWndMain, tempString, TMS, MB_OK);

  if(!bKeepGoing)
  {
    return(FALSE);
  }
//
//  All done
//
  return(TRUE);
}
コード例 #23
0
ファイル: ScreenSave.cpp プロジェクト: cwilko/voxelMap
int SaveScreen() {

	// String buffers for the filenames
	
	char test[] = "anim\\pic";
	char format[] = ".bmp";

	char file[40];
	char file2[40];
	char file3[40];

	// Create the correct file paths and names in the buffers

	sprintf(file, "anim\\pic%d.bmp", frame++);
	sprintf(file3, "Work___Win32_Release\\anim\\pic%d.bmp", frame );
	sprintf(file2, "Work___Win32_Release\\%s", file);

	// Create a pointer to a screen buffer

	UCHAR *screen_buffer = NULL;

	// Assign the pointer to the display

	screen_buffer = (UCHAR *) ddsd.lpSurface;

	// Set the pixel position to the lower left corner

	screen_buffer += (SCREEN_WIDTH * (SCREEN_HEIGHT - 1));


	// Open pic0.bmp for writing

	#define BITMAP_ID        0x4D42				// this is the universal id for a bitmap

	int      file_handle;						// the file handle
	bitmap_file_ptr bitmap = new bitmap_file;	// the bitmap header structure


	OFSTRUCT file_data;							// the file data information

	// open the file if it exists

	if ((file_handle = OpenFile(file,&file_data,OF_READWRITE))==-1)
		return(0);
 
	// Now load the bitmap file header
	
	_lread(file_handle, &bitmap->bitmapfileheader,sizeof(BITMAPFILEHEADER));

	// Test if this is a bitmap file
	if (bitmap->bitmapfileheader.bfType!=BITMAP_ID) {
	
		// close the file
		_lclose(file_handle);
 
		// return error
		return(0);

	} // end if


	// Load the bitmap file header
	
	_lread(file_handle, &bitmap->bitmapinfoheader,sizeof(BITMAPINFOHEADER));


	// Write the palette to the file
	_lwrite(file_handle, (char*) colour_palette,256*sizeof(PALETTEENTRY));
	
	
	// Find the start of the image data
	_lseek(file_handle,-(int)(bitmap->bitmapinfoheader.biSizeImage),SEEK_END);


	// Overwrite the image data in the file

	for (int i=0; i<SCREEN_HEIGHT; i++) {

		_lwrite(file_handle,(char*) screen_buffer,SCREEN_WIDTH * sizeof(UCHAR));
		screen_buffer -= SCREEN_WIDTH;
	
	}


	// Deallocate bitmap header
	delete bitmap;

	// close the file
	_lclose(file_handle);

	// Copy the file to another ( for animation frames )

	CopyFile(file2, file3,TRUE);

	return 1;

}
コード例 #24
0
ファイル: Text.c プロジェクト: atrniv/CLIPS
BOOL text_Revert(
  HWND hwnd,
  char *fileName,
  HWND hEditWnd)
  {
   int hFile;
   OFSTRUCT OfStruct;
   long text_length;
   char *pEditBuffer;
   HICON hSaveCursor;
   unsigned ioStatus;
   char szTemp[128];
   struct textWindowData *theData;
   
   theData = (struct textWindowData *) GetWindowLong(hEditWnd,GWL_USERDATA);
 
   
   /*===================================*/
   /* Open the file and get its handle. */
   /*===================================*/
   
   /* TBD Replace OpenFile with CreateFile. */
   
   if (theData == NULL)
     {
      hFile = OpenFile((LPSTR) fileName,
                       (LPOFSTRUCT) &OfStruct,
                       OF_READ);
     }
   else
     {
      hFile = OpenFile((LPSTR) (char *) &theData->fileName,
                       (LPOFSTRUCT) &OfStruct,
                       OF_READ);
     }
     
   if (hFile == HFILE_ERROR)
     { return (FALSE); }
 
   /*=====================*/
   /* Update window data. */
   /*=====================*/
   
   if (theData == NULL)
     { 
      theData = (struct textWindowData *) malloc(sizeof(struct textWindowData));
      if (theData == NULL) return(FALSE);
      
      strcpy((char *) &theData->fileName,(char *) fileName);
      SetWindowLong(hEditWnd,GWL_USERDATA,(long) theData);
     }
   
   /*===================================================*/
   /* Allocate edit buffer to the size of the file + 1. */
   /*===================================================*/
   
   text_length = _llseek(hFile,0,2); 
   _llseek(hFile,0,0); 

   if (text_length > 65534L) 
     {
      MessageBox(hwnd, "Can't load files larger than 65,534 bytes long !",
                 "FILE READ ERROR", MB_OK | MB_ICONEXCLAMATION);
      _lclose(hFile);
      return (FALSE);
     }

   pEditBuffer = (char *) malloc((size_t) text_length+1);

   if (pEditBuffer == NULL)
     {
      MessageBox(hwnd,"Not enough memory.",
                 NULL,MB_OK | MB_ICONEXCLAMATION);
      _lclose(hFile);
      return (FALSE);
     }

   hSaveCursor = SetCursor(hHourGlass);
        
   ioStatus = _lread(hFile,pEditBuffer,(UINT) text_length);
   pEditBuffer[text_length] = '\0';
   _lclose(hFile); 

   /*====================================*/
   /* # bytes read must equal file size. */
   /*====================================*/

   if (((long) ioStatus) != text_length)
	 {
      sprintf(szTemp,"Error reading %s tl %ld IO %ld.",
	          fileName,text_length,ioStatus);
      SetCursor(hSaveCursor);      
      MessageBox(hwnd,szTemp,NULL,MB_OK | MB_ICONEXCLAMATION);
     }
   else
     { 
      hEditWnd = GetDlgItem(hEditWnd,ID_EDIT_CONTROL);
      SendMessage(hEditWnd,WM_SETTEXT,0,(LPARAM) pEditBuffer);
      FixTextLineEndings(hEditWnd);
     }

   free(pEditBuffer);
    
   /*=======================================*/
   /* Set up a new buffer and window title. */
   /*=======================================*/	 
     
   //sprintf(szTemp, "Edit File - (%s)", szFileTitle);
   //SetNewBuffer(hWnd,(LPSTR)&szTemp);
   SetCursor(hSaveCursor);
   
   return(TRUE);
  }
コード例 #25
0
ファイル: Tmsrpt30.c プロジェクト: ems/TMS
BOOL FAR TMSRPT30(TMSRPTPassedDataDef *pPassedData)
{
  DISPATCHSHEETPassedDataDef RParamData;
  DISPATCHSHEETRosterDataDef RData[MAXRUNSINRUNLIST];
  PROPOSEDRUNDef PROPOSEDRUN;
  COSTDef  COST;
  HFILE hfOutputFile;
  BOOL  bFound;
  char  lastName[DRIVERS_LASTNAME_LENGTH + 1];
  char  firstName[DRIVERS_FIRSTNAME_LENGTH + 1];
  char  badgeNumber[DRIVERS_BADGENUMBER_LENGTH + 1];
  char  abbrName[NODES_ABBRNAME_LENGTH + 1];
  char  outputString[TEMPSTRING_LENGTH];
  char  *pszReportName;
  long  onTime;
  long  offTime;
  long  seq;
  long  time;
  long  flatPay;
  long  makeUpTime;
  long  pieceNumber;
  long  runNumber;
  long  cutAsRuntype;
  long  startTime;
  long  onNode;
  long  offNode;
  int   numRuns;
  int   nI;
  int   nJ;
  int   numPieces;
  int   rcode2;
//
//  See what he wants to unload
//
  RParamData.flags = 0;
  RParamData.nReportNumber = 29;
  if(DispatchSheet(&RParamData) != IDOK)
    return(FALSE);
  if(ROSTERPARMS.serviceDays[RParamData.dayOfWeek] == NO_RECORD)
  {
    TMSError(hWndMain, MB_ICONSTOP, ERROR_318, (HANDLE)NULL);
    return(FALSE);
  }
//
//  Back ok - set up the status bar
//
  pPassedData->nReportNumber = 29;
  pPassedData->numDataFiles = 1;
  for(nI = 0; nI < m_LastReport; nI++)
  {
    if(TMSRPT[nI].originalReportNumber == pPassedData->nReportNumber)
    {
      pszReportName = TMSRPT[nI].szReportName;
      StatusBarStart(hWndMain, TMSRPT[nI].szReportName);
      break;
    }
  }
//
//  Open the output file
//
  StatusBarText("Opening output file...");
  strcpy(tempString, szReportsTempFolder);
  strcat(tempString, "\\tmsrpt30.txt");
  hfOutputFile = _lcreat(tempString, 0);
  if(hfOutputFile == HFILE_ERROR)
  {
    LoadString(hInst, ERROR_202, szFormatString, sizeof(szFormatString));
    sprintf(szarString, szFormatString, tempString);
    MessageBeep(MB_ICONSTOP);
    MessageBox((HWND)NULL, szarString, TMS, MB_ICONSTOP);
    goto deallocate;
  }
  strcpy(pPassedData->szReportDataFile[0], tempString);
  StatusBar(-1L, -1L);
//
//  Loop through the roster to set up drivers, their associated
//  runs, and the start time of each run.  There's a data integrity
//  check here to ensure that the run pointed to by the roster actually exists.
//
  StatusBarText("Examining the roster...");
  numRuns = 0;
  ROSTERKey1.DIVISIONSrecordID = RParamData.DIVISIONSrecordID;
  ROSTERKey1.rosterNumber = NO_RECORD;
  rcode2 = btrieve(B_GETGREATER, TMS_ROSTER, &ROSTER, &ROSTERKey1, 1);
  while(rcode2 == 0 &&
        ROSTER.DIVISIONSrecordID == RParamData.DIVISIONSrecordID)
  {
    if(StatusBarAbort())
    {
      goto deallocate;
    }
    if(ROSTER.WEEK[m_RosterWeek].RUNSrecordIDs[RParamData.dayOfWeek] != NO_RECORD)
    {
      if(ROSTER.WEEK[m_RosterWeek].flags & (1 << RParamData.dayOfWeek))  // Crew-only run
      {
        CREWONLYKey0.recordID = ROSTER.WEEK[m_RosterWeek].RUNSrecordIDs[RParamData.dayOfWeek];
        rcode2 = btrieve(B_GETEQUAL, TMS_CREWONLY, &CREWONLY, &CREWONLYKey0, 0);
        if(rcode2 == 0)
        {
          RData[numRuns].flags = RDATA_FLAG_CREWONLY;
          RData[numRuns].DRIVERSrecordID = ROSTER.DRIVERSrecordID;
          RData[numRuns].RUNSrecordID = ROSTER.WEEK[m_RosterWeek].RUNSrecordIDs[RParamData.dayOfWeek];
          RData[numRuns].startTime = CREWONLY.startTime;
          RData[numRuns].runNumber = CREWONLY.runNumber;
          RData[numRuns].replacementDRIVERSrecordID = NO_RECORD;
          RData[numRuns].rosterNumber = NO_RECORD;
          RData[numRuns].BUSESrecordID = NO_RECORD;
          RData[numRuns].blockNumber = NO_RECORD;
          RData[numRuns].TRIPSrecordID = NO_RECORD;
          RData[numRuns].RGRPROUTESrecordID = NO_RECORD;
          RData[numRuns].SGRPSERVICESrecordID = NO_RECORD;
          numRuns++;
        }
      }
      else
      {
        RUNSKey0.recordID = ROSTER.WEEK[m_RosterWeek].RUNSrecordIDs[RParamData.dayOfWeek];
        rcode2 = btrieve(B_GETEQUAL, TMS_RUNS, &RUNS, &RUNSKey0, 0);
        if(rcode2 == 0)
        {
          RData[numRuns].flags = 0;
          RData[numRuns].DRIVERSrecordID = ROSTER.DRIVERSrecordID;
          RData[numRuns].RUNSrecordID = ROSTER.WEEK[m_RosterWeek].RUNSrecordIDs[RParamData.dayOfWeek];
          RunStartAndEnd(RUNS.start.TRIPSrecordID, RUNS.start.NODESrecordID,
                NO_RECORD, NO_RECORD, &onTime, &offTime);
          RData[numRuns].startTime = onTime;
          RData[numRuns].runNumber = RUNS.runNumber;
          RData[numRuns].replacementDRIVERSrecordID = NO_RECORD;
          RData[numRuns].rosterNumber = NO_RECORD;
          RData[numRuns].BUSESrecordID = NO_RECORD;
          RData[numRuns].blockNumber = NO_RECORD;
          RData[numRuns].TRIPSrecordID = RUNS.start.TRIPSrecordID;
          RData[numRuns].RGRPROUTESrecordID = NO_RECORD;
          RData[numRuns].SGRPSERVICESrecordID = NO_RECORD;
          numRuns++;
        }
      }
    }
    rcode2 = btrieve(B_GETNEXT, TMS_ROSTER, &ROSTER, &ROSTERKey1, 1);
  }
//
//  Now go through the runs to add any unassigned runs to RData
//
  StatusBarText("Setting up unassigned runs...");
  RUNSKey1.DIVISIONSrecordID = RParamData.DIVISIONSrecordID;
  RUNSKey1.SERVICESrecordID = ROSTERPARMS.serviceDays[RParamData.dayOfWeek];
  RUNSKey1.runNumber = NO_RECORD;
  RUNSKey1.pieceNumber = NO_RECORD;
  rcode2 = btrieve(B_GETGREATER, TMS_RUNS, &RUNS, &RUNSKey1, 1);
  while(rcode2 == 0 && 
        RUNS.DIVISIONSrecordID == RParamData.DIVISIONSrecordID &&
        RUNS.SERVICESrecordID == ROSTERPARMS.serviceDays[RParamData.dayOfWeek])
  {
    if(StatusBarAbort())
    {
      goto deallocate;
    }
    if(RUNS.pieceNumber == 1)
    {
      for(bFound = FALSE, nI = 0; nI < numRuns; nI++)
      {
        if(RUNS.recordID == RData[nI].RUNSrecordID &&
              !(RData[nI].flags & RDATA_FLAG_CREWONLY))
        {
          bFound = TRUE;
          break;
        }
      }
      if(!bFound)
      {
        RData[numRuns].DRIVERSrecordID = NO_RECORD;
        RData[numRuns].RUNSrecordID = RUNS.recordID;
        RunStartAndEnd(RUNS.start.TRIPSrecordID, RUNS.start.NODESrecordID,
              NO_RECORD, NO_RECORD, &onTime, &offTime);
        RData[numRuns].startTime = onTime;
        RData[numRuns].runNumber = RUNS.runNumber;
        RData[numRuns].replacementDRIVERSrecordID = NO_RECORD;
        RData[numRuns].rosterNumber = NO_RECORD;
        RData[numRuns].BUSESrecordID = NO_RECORD;
        RData[numRuns].blockNumber = NO_RECORD;
        RData[numRuns].TRIPSrecordID = RUNS.start.TRIPSrecordID;
        RData[numRuns].RGRPROUTESrecordID = NO_RECORD;
        RData[numRuns].SGRPSERVICESrecordID = NO_RECORD;
        RData[numRuns].flags = 0;
        numRuns++;
      }
    }
    rcode2 = btrieve(B_GETNEXT, TMS_RUNS, &RUNS, &RUNSKey1, 1);
  }
//
//  Now go through the runs to add any unassigned crew-only runs to RData
//
  CREWONLYKey1.DIVISIONSrecordID = RParamData.DIVISIONSrecordID;
  CREWONLYKey1.SERVICESrecordID = ROSTERPARMS.serviceDays[RParamData.dayOfWeek];
  CREWONLYKey1.runNumber = NO_RECORD;
  CREWONLYKey1.pieceNumber = NO_RECORD;
  rcode2 = btrieve(B_GETGREATER, TMS_CREWONLY, &CREWONLY, &CREWONLYKey1, 1);
  while(rcode2 == 0 && 
        CREWONLY.DIVISIONSrecordID == RParamData.DIVISIONSrecordID &&
        CREWONLY.SERVICESrecordID == ROSTERPARMS.serviceDays[RParamData.dayOfWeek])
  {
    if(StatusBarAbort())
    {
      goto deallocate;
    }
    if(CREWONLY.pieceNumber == 1)
    {
      for(bFound = FALSE, nI = 0; nI < numRuns; nI++)
      {
        if(CREWONLY.recordID == RData[nI].RUNSrecordID &&
              (RData[nI].flags & RDATA_FLAG_CREWONLY))
        {
          bFound = TRUE;
          break;
        }
      }
      if(!bFound)
      {
        RData[numRuns].flags = RDATA_FLAG_CREWONLY;
        RData[numRuns].DRIVERSrecordID = NO_RECORD;
        RData[numRuns].RUNSrecordID = CREWONLY.recordID;
        RData[numRuns].startTime = CREWONLY.startTime;
        RData[numRuns].runNumber = CREWONLY.runNumber;
        RData[numRuns].replacementDRIVERSrecordID = NO_RECORD;
        RData[numRuns].rosterNumber = NO_RECORD;
        RData[numRuns].BUSESrecordID = NO_RECORD;
        RData[numRuns].blockNumber = NO_RECORD;
        RData[numRuns].TRIPSrecordID = NO_RECORD;
        RData[numRuns].RGRPROUTESrecordID = NO_RECORD;
        RData[numRuns].SGRPSERVICESrecordID = NO_RECORD;
        numRuns++;
      }
    }
    rcode2 = btrieve(B_GETNEXT, TMS_CREWONLY, &CREWONLY, &CREWONLYKey1, 1);
  }
//
//  Check for changes made via Daily Ops
//
  AdjustDispatchSheetRosterData(&RData[0], RParamData.todaysDate, RParamData.date, numRuns, TRUE, FALSE);
//
//  Sort by run number
//
  qsort((void *)RData, numRuns, sizeof(DISPATCHSHEETRosterDataDef), sort_TMSRPT30);
//
//  Generate the run details, and print them
//  out along with any associated driver data.
//
  StatusBarText("Generating run details...");
  seq = 0;
//
//  Initialize the travel matrix
//
  StatusBarEnd();
  if(bUseDynamicTravels)
  {
    SERVICESKey0.recordID = ROSTERPARMS.serviceDays[RParamData.dayOfWeek];
    btrieve(B_GETEQUAL, TMS_SERVICES, &SERVICES, &SERVICESKey0, 0);
    LoadString(hInst, bUseCISPlan ? TEXT_154 : TEXT_135, tempString, TEMPSTRING_LENGTH);
    StatusBarText(tempString);
    if(bUseCISPlan)
    {
      CISfree();
      if(!CISbuildService(FALSE, TRUE, SERVICES.recordID))
        goto deallocate;
    }
    else
    {
      InitTravelMatrix(SERVICES.recordID, FALSE);
    }
  }
//
//  Cycle through the runs
//
  StatusBarStart(hWndMain, pszReportName);
  StatusBarText("Cycling through the runs...");
  for(nI = 0; nI < numRuns; nI++)
  {
    StatusBar((long)(nI + 1), (long)numRuns);
    if(StatusBarAbort())
    {
      goto deallocate;
    }
//
//  Run data
//
    if(RData[nI].flags & RDATA_FLAG_CREWONLY)
    {
      CREWONLYKey0.recordID = RData[nI].RUNSrecordID;
      btrieve(B_GETEQUAL, TMS_CREWONLY, &CREWONLY, &CREWONLYKey0, 0);
    }
    else
    {
      RUNSKey0.recordID = RData[nI].RUNSrecordID;
      btrieve(B_GETEQUAL, TMS_RUNS, &RUNS, &RUNSKey0, 0);
    }
//
//  Set up the output string
//
//  Sequence # and Service
//
    sprintf(outputString, "%d\t%s\t", seq++, RParamData.szDate);
//
//  Driver
//
    if(RData[nI].replacementDRIVERSrecordID != NO_RECORD)
    {
      DRIVERSKey0.recordID = RData[nI].replacementDRIVERSrecordID;
    }
    else if(RData[nI].DRIVERSrecordID != NO_RECORD)
    {
      DRIVERSKey0.recordID = RData[nI].DRIVERSrecordID;
    }
    else
    {
      DRIVERSKey0.recordID = NO_RECORD;
    }
    if(DRIVERSKey0.recordID != NO_RECORD)
    {
      btrieve(B_GETEQUAL, TMS_DRIVERS, &DRIVERS, &DRIVERSKey0, 0);
      strncpy(badgeNumber, DRIVERS.badgeNumber, DRIVERS_BADGENUMBER_LENGTH);
      trim(badgeNumber, DRIVERS_BADGENUMBER_LENGTH);
      strncpy(lastName, DRIVERS.lastName, DRIVERS_LASTNAME_LENGTH);
      trim(lastName, DRIVERS_LASTNAME_LENGTH);
      strncpy(firstName, DRIVERS.firstName, DRIVERS_FIRSTNAME_LENGTH);
      trim(firstName, DRIVERS_FIRSTNAME_LENGTH);
      strcat(outputString, badgeNumber);
      strcat(outputString, " - ");
      strcat(outputString, lastName);
      strcat(outputString, ", ");
      strcat(outputString, firstName);
    }
    strcat(outputString, "\t");
//
//  Run number
//
    sprintf(tempString, "%ld\t", RData[nI].runNumber);
    strcat(outputString, tempString);
//
//  Run details
//
    makeUpTime = 0;
//
//  Crew only
//
    if(RData[nI].flags & RDATA_FLAG_CREWONLY)
    {
      btrieve(B_GETPOSITION, TMS_CREWONLY, &CREWONLY, &CREWONLYKey0, 0);
      rcode2 = btrieve(B_GETDIRECT, TMS_CREWONLY, &CREWONLY, &CREWONLYKey1, 1);
      pieceNumber = 0;
      runNumber = CREWONLY.runNumber;
      while(rcode2 == 0 && CREWONLY.runNumber == runNumber)
      {
        onTime = CREWONLY.startTime;
        offTime = CREWONLY.endTime;
        if(CREWONLY.pieceNumber == 1)
        {
          cutAsRuntype = CREWONLY.cutAsRuntype;
          startTime = onTime;
          onNode = CREWONLY.startNODESrecordID;
        }
        PROPOSEDRUN.piece[pieceNumber].fromTime = onTime;
        PROPOSEDRUN.piece[pieceNumber].fromNODESrecordID = CREWONLY.startNODESrecordID;
        PROPOSEDRUN.piece[pieceNumber].fromTRIPSrecordID = NO_RECORD;
        PROPOSEDRUN.piece[pieceNumber].toTime = offTime;
        PROPOSEDRUN.piece[pieceNumber].toNODESrecordID = CREWONLY.endNODESrecordID;
        PROPOSEDRUN.piece[pieceNumber].toTRIPSrecordID = NO_RECORD;
        PROPOSEDRUN.piece[pieceNumber].prior.startTime = NO_TIME;
        PROPOSEDRUN.piece[pieceNumber].prior.endTime = NO_TIME;
        PROPOSEDRUN.piece[pieceNumber].after.startTime = NO_TIME;
        PROPOSEDRUN.piece[pieceNumber++].after.endTime = NO_TIME;
        offNode = CREWONLY.endNODESrecordID;
        rcode2 = btrieve(B_GETNEXT, TMS_CREWONLY, &CREWONLY, &CREWONLYKey1, 1);
      }
      PROPOSEDRUN.numPieces = pieceNumber;
      RunCoster(&PROPOSEDRUN, cutAsRuntype, &COST);
      numPieces = PROPOSEDRUN.numPieces;
      for(nJ = 0; nJ < numPieces; nJ++)
      {
        RUNSVIEW[nJ].platformTime = COST.PIECECOST[nJ].platformTime;
        RUNSVIEW[nJ].makeUpTime = COST.PIECECOST[nJ].makeUpTime;
        RUNSVIEW[nJ].reportTime = COST.PIECECOST[nJ].reportTime;
        RUNSVIEW[nJ].turninTime = COST.PIECECOST[nJ].turninTime;
        RUNSVIEW[nJ].travelTime = COST.TRAVEL[nJ].startTravelTime + COST.TRAVEL[nJ].endTravelTime;
        RUNSVIEW[nJ].paidBreaks = COST.PIECECOST[nJ].paidBreak;
        RUNSVIEW[nJ].blockNumber = NO_RECORD;
        RUNSVIEW[nJ].runOnNODESrecordID = PROPOSEDRUN.piece[nJ].fromNODESrecordID;
        RUNSVIEW[nJ].runOnTime = PROPOSEDRUN.piece[nJ].fromTime;
        RUNSVIEW[nJ].runOffTime = PROPOSEDRUN.piece[nJ].toTime;
        RUNSVIEW[nJ].runOffNODESrecordID = PROPOSEDRUN.piece[nJ].toNODESrecordID;
      }
    }
//
//  Regular run
//
    else
    {
      numPieces = GetRunElements(hWndMain, &RUNS, &PROPOSEDRUN, &COST, TRUE);
    }
//
//  Cycle through the pieces
//
    for(nJ = 0; nJ < numPieces; nJ++)
    {
      if(nJ != 0)
      {
        sprintf(outputString,
              "%d\t%s\t\t%ld\t", seq++, RParamData.szDate, RData[nI].runNumber);
      }
//
//  Block number
//
      if(RUNSVIEW[nJ].blockNumber != NO_RECORD)
      {
        sprintf(tempString, "%ld\t", RUNSVIEW[nJ].blockNumber);
      }
      else
      {
        strcpy(tempString, "STBY\t");
      }
      strcat(outputString, tempString);
//
//  Location of origin
//
      NODESKey0.recordID = RUNSVIEW[nJ].runOnNODESrecordID;
      btrieve(B_GETEQUAL, TMS_NODES, &NODES, &NODESKey0, 0);
      strncpy(abbrName, NODES.abbrName, NODES_ABBRNAME_LENGTH);
      trim(abbrName, NODES_ABBRNAME_LENGTH);
      strcat(outputString, abbrName);
      strcat(outputString, "\t");
//
//  Time of report
//
      time = RUNSVIEW[nJ].runOnTime - RUNSVIEW[nJ].reportTime;
      if(RParamData.flags & DISPATCHSHEET_FLAG_INCLUDESTARTOFPIECETRAVEL)
        time -= RUNSVIEW[nJ].startOfPieceTravel;
      if(RUNSVIEW[nJ].startOfPieceExtraboardStart != NO_TIME)
        time = RUNSVIEW[nJ].startOfPieceExtraboardStart;
      strcat(outputString, Tchar(time));
      strcat(outputString, "\t");
// 
//  On time
//
      strcat(outputString, Tchar(RUNSVIEW[nJ].runOnTime));
      strcat(outputString, "\t");
//
//  Off time
//
      strcat(outputString, Tchar(RUNSVIEW[nJ].runOffTime));
      strcat(outputString, "\t");
//
//  Location of destination
//
      NODESKey0.recordID = RUNSVIEW[nJ].runOffNODESrecordID;
      btrieve(B_GETEQUAL, TMS_NODES, &NODES, &NODESKey0, 0);
      strncpy(abbrName, NODES.abbrName, NODES_ABBRNAME_LENGTH);
      trim(abbrName, NODES_ABBRNAME_LENGTH);
      strcat(outputString, abbrName);
      strcat(outputString, "\t");
//
//  Platform time
//
      strcat(outputString, Tdec(RUNSVIEW[nJ].platformTime));
      strcat(outputString, "\t");
//
//  Report time
//
      if(RUNSVIEW[nJ].reportTime > 0)
        strcat(outputString, Tdec(RUNSVIEW[nJ].reportTime));
      strcat(outputString, "\t");
//
//  Pad time
//
      if(RUNSVIEW[nJ].makeUpTime > 0)
        makeUpTime += RUNSVIEW[nJ].makeUpTime;
      if(RUNSVIEW[nJ].paidBreaks > 0)
        makeUpTime += RUNSVIEW[nJ].paidBreaks;
      if(makeUpTime > 0)
        strcat(outputString, Tdec(makeUpTime));
      strcat(outputString, "\t");
//
//  Spread time
//
      strcat(outputString, "\t");
//
//  Travel and Dwell Time
//
      if(RUNSVIEW[nJ].travelTime > 0)
        strcat(outputString, Tdec(RUNSVIEW[nJ].travelTime));
      strcat(outputString, "\t\r\n");
//
//  Write it out
//
      _lwrite(hfOutputFile, outputString, strlen(outputString));
    }
//
//  Write out the summary record
//
    sprintf(outputString,
          "%d\t%s\t\t%ld\t\t\t\t\t\tTotals\t", seq++, RParamData.szDate, RData[nI].runNumber);
//
//  Sum the platform, report, makeup, travel, and intervening times
//
//  Change all NO_TIMEs to 0
//
    for(nJ = 0; nJ < numPieces; nJ++)
    {
      if(RUNSVIEW[nJ].platformTime == NO_TIME)
        RUNSVIEW[nJ].platformTime = 0;
      if(RUNSVIEW[nJ].makeUpTime == NO_TIME)
        RUNSVIEW[nJ].makeUpTime = 0;
      if(RUNSVIEW[nJ].reportTime == NO_TIME)
        RUNSVIEW[nJ].reportTime = 0;
      if(RUNSVIEW[nJ].travelTime == NO_TIME)
        RUNSVIEW[nJ].travelTime = 0;
      if(RUNSVIEW[nJ].paidBreaks == NO_TIME)
        RUNSVIEW[nJ].paidBreaks = 0;
      if(RUNSVIEW[nJ].turninTime == NO_TIME)
        RUNSVIEW[nJ].turninTime = 0;
    }
//
//  Generate the sums
//
    for(nJ = 1; nJ < numPieces; nJ++)
    {
      RUNSVIEW[0].platformTime += RUNSVIEW[nJ].platformTime;
      RUNSVIEW[0].makeUpTime += RUNSVIEW[nJ].makeUpTime;
      RUNSVIEW[0].reportTime += RUNSVIEW[nJ].reportTime;
      RUNSVIEW[0].turninTime += RUNSVIEW[nJ].turninTime;
      RUNSVIEW[0].travelTime += RUNSVIEW[nJ].travelTime;
      RUNSVIEW[0].paidBreaks += RUNSVIEW[nJ].paidBreaks;
    }
//
//  And write them out
//
//  Platform time
//
    strcat(outputString, Tdec(RUNSVIEW[0].platformTime));
    strcat(outputString, "\t");
    flatPay = RUNSVIEW[0].platformTime;
//
//  Report and turnin time
//
    if(RUNSVIEW[0].reportTime > 0 || RUNSVIEW[0].turninTime > 0)
    {
      strcat(outputString, Tdec(RUNSVIEW[0].reportTime + RUNSVIEW[0].turninTime));
      flatPay += RUNSVIEW[0].reportTime + RUNSVIEW[0].turninTime;
    }
    strcat(outputString, "\t");
//
//  Pad time
//
    makeUpTime = 0;
    if(RUNSVIEW[0].makeUpTime > 0)
      makeUpTime += RUNSVIEW[0].makeUpTime;
    if(RUNSVIEW[0].paidBreaks > 0)
      makeUpTime += RUNSVIEW[0].paidBreaks;
    if(makeUpTime > 0)
    {
      strcat(outputString, Tdec(makeUpTime));
      flatPay += makeUpTime;
    }
    strcat(outputString, "\t");
//
//  Spread overtime
//
    if(RUNSVIEW[numPieces - 1].spreadOT > 0)
    {
      strcat(outputString, Tdec(RUNSVIEW[numPieces - 1].spreadOT));
      flatPay += RUNSVIEW[numPieces - 1].spreadOT;
    }
    strcat(outputString, "\t");
//
//  Travel and Dwell Time
//
    if(RUNSVIEW[0].travelTime > 0)
    {
      strcat(outputString, Tdec(RUNSVIEW[0].travelTime));
      flatPay += RUNSVIEW[0].travelTime;
    }
    strcat(outputString, "\t");
//
//  Flat Pay time
//
    strcat(outputString, Tdec(flatPay));
    strcat(outputString, "\t");
//
//  School?
//
    strcat(outputString, "\r\n");
//
//  Write it out
//
    _lwrite(hfOutputFile, outputString, strlen(outputString));
  }

//
//  All done
//
  deallocate:
    StatusBarEnd();
    _lclose(hfOutputFile);

  return(TRUE);
}
コード例 #26
0
ファイル: Text.c プロジェクト: atrniv/CLIPS
BOOL text_Save(
  HWND hwnd)
  {
   HWND hEditWnd;
   struct textWindowData *theData;
   HFILE hFile;
   OFSTRUCT OfStruct;
   char szTemp[398];
   int text_length; 
   char *pEditBuffer;
   HICON hSaveCursor;
   unsigned ioStatus;
   BOOL bSuccess;
   
   //hEditWnd = GetFirstChild(MDIClientWnd);
   hEditWnd = hwnd;
   
   /*======================*/
   /* Get the window data. */
   /*======================*/
   
   theData = (struct textWindowData *) GetWindowLong(hEditWnd,GWL_USERDATA);
   if (theData == NULL)
     {
	  if (! GetSaveFileName ((LPOPENFILENAME) &ofn))
        { return(FALSE); }
        
      theData = (struct textWindowData *) malloc(sizeof(struct textWindowData));
      if (theData == NULL) 
        { return(FALSE); }
        
      strcpy((char *) &theData->fileName,(char *) szFileName);
      SetWindowLong(hEditWnd,GWL_USERDATA,(long) theData);
      SetWindowText(hEditWnd,szFileName);
     }

   if ((hFile = OpenFile(theData->fileName, &OfStruct, OF_CANCEL | OF_CREATE)) < 0)
     {  
      sprintf(szTemp, "Cannot write to %s.",theData->fileName);
      MessageBox(hwnd,szTemp,NULL,MB_OK | MB_ICONHAND);
      return (FALSE);
     }
     
   hEditWnd = GetDlgItem(hEditWnd,ID_EDIT_CONTROL);
   text_length = SendMessage(hEditWnd,WM_GETTEXTLENGTH,0,0);
   pEditBuffer = (char *) malloc((size_t) text_length+1);

   if (pEditBuffer == NULL)
     {
      sprintf(szTemp, "Not enough memory to save %s.", theData->fileName);
      MessageBox(hwnd, szTemp, NULL, MB_OK | MB_ICONHAND);
      _lclose(hFile);
      return (FALSE);
	 }

   SendMessage(hEditWnd,WM_GETTEXT,(unsigned) text_length+1,(LPARAM) pEditBuffer);

   /*==========================================================*/
   /* Set the cursor to an hourglass during the file transfer. */
   /*==========================================================*/

   hSaveCursor = SetCursor(hHourGlass);
   
   ioStatus = _lwrite(hFile,pEditBuffer,strlen(pEditBuffer));

   _lclose(hFile);

   SetCursor(hSaveCursor);

   if (ioStatus != strlen(pEditBuffer))
     { 
      sprintf(szTemp, "Error writing to %s.", theData->fileName);
      MessageBox(hwnd, szTemp, NULL, MB_OK | MB_ICONHAND);
      bSuccess = FALSE;
     }
   else
     {  
      bSuccess = TRUE;     
      SendMessage(hEditWnd,EM_SETMODIFY,
                  (WPARAM) (UINT) FALSE, (LPARAM) 0);
     }
     
   free(pEditBuffer);
   return (bSuccess);
  }
コード例 #27
0
LPPALETTE ReadPalette( LPSTR lpFileName, BOOL bCombine )
/************************************************************************/
{
    int ifh;		/* file handle( unbuffered) */
    FILEBUF ifd;		/* file descriptor( buffered) */
    short i, iColors;
    VERSIONINFO version;
    RECINFO rec;
    LPTR lpByte;
    LPWORD lpWord;
    LPLONG lpLong;
    BYTE Previous;
    BOOL bError;
    FNAME szName;
    LPPALETTE lpHeadPalette, lpPalette, lpBigPalette;

    /* open the palette file */
    if ( ( ifh = _lopen( lpFileName, OF_READ)) < 0 )
    {
        Message( IDS_EOPEN, lpFileName);
        return( NULL );
    }

    /* create a buffered stream to speed access */
    FileFDOpenRdr( &ifd, ifh, (LPTR)LineBuffer[0], 16*1024);

// read palette version
    version.Length = sizeof(version.Number);
    version.Type = PALFILE_VERSION;
    FileRead(&ifd, (LPTR)&version, sizeof(version));
#ifdef _MAC
    swapw(&version.Length);
    swapw(&version.Number);
#endif
    if (ifd.err ||
            version.Type != PALFILE_VERSION ||
            version.Length != sizeof(version.Number) ||
            version.Number > CURRENT_VERSION)
    {
        Message(IDS_INVALIDPALETTE, lpFileName);
        _lclose(ifh);
        return(NULL);
    }
    rec.Type = 0;
    lpHeadPalette = NULL;
    lpPalette = NULL;
    bError = NO;
    while (!bError && !ifd.err && rec.Type != PALFILE_END)
    {
        Previous = rec.Type;
        FileRead(&ifd, (LPTR)&rec, sizeof(RECINFO));
#ifdef _MAC
        swapw(&rec.Length);
#endif
        if (ifd.err)
            break;
        switch (rec.Type)
        {
        case PALFILE_VERSION:
            bError = YES;
            break;
        case PALFILE_COUNT:
            lpByte = Alloc((long)rec.Length);
            FileRead(&ifd, lpByte, rec.Length);
            FreeUp(lpByte);
            break;
        case PALFILE_COLORS:
            if (!lpPalette)
            {
                bError = YES;
                break;
            }
            lpWord = (LPWORD)Alloc((long)rec.Length);
            if (!lpWord)
            {
                Message (IDS_EMEMALLOC);
                bError = YES;
                break;
            }
            FileRead(&ifd, (LPTR)lpWord, rec.Length);
            if (ifd.err)
            {
                FreeUp((LPTR)lpWord);
                break;
            }
#ifdef _MAC
            swapw(lpWord);
#endif
            iColors = *lpWord;
            if ((iColors * sizeof(COLOR) + sizeof(WORD)) != rec.Length)
            {
                FreeUp((LPTR)lpWord);
                bError = YES;
                break;
            }
            lpPalette->iColors = iColors;
            if (!iColors)
            {
                FreeUp((LPTR)lpWord);
                break;
            }
            lpLong = (LPLONG)(lpWord+1);
            lpPalette->lpColorInfo =
                (LPCOLORINFO)Alloc((long)(sizeof(COLORINFO)*iColors));
            if (!lpPalette->lpColorInfo)
            {
                Message(IDS_EMEMALLOC);
                FreeUp((LPTR)lpWord);
                bError = YES;
                break;
            }
            for (i = 0; i < iColors; ++i)
            {
                LPVOID lp = &lpPalette->lpColorInfo[i].rgb;

#ifdef _MAC
                swapl((LPDWORD)lp);
#endif

                CopyRGB(lpLong+i, lp);
                SetColorInfo(
                    &lpPalette->lpColorInfo[i],
                    &lpPalette->lpColorInfo[i],
                    CS_RGB);
            }

            FreeUp((LPTR)lpWord);
            break;
        case PALFILE_NAME:
            if (Previous == PALFILE_NAME)
            {
                bError = YES;
                break;
            }
            if (lpPalette)
            {
                lpHeadPalette = LinkPalette(lpHeadPalette, lpPalette);
                lpPalette = NULL;
            }
            rec.Length = bound(rec.Length, 0, MAX_FNAME_LEN);
            FileRead(&ifd, (LPTR)szName, rec.Length);
            if (ifd.err)
                break;
            lpPalette = NewPalette(szName);
            if (!lpPalette)
            {
                Message (IDS_EMEMALLOC);
                bError = YES;
                break;
            }
            break;
        case PALFILE_GROUP:
            if (!lpPalette || (rec.Length != sizeof(lpPalette->dwGroup)))
            {
                bError = YES;
                break;
            }
            FileRead(&ifd, (LPTR)&lpPalette->dwGroup, rec.Length);
#ifdef _MAC
            swapl((LPDWORD)(&lpPalette->dwGroup));
#endif
            break;
        case PALFILE_LABELS:
            if (!lpPalette)
            {
                bError = YES;
                break;
            }
            lpPalette->lpLabels = Alloc((long)rec.Length);
            if (!lpPalette->lpLabels)
            {
                Message (IDS_EMEMALLOC);
                bError = YES;
                break;
            }
            lpPalette->LabelsLength = rec.Length;
            FileRead(&ifd, lpPalette->lpLabels, rec.Length);
            break;
        case PALFILE_FORMAT:
            if (!lpPalette || (rec.Length > MAX_STR_LEN))
            {
                bError = YES;
                break;
            }
            FileRead(&ifd, (LPTR)lpPalette->szFormat, rec.Length);
            break;
        case PALFILE_END:
            if (lpPalette)
            {
                lpHeadPalette = LinkPalette(lpHeadPalette, lpPalette);
                lpPalette = NULL;
            }
            break;
        default:
            bError = YES;
            break;
        }
    }
    _lclose(ifh);
    if (lpPalette)
    {
        if (lpPalette->lpColorInfo)
            FreeUp((LPTR)lpPalette->lpColorInfo);
        if (lpPalette->lpLabels)
            FreeUp((LPTR)lpPalette->lpLabels);
        FreeUp((LPTR)lpPalette);
    }
    if (ifd.err || bError || rec.Type != PALFILE_END || lpPalette)
    {
        Message(IDS_INVALIDPALETTE, lpFileName);
        FreeUpPalette(lpHeadPalette);
        return(NULL);
    }

    if ( !bCombine || !lpHeadPalette )
        return( lpHeadPalette );

    if ( !(lpBigPalette = CombinePalettes(lpHeadPalette)) )
        Message (IDS_EMEMALLOC);
    FreeUpPalette(lpHeadPalette);
    return( lpBigPalette );
}
コード例 #28
0
ファイル: timer.c プロジェクト: k-takata/TClockLight
/*-------------------------------------------
  add item to tcmenu*.txt
---------------------------------------------*/
void OnRequestMenu(HWND hwnd, BOOL bClear)
{
	char tcmenutxt[MAX_PATH];
	WIN32_FIND_DATA fd;
	HANDLE hfind;
	HFILE hf;
	int size;
	char *buf;
	const char *p, *np;
	static BOOL bWrite = FALSE;
	
	if(!bClear && m_pTimerRun == NULL) return;
	
	if(bClear && !bWrite) return;
	
	// ../common/tclang.c
	FindFileWithLangCode(tcmenutxt, GetUserDefaultLangID(), TCMENUTXT);
	
	hfind = FindFirstFile(tcmenutxt, &fd);
	if(hfind == INVALID_HANDLE_VALUE) return;
	
	FindClose(hfind);
	size = (int)fd.nFileSizeLow;
	buf = malloc(size+1);
	if(!buf) return;
	
	hf = _lopen(tcmenutxt, OF_READWRITE);
	if(hf == HFILE_ERROR) { free(buf); return; }
	_lread(hf, buf, size);
	*(buf + size) = 0;
	
	_llseek(hf, 0, 0);
	
	p = buf;
	while(*p)
	{
		if(strncmp(p, "#Timer Begin", 12) == 0)
		{
			PTIMERSTRUCT pitem;
			DWORD tick;
			char s[160];
			
			np = nextline(p);
			_lwrite(hf, p, (int)(np - p));
			p = np;
			
			tick = GetTickCount();
			
			pitem = m_pTimerRun;
			while(pitem)
			{
				int remaining =
					pitem->interval - (tick - pitem->tickonstart)/1000 - 1;
				
				wsprintf(s, "\"%s %s %02d:%02d\" post %s %d 0 %d\r\n",
					MyString(IDS_STOP, "Stop"),
					pitem->name, remaining/60, remaining%60,
					CLASS_TCLOCKTIMER, TIMERM_STOP, pitem->id);
				_lwrite(hf, s, (int)strlen(s));
				
				pitem = pitem->next;
			}
			
			while(*p)
			{
				if(strncmp(p, "#Timer End", 10) == 0)
					break;
				p = nextline(p);
			}
		}
		else
		{
			np = nextline(p);
			_lwrite(hf, p, (int)(np - p));
			p = np;
		}
	}
	
	_lwrite(hf, NULL, 0); // truncate
	
	_lclose(hf);
	free(buf);
	
	bWrite = TRUE;
}
コード例 #29
0
//***********************************************************************
LRESULT FAR PASCAL MMIOJunkIOProc(LPSTR lpmmioinfo, UINT wMsg, LPARAM lParam1, LPARAM lParam2)
//***********************************************************************
{
	LRESULT lRes = MMSYSERR_NOERROR;
	MMIOINFO *pInfo = (MMIOINFO *)lpmmioinfo;

	switch(wMsg)
	{
	case MMIOM_READ:
		lRes = MMIOJunkRead(pInfo, (LPBYTE)lParam1, lParam2);
		break;

	case MMIOM_SEEK:
		{
			HFILE hFile = pInfo->adwInfo[0];
			MMIOSeek(pInfo, hFile, lParam1, lParam2);
		}
		break;

	case MMIOM_WRITE:
		break;

	case MMIOM_OPEN:
		{
			LPSTR lpszFileName = (LPSTR)lParam1;
			char szNewName[_MAX_PATH];

			// If just parsing the name...
			if (pInfo->dwFlags & MMIO_PARSE)
			{

				StripPlus(szNewName, lpszFileName);
				//lRes = TRUE;
			}

			// Else, assume we are to open the file
			else
			{
				// Get rid of the +abc stuff
				StripPlus(szNewName, lpszFileName);

				// Open the file and stuff the handle in user info
				HFILE hFile = _lopen(szNewName, OF_READ);
				pInfo->adwInfo[0] = hFile;
				pInfo->lDiskOffset = 0;
			}

			lFrameCount = 0;

			//pInfo->hmmio = hFile;
		}
		break;

	case MMIOM_CLOSE:
		{
		HFILE hFile = (HFILE)pInfo->adwInfo[0];
		if (hFile)
			_lclose(hFile);
		}
		break;
	}

	return lRes;
}
コード例 #30
0
int objwrt(LPIMAGE lpImage, LPSTR lpFileName, int idFileType, LPRECT lpRect,
			int flag, BOOL fCompressed)
/************************************************************************/
{
LPOBJECT lpObject;
int ofp;
LPLONG lngptr;
LPWORD shtptr;
FNAME temp;
BOOL bEscapable;
int nObjects, i, nPasses;
long lObjStart;
WORD wBytes;
LPOBJOFFSETS lpOffsets;

if (!lpImage)
	return( -1 );

lpObject = NULL;
nObjects = nPasses = 0;
while (lpObject = ImgGetNextObject(lpImage, lpObject, YES, NO))
	{
	if (lpObject->lpAlpha && (nObjects || Save.bSaveMask))
		++nPasses;
	++nObjects;
	++nPasses;
	}
if (!(lpOffsets = (LPOBJOFFSETS)Alloc(sizeof(OBJOFFSETS)*nObjects)))
	{
	Message(IDS_EMEMALLOC);
	return(-1);
	}
bEscapable = !FileExists(lpFileName);

#ifdef _MAC
// The Mac file system can't handle the following pathname:
//		Bad --->        "DIR:FILE.EXT"
//		Needs to be -> ":DIR:FILE.EXT"
// Add the additional ':' here to specify starting at our directory.
if (lpFileName[0] != ':')
{
	STRING szName;
	lstrcpy(szName, lpFileName);
	lstrcpy(lpFileName+1, szName);
	lpFileName[0] = ':';
}
#endif

if ((ofp = _lcreat(lpFileName,0)) < 0)
	{
	FreeUp((LPTR)lpOffsets);
	Message( IDS_EOPEN, lpFileName );
	return(-1);
	}

ProgressBegin(nPasses, 0);

// Fill in header info
shtptr = (LPWORD)LineBuffer[0];
SetNextWord(&shtptr, 0x4949);					/* byte order is LSB,MSB */
SetNextWord(&shtptr, OBJ_VERSION);				/* Version Number */
SetNextWord(&shtptr, ImgCountObjects(lpImage));	/* Number of Objects */
lngptr = (LPLONG)shtptr;
SetNextLong(&lngptr, OBJ_DATA_SIZE);			/* size of object data */
SetNextLong(&lngptr, OBJ_HDR_SIZE);				/* start of object data */

// Write out header info
wBytes = (LPTR)lngptr - (LPTR)LineBuffer[0];
if ( _lwrite(ofp, LineBuffer[0], wBytes) != wBytes )
	goto BadWrite;

lObjStart = _llseek (ofp, 0L, 1);
wBytes = OBJ_DATA_SIZE * ImgCountObjects(lpImage);
if ( _lwrite(ofp, LineBuffer[0], wBytes) != wBytes )
	goto BadWrite;
lpObject = NULL;
i = 0;
while (lpObject = ImgGetNextObject(lpImage, lpObject, YES, NO))
	{
	lpOffsets[i].lDataOffset = _llseek (ofp, 0L, 1);
	lpOffsets[i].lAlphaOffset = 0L;
	if (TiffWriteFrame(ofp, lpFileName, NULL, lpObject->Pixmap.EditFrame,
				NULL, flag, fCompressed, bEscapable) < 0)
		goto BadWrite;
	if (!lpObject->lpAlpha || (!i && !Save.bSaveMask))
		{
		++i;
		continue;
		}
	lpOffsets[i].lAlphaOffset = _llseek (ofp, 0L, 1);
	if (TiffWriteFrame(ofp, lpFileName, NULL, lpObject->lpAlpha->Pixmap.EditFrame,
				NULL, IDC_SAVECT, fCompressed, bEscapable) < 0)
		goto BadWrite;
	++i;
	}

// fill in object data information and write it
_llseek (ofp, lObjStart, 0);
lpObject = NULL;
i = 0;
while (lpObject = ImgGetNextObject(lpImage, lpObject, YES, NO))
	{
	shtptr = (LPWORD)LineBuffer[0];
	SetNextWord(&shtptr, lpObject->ObjectType);
	SetNextWord(&shtptr, lpObject->rObject.left);
	SetNextWord(&shtptr, lpObject->rObject.top);
	SetNextWord(&shtptr, lpObject->rObject.right);
	SetNextWord(&shtptr, lpObject->rObject.bottom);
	SetNextWord(&shtptr, lpObject->Opacity);
	SetNextWord(&shtptr, lpObject->MergeMode);
	SetNextWord(&shtptr, lpObject->wGroupID);
	SetNextWord(&shtptr, idFileType);
	if (lpObject->lpAlpha)
		{
		SetNextWord(&shtptr, lpObject->lpAlpha->bInvert);
		SetNextWord(&shtptr, lpObject->lpAlpha->rMask.left);
		SetNextWord(&shtptr, lpObject->lpAlpha->rMask.top);
		SetNextWord(&shtptr, lpObject->lpAlpha->rMask.right);
		SetNextWord(&shtptr, lpObject->lpAlpha->rMask.bottom);
		}
	else
		{
		SetNextWord(&shtptr, 0);
		SetNextWord(&shtptr, 0);
		SetNextWord(&shtptr, 0);
		SetNextWord(&shtptr, 0);
		SetNextWord(&shtptr, 0);
		}
	lngptr = (LPLONG)shtptr;
	SetNextLong(&lngptr, lpOffsets[i].lDataOffset);
	SetNextLong(&lngptr, lpOffsets[i].lAlphaOffset);
	shtptr = (LPWORD)lngptr;
	SetNextWord(&shtptr, lpObject->fSelected);
    SetNextWord(&shtptr, lpObject->ObjectDataID);
	lngptr = (LPLONG)shtptr;
    SetNextLong(&lngptr, lpObject->dwObjectData);
	shtptr = (LPWORD)lngptr;

	++i;
	// Write out Object data
	wBytes = OBJ_DATA_SIZE;;
	if ( _lwrite(ofp, LineBuffer[0], wBytes) != wBytes )
		goto BadWrite;
	}

FreeUp( (LPTR)lpOffsets );
_lclose(ofp);
ProgressEnd();
return( 0 );

BadWrite:
_lclose(ofp);
FreeUp( (LPTR)lpOffsets );
lstrcpy(temp,lpFileName);
FileDelete(temp);
if (nPasses)
	ProgressEnd();
return( -1 );
}