void
avtMultiResolutionPartitionStrategy::ConstructPartition(const int *cell_dims,
                             avtStructuredMeshChunker::ZoneDesignation *d_plus,
                             std::vector<int> &boxes)
{
    FreeUpMemory();  // In case we called this module before.
    Level0Initialize(cell_dims, d_plus);
    SearchFromCorners();
    FinalInitialize();

    int cell = 0;
    FindBoxes(nLevels-1, cell);
    boxes = tmpBox;

    FreeUpMemory();  // No reason to hold onto this memory.
}
Exemplo n.º 2
0
void *LAlloc( size_t size )
#endif
{
    void    *p;

    for( ;; ) {
#ifdef TRMEM
        p = _trmem_alloc( size, ra, TrHdl );
#else
        p = malloc( size );
#endif
        if( p != NULL ) {
            memset( p, 0, size );
            break;
        }
        if( !FreeUpMemory() ) break;
    }
#ifdef _INT_DEBUG
    if( p != NULL ) ++Chunks;
#endif
    return( p );
}
Exemplo n.º 3
0
void *LAlloc( size_t size )
/*************************/
#endif
{
    void    *p;

    for( ;; ) {
#ifdef TRMEM
        p = _trmem_alloc( size, ra, TrHdl );

#elif defined( USE_OS2HMALLOC )

        /* Use all but 64MB of available low memory address space
           and then use available high memory.
           Os2_private_mem_left is a good enough estimate of
           address space remaining in the lower private arena.
           The goal is to leave a large chunk of address space available
           for the HLL_SECT_MISC section which is allocated at the end of pass1
           after most of the other memory allocations have been done
        */
        if( os2_private_mem_left > 64 * 1024 * 1024 &&
            size + 16 < os2_private_mem_left ) {
            p = malloc( size );
            if( p )
                os2_private_mem_left -= size + 16;
        }
        else {
            p = _os2hmalloc( size );
        }

#elif defined( OS2_MEM_HDR_MAGIC )
        /*
         * On OS/2 we will try use high memory when available. OS/2 has
         * two arenas for private memory, the Open Watcom heap is currently
         * only using the lower one. The lower arena is often smaller than
         * 128MB because of fragmentation caused by big applications (like
         * mozilla, openoffice, ..) in the shared arena above it. The high
         * arena on the other hand, is usually not subject to this kind of
         * fragmentation and will normally be able to provide more than
         * 400MB of contiguous virtual memory. Big links needs lots of
         * memory, so for medium/large allocations we try use the high memory.
         *
         * The allocations are identified by being at a fixed offset (16) into
         * a page and the header values (the 3 magics and the page aligned size).
         */
        static int fObjAny = -1;        /* -1 = check, 0 = no upper, 1 = have upper */
        static size_t minUpperAlloc = 0x2000;     /* 8 KBytes */
        if( fObjAny && size >= minUpperAlloc ) {
            APIRET rc;
            ULONG  ul;

            /*
             * Check if can allocate more than 512MB on the first call.
             * Will fail if upper arena does not exist.
             */
            if( fObjAny == -1) {
                rc = DosQuerySysInfo( QSV_VIRTUALADDRESSLIMIT,
                                      QSV_VIRTUALADDRESSLIMIT,
                                      &ul, sizeof( ul ) );
                fObjAny =   rc == NO_ERROR
                         && ul > 512 /*MB*/;
                if( !fObjAny )
                    continue; /* restart the loop */
            }

            /* Try allocate a block in the high arena. */
            ul = size + sizeof( os2_mem_hdr );  /* Make room for header */
            ul = ( ul + 0xfff ) & ~0xfffUL; /* Round up to 4K boundary */
            rc = DosAllocMem( &p, ul, OBJ_ANY | PAG_READ | PAG_WRITE | PAG_COMMIT );
            if(     rc == NO_ERROR
                &&  (uintptr_t)p >= 0x20000000UL /* 512MB */) {
               /* Mark allocation as coming from upper arena */
               os2_mem_hdr *hdr = (os2_mem_hdr *)p;
               hdr->magic = hdr->magic1 = hdr->magic2 = OS2_MEM_HDR_MAGIC;
               hdr->size = ul;
               p = hdr + 1;
               break;                   /* return pointer to caller */
            }
            if( rc == ERROR_INVALID_PARAMETER )
                fObjAny = FALSE;        /* Upper arena not supported */
            else if( rc == NO_ERROR )
                DosFreeMem( p );        /* Came for lower area - give back */
        }
        p = malloc( size );
        /* If lower arena allocation failed try upper arena unless time to die */
        if( p == NULL && fObjAny == TRUE && minUpperAlloc > 0x2000 ) {
            minUpperAlloc >>= 1;        /* Halve if more than 8192 */
            continue;                   /* Try again */
        }

#else /* ! OS2_MEM_HDR_MAGIC */
        p = malloc( size );
#endif
        if( p != NULL ) {
            memset( p, 0, size );
            break;
        }
        /* Try to free up some memory and try malloc */
        if( !FreeUpMemory() ) break;
    } /* for */
avtMultiResolutionPartitionStrategy::~avtMultiResolutionPartitionStrategy()
{
    FreeUpMemory();
}
Exemplo n.º 5
0
void CheckKeys (void)
{
	//extern id0_boolean_t autofire;

	if (screenfaded)			// don't do anything with a faded screen
		return;

#if 0
//
// pause key wierdness can't be checked as a scan code
//
	if (Paused)
	{
		CenterWindow (8,3);
		US_PrintCentered ("PAUSED");
		VW_UpdateScreen ();
//		SD_MusicOff();
		IN_Ack();
//		SD_MusicOn();
		Paused = false;
		// (REFKEEN) Minor difference from vanilla Catacomb
		if (MousePresent) BE_ST_GetEmuAccuMouseMotion(NULL, NULL);	// Clear accumulated mouse movement
		//if (MousePresent) Mouse(MDelta);	// Clear accumulated mouse movement
	}
	else
	if (Keyboard[sc_Enter])			// P = pause with no screen disruptioon
	{
//		SD_MusicOff();
		DisplaySMsg("PAUSED",NULL);
		IN_Ack();
//		SD_MusicOn();
		// (REFKEEN) Minor difference from vanilla Catacomb
		if (MousePresent) BE_ST_GetEmuAccuMouseMotion(NULL, NULL);	// Clear accumulated mouse movement
		//if (MousePresent) Mouse(MDelta);	// Clear accumulated mouse movement
	}
	else
	if (Keyboard[sc_S])
	{
		id0_char_t *Text[] = {{"Slow Mode ON"},{"Slow Mode OFF"}};

		SlowMode ^= 1;
		extravbls = SlowMode << 3;
		CenterWindow (8,3);
		US_PrintCentered (Text[SlowMode]);
		VW_UpdateScreen ();
//		SD_MusicOff();
		IN_Ack();
//		SD_MusicOn();
		// (REFKEEN) Minor difference from vanilla Catacomb
		if (MousePresent) BE_ST_GetEmuAccuMouseMotion(NULL, NULL);	// Clear accumulated mouse movement
		//if (MousePresent) Mouse(MDelta);	// Clear accumulated mouse movement
	}
#endif


// F2 - SOUND OPTIONS
//
	if (Keyboard[sc_F2])
	{
		id0_int_t height=7;
		id0_boolean_t ChoiceMade = false;

		if (AdLibPresent)
			height++;

		VW_FixRefreshBuffer();
		CenterWindow(22,height);
		US_Print( "\n        1 )  NO SOUND \n");
		US_Print(   "        2 )  PC  AUDIO \n");

		if (AdLibPresent)
			US_Print("        3 ) ADLIB AUDIO\n");

		US_Print( "\n       ESC)    EXIT    ");
		VW_UpdateScreen();

		// REFKEEN - Alternative controllers support
		extern BE_ST_ControllerMapping g_ingame_altcontrol_mapping_soundoptions;
		g_ingame_altcontrol_mapping_soundoptions.buttons[BE_ST_CTRL_BUT_X].mapClass = AdLibPresent ? BE_ST_CTRL_MAP_KEYSCANCODE : BE_ST_CTRL_MAP_NONE; // A bit of patching
		BE_ST_AltControlScheme_Push();
		BE_ST_AltControlScheme_PrepareControllerMapping(&g_ingame_altcontrol_mapping_soundoptions);

		// Switch audio device ON/OFF & load sounds if there
		// was a change in the device.

		do {

			if (Keyboard[1]) 								// ESC - Exit
				ChoiceMade = true;
			else
			if (Keyboard[2]) 							 	// 1 - No Sound
			{
				SD_SetSoundMode(sdm_Off);
				ChoiceMade = true;
			}
			else
			if (Keyboard[3])  							// 2 - PC Audio
			{
				SD_SetSoundMode(sdm_PC);
//				if (oldsoundmode != sdm_PC)
					CA_LoadAllSounds();
				ChoiceMade = true;
			}
			else
			if ((Keyboard[4]) &&	AdLibPresent)		// 3 - AdLib Audio
			{
				SD_SetSoundMode(sdm_AdLib);
//				if (oldsoundmode != sdm_AdLib)
					CA_LoadAllSounds();
				ChoiceMade = true;
			}

			BE_ST_ShortSleep();

		} while (!ChoiceMade);

		// REFKEEN - Alternative controllers support
		BE_ST_AltControlScheme_Pop();

		tics = realtics = 1;
		IN_ClearKeysDown();
	}

// F5 - CALIBRATE JOYSTICK
//
	if (Keyboard[sc_F5])
	{
		CalibrateJoystick(0);
		tics = realtics = 1;
		IN_ClearKeysDown();
	}

deadloop:;
// ESCAPE - quits game
//
	if ((Keyboard[sc_Escape]) || (Flags & FL_DEAD))
	{
		id0_char_t ch;

		DisplaySMsg("Options", NULL);
		status_flag = S_NONE;


		if (Flags & FL_DEAD)
		{
			id0_char_t choices[] = {sc_Escape,sc_R,sc_N,sc_Q,0};
			ch = DisplayMsg("Restore          New          Quit",choices);
		}
		else
		{
			id0_char_t choices[] = {sc_Escape,sc_S,sc_R,sc_N,sc_Q,0};
			ch = DisplayMsg("Save       Restore       New       Quit",choices);
		}
		DrawText(true);

		switch (ch)
		{
			case sc_S:
				if (!(Flags & FL_DEAD))
					Keyboard[sc_F3] = true;
			break;

			case sc_R:
				Keyboard[sc_F4] = true;
			break;

			case sc_N:
				DisplaySMsg("Starting anew", NULL);
				VW_WaitVBL(60);
				playstate = ex_resetgame;
				Flags &= ~FL_DEAD;
			break;

			case sc_Q:
				// REFKEEN - Alternative controllers support
				{
					extern BE_ST_ControllerMapping g_ingame_altcontrol_mapping_inackback;
					BE_ST_AltControlScheme_Push();
					BE_ST_AltControlScheme_PrepareControllerMapping(&g_ingame_altcontrol_mapping_inackback);
					// REFKEEN - We don't pop this since we quit...
				}
				DisplaySMsg("FARE THEE WELL!", NULL);
				VW_WaitVBL(120);
				if (!Flags & FL_QUICK)
					VW_FadeOut();
				NormalScreen();
				FreeUpMemory();
				Quit(NULL);
			break;
		}
		tics = realtics = 1;
	}

// F1 - DISPLAY HELP
//
	if (Keyboard[sc_F1])
	{
		PrintHelp();

#ifdef TEXT_PRESENTER

		extern PresenterInfo MainHelpText;

		VW_FadeOut();

		FreeUpMemory();
		if (!LoadPresenterScript("HELP.TXT",&MainHelpText))
		{
			VW_FadeIn();
			CenterWindow(30,5);
			US_CPrint("\nError loading HELP file.\n");
			US_CPrint("Press any key.");
			IN_Ack();
			VW_FadeOut();
		}
		else
		{
			VW_SetSplitScreen(200);
			bufferofs = displayofs = screenloc[0];
			VW_Bar(0,0,320,200,0);

			Display640();
			Presenter(&MainHelpText);
			Display320();
		}
		FreePresenterScript(&MainHelpText);
#endif
		VW_SetSplitScreen(120);
		VW_SetScreen(screenloc[0],0);
		screenpage = 0;
		CacheScaleds();

		bufferofs = 0;
		RedrawStatusWindow();
		ThreeDRefresh();
		VW_FadeIn();
		Keyboard[sc_F1] = false;
		tics = realtics = 1;
		IN_ClearKeysDown();
	}

// F3 - SAVE GAME
//
	if ((Keyboard[sc_F3]) && (!(Flags & FL_DEAD)))
	{
		PreFullDisplay();
		GE_SaveGame();
		PostFullDisplay(true);
		tics = realtics = 1;
		IN_ClearKeysDown();
	}

// F4 - LOAD GAME
//
	if (Keyboard[sc_F4])
	{
		PreFullDisplay();
		if (GE_LoadGame())
		{
			loadedgame = true;
			playstate = ex_loadedgame;
			Flags &= ~FL_DEAD;
			lasttext = -1;
			PostFullDisplay(false);
		}
		else
		if (playstate == ex_victorious)
		{
			PostFullDisplay(false);
			Victory(false);
			IN_Ack();
//			gamestate.mapon++;
		}
		else
			PostFullDisplay(true);
		Keyboard[sc_F5] = false;
		tics = realtics = 1;
		IN_ClearKeysDown();
	}

	if (Flags & FL_DEAD)
		goto deadloop;

//
// F10-? debug keys
//
	if (Keyboard[sc_BackSpace])
	{
		DebugKeys();
		// (REFKEEN) Minor difference from vanilla Catacomb
		if (MousePresent) BE_ST_GetEmuAccuMouseMotion(NULL, NULL);	// Clear accumulated mouse movement
		//if (MousePresent) Mouse(MDelta);	// Clear accumulated mouse movement
		lasttimecount = SD_GetTimeCount();
	}
}
Exemplo n.º 6
0
int __fmemneed( size_t amount )
/*****************************/
{
    amount = amount;
    return( FreeUpMemory() );
}
Exemplo n.º 7
0
id0_boolean_t	LoadTheGame(BE_FILE_T file)
{
	id0_unsigned_t	i,x,y;
	objtype		/**obj,*/*prev,*next,*followed;
	id0_unsigned_t	compressed,expanded;
	id0_unsigned_t	id0_far *map,tile;
	memptr		bigbuffer;

	screenpage = 0;
	FreeUpMemory();

	playstate = ex_loadedgame;
	// load the sky and ground colors
	// REFKEEN - But not before converting from original 16-bit pointers (reusing i variable)
	if (BE_Cross_readInt16LE(file, &i) != 2)
	//if (!CA_FarRead(file,(void id0_far *)&skycolor,sizeof(skycolor)))
		return(false);
	skycolor = GetSkyGndColorPtrFromDOSPointer(i);
	if (BE_Cross_readInt16LE(file, &i) != 2)
	//if (!CA_FarRead(file,(void id0_far *)&groundcolor,sizeof(groundcolor)))
		return(false);
	groundcolor = GetSkyGndColorPtrFromDOSPointer(i);

	if (BE_Cross_readInt16LE(file, &FreezeTime) != 2)
	//if (!CA_FarRead(file,(void id0_far *)&FreezeTime,sizeof(FreezeTime)))
		return(false);

	// (REFKEEN) Reading fields one-by-one in a cross-platform manner
	if (!LoadGameState(file, &gamestate))
	//if (!CA_FarRead(file,(void id0_far *)&gamestate,sizeof(gamestate)))
		return(false);

	if (BE_Cross_read_boolean_From16LE(file, &EASYMODEON) != 2)
	//if (!CA_FarRead(file,(void id0_far *)&EASYMODEON,sizeof(EASYMODEON)))
		return(false);

	SetupGameLevel ();		// load in and cache the base old level

	// (REFKEEN) DIFFERENCE FROM VANILLA CATACOMB ADVENTURES:
	// Don't do this check, we've already opened the file anyway
	// and this can lead to unexpected behaviors!
#if 0
	if (!FindRewritableFile(Filename,"SAVE GAME",-1))
		Quit("Error: Can't find saved game file!");
#endif

	expanded = mapwidth * mapheight * 2;
	MM_GetPtr (&bigbuffer,expanded);

	for (i = 0;i < 3;i+=2)	// Read planes 0 and 2
	{
		if (BE_Cross_readInt16LE(file, &compressed) != 2)
		//if (!CA_FarRead(file,(id0_byte_t id0_far *)&compressed,sizeof(compressed)) )
		{
			MM_FreePtr (&bigbuffer);
			return(false);
		}

		if (BE_Cross_readInt16LEBuffer(file, bigbuffer, compressed) != compressed)
		//if (!CA_FarRead(file,(id0_byte_t id0_far *)bigbuffer,compressed) )
		{
			MM_FreePtr (&bigbuffer);
			return(false);
		}

		CA_RLEWexpand ((id0_unsigned_t id0_huge *)bigbuffer,
			(id0_unsigned_t id0_huge *)mapsegs[i],expanded,RLETAG);
	}

	MM_FreePtr (&bigbuffer);
//
// copy the wall data to a data segment array again, to handle doors and
// bomb walls that are allready opened
//
	memset (tilemap,0,sizeof(tilemap));
	memset (actorat,0,sizeof(actorat));
	map = mapsegs[0];
	for (y=0;y<mapheight;y++)
		for (x=0;x<mapwidth;x++)
		{
			tile = *map++;
			if (tile<NUMFLOORS)
			{
				if (tile != INVISIBLEWALL)
					tilemap[x][y] = tile;
				if (tile>0)
					actorat[x][y] = tile;
					//(id0_unsigned_t)actorat[x][y] = tile;
			}
		}


	// Read the object list back in - assumes at least one object in list

	InitObjList ();
	newobj = player;
	while (true)
	{
		prev = newobj->prev;
		next = newobj->next;
		// (REFKEEN) Reading fields one-by-one in a cross-platform manner
		if (!LoadObject(file, newobj))
		//if (!CA_FarRead(file,(void id0_far *)newobj,sizeof(objtype)))
			return(false);
		followed = newobj->next;
		newobj->prev = prev;
		newobj->next = next;
		actorat[newobj->tilex][newobj->tiley] = COMPAT_OBJ_CONVERT_OBJ_PTR_TO_DOS_PTR(newobj);	// drop a new marker
		//actorat[newobj->tilex][newobj->tiley] = newobj;	// drop a new marker

		if (followed)
			GetNewObj (false);
		else
			break;
	}

	return(true);
}
Exemplo n.º 8
0
void CheckKeys (void)
{
	if (screenfaded)			// don't do anything with a faded screen
		return;

//
// pause key wierdness can't be checked as a scan code
//
	if (Paused)
	{
		CenterWindow (8,3);
		US_PrintCentered ("PAUSED");
		VW_UpdateScreen ();
		SD_MusicOff();
		IN_Ack();
		SD_MusicOn();
		Paused = false;
		if (MousePresent) BE_ST_GetMouseDelta(NULL, NULL); // Clear accumulated mouse movement
		//if (MousePresent) Mouse(MDelta);	// Clear accumulated mouse movement
	}

//
// F1-F7/ESC to enter control panel
//
	if ( (LastScan >= sc_F1 && LastScan <= sc_F7) || LastScan == sc_Escape)
	{
		StopMusic ();
		NormalScreen ();
		FreeUpMemory ();
		US_CenterWindow (20,8);
		US_CPrint ("Loading");
		VW_UpdateScreen ();
		US_ControlPanel();
		// REFKEEN - Alternative controllers support (maybe user has changed some keys which may currently have an effect)
		void PrepareGamePlayControllerMapping(void);
		PrepareGamePlayControllerMapping();
		//
		if (abortgame)
		{
			playstate = ex_abort;
			return;
		}
		StartMusic ();
		IN_ClearKeysDown();
		if (restartgame)
			playstate = ex_resetgame;
		if (loadedgame)
			playstate = ex_loadedgame;
		DrawPlayScreen ();
		CacheScaleds ();
		lasttimecount = SD_GetTimeCount();
		if (MousePresent) BE_ST_GetMouseDelta(NULL, NULL); // Clear accumulated mouse movement
		//if (MousePresent) Mouse(MDelta);	// Clear accumulated mouse movement
	}

//
// F10-? debug keys
//
	if (Keyboard[sc_F10])
	{
		DebugKeys();
		if (MousePresent) BE_ST_GetMouseDelta(NULL, NULL); // Clear accumulated mouse 			// if (MousePresent) Mouse(MDelta);	// Clear accumulated mouse movement
		lasttimecount = SD_GetTimeCount();
	}

}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
    LPSTR szFileList;
    char **index, *sz;
    int retcode, i, cc;
    DWORD dwVerInfoSize;
    DWORD dwVerHnd;
    char szFullPath[PATH_MAX];
#ifdef WIN32
    char *ptr;
#else
    HFILE hfile;
    OFSTRUCT ofs;
#endif
    HANDLE  hMem;         /* handle to mem alloc'ed */

    if (argc < 3)
        return 0;           /* Exits if not proper number of arguments */

    hZUF = GlobalAlloc( GPTR, (DWORD)sizeof(ZIPUSERFUNCTIONS));
    if (!hZUF)
    {
        return 0;
    }
    lpZipUserFunctions = (LPZIPUSERFUNCTIONS)GlobalLock(hZUF);

    if (!lpZipUserFunctions)
    {
        GlobalFree(hZUF);
        return 0;
    }

    lpZipUserFunctions->print = DummyPrint;
    lpZipUserFunctions->password = DummyPassword;
    lpZipUserFunctions->comment = DummyComment;

    /* Let's go find the dll */
#ifdef WIN32
    if (SearchPath(
                NULL,               /* address of search path               */
                ZIP_DLL_NAME,       /* address of filename                  */
                NULL,               /* address of extension                 */
                PATH_MAX,           /* size, in characters, of buffer       */
                szFullPath,         /* address of buffer for found filename */
                &ptr                /* address of pointer to file component */
            ) == 0)
#else
    hfile = OpenFile(ZIP_DLL_NAME,  &ofs, OF_SEARCH);
    if (hfile == HFILE_ERROR)
#endif
    {
        char str[256];
        wsprintf (str, DLL_WARNING, ZIP_DLL_NAME);
        printf("%s\n", str);
        FreeUpMemory();
        return 0;
    }
#ifndef WIN32
    else
        lstrcpy(szFullPath, ofs.szPathName);
    _lclose(hfile);
#endif

    /* Now we'll check the zip dll version information */
    dwVerInfoSize =
        GetFileVersionInfoSize(szFullPath, &dwVerHnd);

    if (dwVerInfoSize)
    {
        BOOL  fRet, fRetName;
        char str[256];
        LPSTR   lpstrVffInfo; /* Pointer to block to hold info */
        LPSTR lszVer = NULL;
        LPSTR lszVerName = NULL;
        UINT  cchVer = 0;

        /* Get a block big enough to hold the version information */
        hMem          = GlobalAlloc(GMEM_MOVEABLE, dwVerInfoSize);
        lpstrVffInfo  = GlobalLock(hMem);

        /* Get the version information */
        GetFileVersionInfo(szFullPath, 0L, dwVerInfoSize, lpstrVffInfo);
        fRet = VerQueryValue(lpstrVffInfo,
                             TEXT("\\StringFileInfo\\040904E4\\FileVersion"),
                             (LPVOID)&lszVer,
                             &cchVer);
        fRetName = VerQueryValue(lpstrVffInfo,
                                 TEXT("\\StringFileInfo\\040904E4\\CompanyName"),
                                 (LPVOID)&lszVerName,
                                 &cchVer);
        if (!fRet || !fRetName ||
                (lstrcmpi(lszVer, ZIP_DLL_VERSION) != 0) ||
                (lstrcmpi(lszVerName, COMPANY_NAME) != 0))
        {
            wsprintf (str, DLL_VERSION_WARNING, ZIP_DLL_NAME);
            printf("%s\n", str);
            FreeUpMemory();
            return 0;
        }
        /* free memory */
        GlobalUnlock(hMem);
        GlobalFree(hMem);
    }
    else
    {
        char str[256];
        wsprintf (str, DLL_VERSION_WARNING, ZIP_DLL_NAME);
        printf("%s\n", str);
        FreeUpMemory();
        return 0;
    }
    /* Okay, now we know that the dll exists, and has the proper version
     * information in it. We can go ahead and load it.
     */
    hZipDll = LoadLibrary(ZIP_DLL_NAME);
#ifndef WIN32
    if (hZipDll > HINSTANCE_ERROR)
#else
    if (hZipDll != NULL)
#endif
    {
        (_DLL_ZIP)ZipArchive = (_DLL_ZIP)GetProcAddress(hZipDll, "ZpArchive");
        (ZIPSETOPTIONS)ZipSetOptions = (ZIPSETOPTIONS)GetProcAddress(hZipDll, "ZpSetOptions");
        if (!ZipArchive || !ZipSetOptions)
        {
            char str[256];
            wsprintf (str, "Could not get entry point to %s", ZIP_DLL_NAME);
            MessageBox((HWND)NULL, str, "Info-ZIP Example", MB_ICONSTOP | MB_OK);
            FreeUpMemory();
            return 0;
        }
    }
    else
    {
        char str[256];
        wsprintf (str, "Could not load %s", ZIP_DLL_NAME);
        printf("%s\n", str);
        FreeUpMemory();
        return 0;
    }

    (_ZIP_USER_FUNCTIONS)ZipInit = (_ZIP_USER_FUNCTIONS)GetProcAddress(hZipDll, "ZpInit");
    if (!ZipInit)
    {
        printf("Cannot get address of ZpInit in Zip dll. Terminating...");
        FreeLibrary(hZipDll);
        FreeUpMemory();
        return 0;
    }
    if (!(*ZipInit)(lpZipUserFunctions))
    {
        printf("Application functions not set up properly. Terminating...");
        FreeLibrary(hZipDll);
        FreeUpMemory();
        return 0;
    }

    /* Here is where the action starts */
    ZpOpt.fSuffix = FALSE;        /* include suffixes (not yet implemented) */
    ZpOpt.fEncrypt = FALSE;       /* true if encryption wanted */
    ZpOpt.fSystem = FALSE;        /* true to include system/hidden files */
    ZpOpt.fVolume = FALSE;        /* true if storing volume label */
    ZpOpt.fExtra = FALSE;         /* true if including extra attributes */
    ZpOpt.fNoDirEntries = FALSE;  /* true if ignoring directory entries */
    ZpOpt.fVerbose = FALSE;       /* true if full messages wanted */
    ZpOpt.fQuiet = FALSE;         /* true if minimum messages wanted */
    ZpOpt.fCRLF_LF = FALSE;       /* true if translate CR/LF to LF */
    ZpOpt.fLF_CRLF = FALSE;       /* true if translate LF to CR/LF */
    ZpOpt.fJunkDir = FALSE;       /* true if junking directory names */
    ZpOpt.fGrow = FALSE;          /* true if allow appending to zip file */
    ZpOpt.fForce = FALSE;         /* true if making entries using DOS names */
    ZpOpt.fMove = FALSE;          /* true if deleting files added or updated */
    ZpOpt.fUpdate = FALSE;        /* true if updating zip file--overwrite only
                                  if newer */
    ZpOpt.fFreshen = FALSE;       /* true if freshening zip file--overwrite only */
    ZpOpt.fJunkSFX = FALSE;       /* true if junking sfx prefix*/
    ZpOpt.fLatestTime = FALSE;    /* true if setting zip file time to time of
                                  latest file in archive */
    ZpOpt.fComment = FALSE;       /* true if putting comment in zip file */
    ZpOpt.fOffsets = FALSE;       /* true if updating archive offsets for sfx
                                  files */
    ZpOpt.fDeleteEntries = FALSE; /* true if deleting files from archive */
    ZpOpt.fRecurse = 0;           /* subdir recursing mode: 1 = "-r", 2 = "-R" */
    ZpOpt.fRepair = 0;            /* archive repair mode: 1 = "-F", 2 = "-FF" */
    ZpOpt.Date = NULL;            /* Not using, set to NULL pointer */
    getcwd(szFullPath, PATH_MAX); /* Set directory to current directory */
    ZpOpt.szRootDir = szFullPath;

    ZpZCL.argc = argc - 2;        /* number of files to archive - adjust for the
                                  actual number of file names to be added */
    ZpZCL.lpszZipFN = argv[1];    /* archive to be created/updated */

    /* Copy over the appropriate portions of argv, basically stripping out argv[0]
       (name of the executable) and argv[1] (name of the archive file)
     */
    hFileList = GlobalAlloc( GPTR, 0x10000L);
    if ( hFileList )
    {
        szFileList = (char far *)GlobalLock(hFileList);
    }
    index = (char **)szFileList;
    cc = (sizeof(char *) * ZpZCL.argc);
    sz = szFileList + cc;

    for (i = 0; i < ZpZCL.argc; i++)
    {
        cc = lstrlen(argv[i+2]);
        lstrcpy(sz, argv[i+2]);
        index[i] = sz;
        sz += (cc + 1);
    }
    ZpZCL.FNV = (char **)szFileList;  /* list of files to archive */

    /* Set the options */
    ZipSetOptions(&ZpOpt);

    /* Go zip 'em up */
    retcode = ZipArchive(ZpZCL);
    if (retcode != 0)
        printf("Error in archiving\n");

    GlobalUnlock(hFileList);
    GlobalFree(hFileList);
    FreeUpMemory();
    FreeLibrary(hZipDll);
    return 1;
}
Exemplo n.º 10
0
int main(int argc, char **argv)
{
int exfc, infc;
char **exfv, **infv;
char *x_opt;
DWORD dwVerInfoSize;
DWORD dwVerHnd;
char szFullPath[_MAX_PATH];
int retcode;
#ifdef WIN32
char *ptr;
#else
HFILE hfile;
OFSTRUCT ofs;
#endif
HANDLE  hMem;         /* handle to mem alloc'ed */

if (argc < 2)   /* We must have an archive to unzip */
   {
   printf("usage: %s <zipfile> [entry1 [entry2 [...]]] [-x xentry1 [...]]",
          "example");
   return 0;
   }

hDCL = GlobalAlloc( GPTR, (DWORD)sizeof(DCL));
if (!hDCL)
   {
   return 0;
   }
lpDCL = (LPDCL)GlobalLock(hDCL);
if (!lpDCL)
   {
   GlobalFree(hDCL);
   return 0;
   }

hUF = GlobalAlloc( GPTR, (DWORD)sizeof(USERFUNCTIONS));
if (!hUF)
   {
   GlobalUnlock(hDCL);
   GlobalFree(hDCL);
   return 0;
   }
lpUserFunctions = (LPUSERFUNCTIONS)GlobalLock(hUF);

if (!lpUserFunctions)
   {
   GlobalUnlock(hDCL);
   GlobalFree(hDCL);
   GlobalFree(hUF);
   return 0;
   }

lpUserFunctions->password = password;
lpUserFunctions->print = DisplayBuf;
lpUserFunctions->sound = NULL;
lpUserFunctions->replace = GetReplaceDlgRetVal;
lpUserFunctions->SendApplicationMessage = ReceiveDllMessage;

/* First we go look for the unzip dll */
#ifdef WIN32
if (SearchPath(
    NULL,               /* address of search path               */
    UNZ_DLL_NAME,       /* address of filename                  */
    NULL,               /* address of extension                 */
    _MAX_PATH,           /* size, in characters, of buffer       */
    szFullPath,         /* address of buffer for found filename */
    &ptr                /* address of pointer to file component */
   ) == 0)
#else
hfile = OpenFile(UNZ_DLL_NAME,  &ofs, OF_SEARCH);
if (hfile == HFILE_ERROR)
#endif
   {
   char str[256];
   wsprintf (str, DLL_WARNING, UNZ_DLL_NAME);
   printf("%s\n", str);
   FreeUpMemory();
   return 0;
   }
#ifndef WIN32
else
   lstrcpy(szFullPath, ofs.szPathName);
_lclose(hfile);
#endif

/* Now we'll check the unzip dll version information. Note that this is
   not the same information as is returned from a call to UzpVersion()
 */
dwVerInfoSize =
    GetFileVersionInfoSize(szFullPath, &dwVerHnd);

if (dwVerInfoSize)
   {
   BOOL  fRet, fRetName;
   char str[256];
   LPSTR   lpstrVffInfo; /* Pointer to block to hold info */
   LPSTR lszVer = NULL;
   LPSTR lszVerName = NULL;
   UINT  cchVer = 0;

   /* Get a block big enough to hold the version information */
   hMem          = GlobalAlloc(GMEM_MOVEABLE, dwVerInfoSize);
   lpstrVffInfo  = GlobalLock(hMem);

   /* Get the version information */
   if (GetFileVersionInfo(szFullPath, 0L, dwVerInfoSize, lpstrVffInfo))
      {
      fRet = VerQueryValue(lpstrVffInfo,
               TEXT("\\StringFileInfo\\040904E4\\FileVersion"),
              (LPVOID)&lszVer,
              &cchVer);
      fRetName = VerQueryValue(lpstrVffInfo,
               TEXT("\\StringFileInfo\\040904E4\\CompanyName"),
               (LPVOID)&lszVerName,
               &cchVer);
      if (!fRet || !fRetName ||
         (lstrcmpi(lszVer, UNZ_DLL_VERSION) != 0) ||
         (lstrcmpi(lszVerName, COMPANY_NAME) != 0))
         {
         wsprintf (str, DLL_VERSION_WARNING, UNZ_DLL_NAME);
         printf("%s\n", str);
         FreeUpMemory();
         GlobalUnlock(hMem);
         GlobalFree(hMem);
         return 0;
         }
      }
      /* free memory */
   GlobalUnlock(hMem);
   GlobalFree(hMem);
   }
else
   {
   char str[256];
   wsprintf (str, DLL_VERSION_WARNING, UNZ_DLL_NAME);
   printf("%s\n", str);
   FreeUpMemory();
   return 0;
   }
/* Okay, now we know that the dll exists, and has the proper version
 * information in it. We can go ahead and load it.
 */
hUnzipDll = LoadLibrary(UNZ_DLL_NAME);
#ifndef WIN32
if (hUnzipDll > HINSTANCE_ERROR)
#else
if (hUnzipDll != NULL)
#endif
   {
   Wiz_SingleEntryUnzip =
     (_DLL_UNZIP)GetProcAddress(hUnzipDll, "Wiz_SingleEntryUnzip");
   }
else
   {
   char str[256];
   wsprintf (str, "Could not load %s", UNZ_DLL_NAME);
   printf("%s\n", str);
   FreeUpMemory();
   return 0;
   }

/*
   Here is where the actual extraction process begins. First we set up the
   flags to be passed into the dll.
 */
lpDCL->ncflag = 0; /* Write to stdout if true */
lpDCL->fQuiet = 0; /* We want all messages.
                      1 = fewer messages,
                      2 = no messages */
lpDCL->ntflag = 0; /* test zip file if true */
lpDCL->nvflag = 0; /* give a verbose listing if true */
lpDCL->nzflag = 0; /* display a zip file comment if true */
lpDCL->ndflag = 1; /* Recreate directories if true */
lpDCL->naflag = 0; /* Do not convert CR to CRLF */
lpDCL->nfflag = 0; /* Do not freshen existing files only */
lpDCL->noflag = 1; /* Over-write all files if true */
lpDCL->ExtractOnlyNewer = 0; /* Do not extract only newer */
lpDCL->PromptToOverwrite = 0; /* "Overwrite all" selected -> no query mode */
lpDCL->lpszZipFN = argv[1]; /* The archive name */
lpDCL->lpszExtractDir = NULL; /* The directory to extract to. This is set
                                 to NULL if you are extracting to the
                                 current directory.
                               */
/*
   As this is a quite short example, intended primarily to show how to
   load and call in to the dll, the command-line parameters are only
   parsed in a very simplistic way:
   We assume that the command-line parameters after the zip archive
   make up a list of file patterns:
   " [file_i1] [file_i2] ... [file_iN] [-x file_x1 [file_x2] ...]".
   We scan for an argument "-x"; all arguments in front are
   "include file patterns", all arguments after are "exclude file patterns".
   If no more arguments are given, we extract ALL files.

   In summary, the example program should be run like:
   example <archive.name> [files to include] [-x files to exclude]
   ("<...> denotes mandatory arguments, "[...]" optional arguments)
 */
x_opt = NULL;
if (argc > 2) {
  infv = &argv[2];
  for (infc = 0; infc < argc-2; infc++)
    if (!strcmp("-x", infv[infc])) {
        x_opt = infv[infc];
        infv[infc] = NULL;
        break;
    }
  exfc = argc - infc - 3;
  if (exfc > 0)
    exfv = &argv[infc+3];
  else {
    exfc = 0;
    exfv = NULL;
  }
} else {
  infc = exfc = 0;
  infv = exfv = NULL;
}
retcode = (*Wiz_SingleEntryUnzip)(infc, infv, exfc, exfv, lpDCL,
                                  lpUserFunctions);
if (x_opt) {
  infv[infc] = x_opt;
  x_opt = NULL;
}

if (retcode != 0)
   printf("Error unzipping...\n");

FreeUpMemory();
FreeLibrary(hUnzipDll);
return 1;
}