Downloader application using pure C/C++ WinAPI

#include
#include
#include
#include
#include "jpeg_decoder.h"
#include "media.h"
#include "appdata.h"
#include
#include
#include
/*****************************************
Downloader application from @bitetti
marcosbitetti@gmail.com
*****************************************/
/* Declare Windows procedure */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
void setLabel(const char*);
/* hint of http://globalhackers.blogspot.com/2008/11/how-to-skin-your-guis-in-cc.html */
// defines, we will need these later
#ifndef LWA_COLORKEY
#define LWA_COLORKEY 0x00000001
#endif
#ifndef LWA_ALPHA
#define LWA_ALPHA 0x00000002
#endif
#ifndef g_ColourKey
#define g_ColourKey 0xFF00FF // 0,0,255(pink) in RGB hex value
#endif
// declare the function
typedef BOOL (WINAPI *lpfnSetLayeredWindowAttributes)(HWND hWnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);
lpfnSetLayeredWindowAttributes SetLayeredWindowAttributes;
#define WIN_WIDTH 360
#define WIN_HEIGHT 200
#define WM_UPDATE_PROGRESS_DA_PARADA 100101
/* Make the class name into a global variable */
char szClassName[ ] = "WildWitchProjectDownloader";
/* imagens */
Jpeg::Decoder* imagens[16];
//tela
unsigned char tela[ WIN_WIDTH*WIN_HEIGHT*3 ];
HWND hwnd; /* This is the handle for our window */
HINSTANCE hinstance;
HWND label;
HWND labelS;
int mouseX;
int mouseY;
struct Botao
{
Botao() { visible=true; left=top=right=bottom=imgID=imgOverID=imgMaskID=0; };
bool over(int x, int y)
{
if (x>=left && x<=right && y>=top && y<=bottom) return true;
return false;
}
int left;
int top;
int right;
int bottom;
int imgID;
int imgOverID;
int imgMaskID;
bool visible;
};
Botao botao[2];
unsigned char* getImage( int resourceName, size_t &size )
{
HRSRC rsrc = FindResource(NULL, MAKEINTRESOURCE(resourceName), "BINARY"); // RT_RCDATA
if(!rsrc)
{
//std::cout<<"nao acho resource\n";
return 0;
}
HGLOBAL glo = LoadResource(NULL, rsrc);
if (!glo)
{
//std::cout<<"nao carrega\n";
return 0;
}
size = SizeofResource(NULL, rsrc);
if(size == 0)
{
//std::cout<<"tamanho?\n";
return 0;
}
return (unsigned char*) LockResource(glo);
}
/**
Carrega as imagens
*/
int loadedImagens = 0;
void prepareImagens()
{
size_t size;
unsigned char* data;
int index = 0;
data = getImage(FGR,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(FGR_M,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(BORDAS,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
// botoes
data = getImage(BOT01,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(BOT01OV,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(BOT01SD,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
botao[0].left=WIN_WIDTH-imagens[BOT01]->GetWidth()-4;
botao[0].top=2;
botao[0].right=botao[0].left + imagens[BOT01]->GetWidth();
botao[0].bottom=botao[0].top + imagens[BOT01]->GetHeight();
botao[0].imgID = BOT01;
botao[0].imgOverID = BOT01OV;
botao[0].imgMaskID = BOT01SD;
data = getImage(BOT02,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(BOT02OV,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(BOT02SD,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
botao[1].left=(WIN_WIDTH/2)-(imagens[BOT02]->GetWidth()/2);
botao[1].top=124;
botao[1].right=botao[1].left + imagens[BOT02]->GetWidth();
botao[1].bottom=botao[1].top + imagens[BOT02]->GetHeight();
botao[1].imgID = BOT02;
botao[1].imgOverID = BOT02OV;
botao[1].imgMaskID = BOT02SD;
botao[1].visible = false;
// barras
data = getImage(BARRA01,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(BARRA02,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
//slides
data = getImage(SLIDE01,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(SLIDE02,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(SLIDE03,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
data = getImage(SLIDE04,size);
if (data) imagens[index++] = new Jpeg::Decoder(data,size);
loadedImagens = index;
}
void destroyImagens()
{
for( int i=0; i<loadedImagens; i++)
if (imagens[i]) delete imagens[i];
}
void drawImage( int imagemIndex, int x, int y)
{
Jpeg::Decoder* img = imagens[imagemIndex];
unsigned char* pixel = img->GetImage();
BYTE* ptr;
static int MHEIGHT = WIN_WIDTH*(WIN_HEIGHT-1)*3;
for( int lin=y; linGetHeight()+y; lin++)
{
ptr = &tela[0] + (MHEIGHT - lin*WIN_WIDTH*3) + x*3;
int max = img->GetWidth()+x;
if (max>WIN_WIDTH) max = WIN_WIDTH;
for( int col=x; col<max; col++)
{
BYTE r = *pixel++;
BYTE g = *pixel++;
BYTE b = *pixel++;
/*SetPixel(dc,col,lin, RGB(r,g,b));*/
*ptr++ = b;
*ptr++ = g;
*ptr++ = r;
}
int dif = (img->GetWidth()+x) - WIN_WIDTH;
if (dif>0)
pixel += 3*dif;
}
}
void drawImagePartial( int imagemIndex, int x, int y, float p=1)
{
Jpeg::Decoder* img = imagens[imagemIndex];
int maxCol = (int) ( p*(float)img->GetWidth() );
unsigned char* pixel = img->GetImage();
BYTE* ptr;
int atualCol=0;
static int MHEIGHT = WIN_WIDTH*(WIN_HEIGHT-1)*3;
for( int lin=y; linGetHeight()+y; lin++)
{
ptr = &tela[0] + (MHEIGHT - lin*WIN_WIDTH*3) + x*3;
int max = img->GetWidth()+x;
if (max>WIN_WIDTH) max = WIN_WIDTH;
atualCol=0;
for( int col=x; col<max; col++)
{
BYTE r = *pixel++;
BYTE g = *pixel++;
BYTE b = *pixel++;
/*SetPixel(dc,col,lin, RGB(r,g,b));*/
if (atualCol<maxCol)
{
*ptr++ = b;
*ptr++ = g;
*ptr++ = r;
} else ptr += 3;
atualCol++;
}
int dif = (img->GetWidth()+x) - WIN_WIDTH;
if (dif>0)
pixel += 3*dif;
}
}
void drawMaskedImage( int imagemIndex, int maskIndex, int x, int y)
{
Jpeg::Decoder* img = imagens[imagemIndex];
Jpeg::Decoder* msk = imagens[maskIndex];
unsigned char* pixel = img->GetImage();
unsigned char* mask = msk->GetImage();
BYTE* ptr;
static int MHEIGHT = WIN_WIDTH*(WIN_HEIGHT-1)*3;
for( int lin=y; linGetHeight()+y; lin++)
{
ptr = &tela[0] + (MHEIGHT - lin*WIN_WIDTH*3) + x*3;
for( int col=x; colGetWidth()+x; col++)
{
// técnica de blend http://en.wikipedia.org/wiki/Alpha_Blend
/* //simples transparencia mas toska
BYTE r = *pixel++;
BYTE g = *pixel++;
BYTE b = *pixel++;
int a = (int) *mask++;
if (a>128)
{
*ptr++ = b;
*ptr++ = g;
*ptr++ = r;
} else {
ptr += 3;
}*/
BYTE sr = *pixel++;
BYTE sg = *pixel++;
BYTE sb = *pixel++;
float a = (float) *mask++ / 255;
BYTE dr = *(ptr+2);
BYTE dg = *(ptr+1);
BYTE db = *ptr;
dr = sr*a + dr*(1-a);
dg = sg*a + dg*(1-a);
db = sb*a + db*(1-a);
*ptr++ = db;
*ptr++ = dg;
*ptr++ = dr;
}
}
}
// blend seguindo a linha http://en.wikipedia.org/wiki/Blend_modes
#define BLEND_ADD 1
#define BLEND_MULTIPLY 2
void drawImageBlend( int imagemIndex, int x, int y, int blendMode)
{
static double DV = 1.0/255.0;
Jpeg::Decoder* img = imagens[imagemIndex];
unsigned char* pixel = img->GetImage();
BYTE* ptr;
static int MHEIGHT = WIN_WIDTH*(WIN_HEIGHT-1)*3;
switch( blendMode )
{
case BLEND_ADD:
for( int lin=y; linGetHeight()+y; lin++)
{
ptr = &tela[0] + (MHEIGHT - lin*WIN_WIDTH*3) + x*3;
for( int col=x; colGetWidth()+x; col++)
{
BYTE* cor = ptr;
BYTE r = *cor++ + *pixel++;
BYTE g = *cor++ + *pixel++;
BYTE b = *cor++ + *pixel++;
if (r>255) r=255;
if (g>255) g=255;
if (b>255) b=255;
*ptr++ = b;
*ptr++ = g;
*ptr++ = r;
}
}
break;
case BLEND_MULTIPLY:
for( int lin=y; linGetHeight()+y; lin++)
{
ptr = &tela[0] + (MHEIGHT - lin*WIN_WIDTH*3) + x*3;
for( int col=x; colGetWidth()+x; col++)
{
BYTE* cor = ptr;
BYTE r = (double)(*cor++ * *pixel++) * DV;
BYTE g = (double)(*cor++ * *pixel++) * DV;
BYTE b = (double)(*cor++ * *pixel++) * DV;
if (r>255) r=255;
if (g>255) g=255;
if (b>255) b=255;
*ptr++ = b;
*ptr++ = g;
*ptr++ = r;
}
}
break;
}
}
void drawBordas( )
{
Jpeg::Decoder* img = imagens[BORDAS];
unsigned char* pixel = img->GetImage();
BYTE* ptr;
static int MHEIGHT = WIN_WIDTH*(WIN_HEIGHT-1)*3;
for( int lin=0; linGetHeight(); lin++)
{
ptr = &tela[0] + (MHEIGHT - lin*WIN_WIDTH*3);
for( int col=0; col<WIN_WIDTH; col++)
{
BYTE i = *pixel++;
if (i<128)
{
*ptr++ = 0;
*ptr++ = 255;
*ptr++ = 0;
} else ptr += 3;
}
}
}
/**
Monta tela
**/
UINT_PTR slideTimmerID;
int tick;
int xSlider=0;
int sliderPos=0;
#define MAX_SLIDERS 4
int currentFundo=SLIDE01;
int currentSlider = -1;
float percentTotal=0;
float percentCurrent=0;
void montaTela()
{
// fundao
drawImage(currentFundo,0,0);
if(currentSlider>-1) drawImage(currentSlider,xSlider,0);
drawMaskedImage(FGR,FGR_M,0,0);
drawMaskedImage( (botao[0].over(mouseX,mouseY)) ? botao[0].imgOverID : botao[0].imgID, botao[0].imgMaskID, botao[0].left, botao[0].top );
//drawMaskedImage( botao[1].imgOverID, botao[1].imgMaskID, 20, 20 );
if(botao[1].visible)
{
drawMaskedImage( (botao[1].over(mouseX,mouseY)) ? botao[1].imgOverID : botao[1].imgID, botao[1].imgMaskID, botao[1].left, botao[1].top );
drawImagePartial(BARRA01,14,182,1);
drawImagePartial(BARRA02,28,190,1);
setLabel("Clique para iniciar.");
} else {
drawImagePartial(BARRA01,14,182,percentCurrent);
drawImagePartial(BARRA02,28,190,percentTotal);
}
drawBordas();
}
void sliderAnim()
{
tick++;
if (tick>20)
{
if (xSlider==0)
{
sliderPos++;
if (sliderPos>=MAX_SLIDERS) sliderPos = 0;
currentSlider = sliderPos + SLIDE01;
xSlider = WIN_WIDTH-1;
} else {
xSlider -= ((float)xSlider*0.3);
if (xSlider<1)
{
tick=0;
currentFundo = currentSlider;
currentSlider = -1;
xSlider=0;
}
//InvalidateRect (hwnd, 0, true);
//UpdateWindow (hwnd);
RedrawWindow(hwnd,0,0,true);
}
}
}
void paintTela(HDC dc)
{
unsigned char* pixel;
HDC hDC, MemDCExercising;
BITMAPINFOHEADER header;
BITMAPINFO info;
BITMAPINFO bitInf;
bitInf.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitInf.bmiHeader.biWidth = WIN_WIDTH;
bitInf.bmiHeader.biHeight = WIN_HEIGHT;
bitInf.bmiHeader.biPlanes = 1;
bitInf.bmiHeader.biBitCount = 8*3;
bitInf.bmiHeader.biCompression = BI_RGB;
HDC iDC = CreateCompatibleDC( dc );
BYTE* bytes;
BYTE* ptr = &tela[0];
HBITMAP bmp = CreateDIBSection(iDC, &bitInf, DIB_RGB_COLORS, (void**) &bytes, 0, 0);
for(int i=0; i<sizeof(tela); i++)
*bytes++ = *ptr++;
SelectObject( iDC,bmp );
//BitBlt(dc,0, 0, WIN_WIDTH, WIN_HEIGHT, iDC, 0, 0, BLACKNESS );
BitBlt(dc,0, 0, WIN_WIDTH, WIN_HEIGHT, iDC, 0, 0, SRCCOPY );
//free(bytes);
DeleteDC(iDC);
DeleteObject(bmp);
}
void contextMenu(int x, int y)
{
HMENU hPopupMenu = CreatePopupMenu();
InsertMenu(hPopupMenu, 0, MF_BYPOSITION | MF_STRING, MENU_CONFIGURAR , "&Configurações");
InsertMenu(hPopupMenu, 0, MF_BYPOSITION | MF_STRING, MENU_AJUDA , "&Ajuda");
InsertMenu(hPopupMenu, 0, MF_BYPOSITION | MF_STRING, MENU_CLOSE, "F&echar");
SetForegroundWindow(hwnd);
TrackPopupMenu(hPopupMenu, 0 /*TPM_VCENTERALIGN | TPM_CENTERALIGN*/, x, y, 0, hwnd, NULL);
}
void showAjuda()
{
#define LEIAME "leiame.html"
// pequena gambi, usar o getImage para obter o arquivo texto
size_t size;
const char* dt = (const char*) getImage(AJUDA,size);
#ifndef NDEBUG
printf("%s\n",dt);
#endif
FILE *file;
file = fopen(LEIAME,"w");
fprintf(file,"%s",dt);
fclose(file);
ShellExecute(NULL, "open", LEIAME, NULL, NULL, SW_SHOWNORMAL);
}
/**
*
* Manipulação de rede
*
**/
// Inicio da implementaçao usando WinHTTP
typedef LPVOID HINTERNET;
typedef HINTERNET * LPHINTERNET;
typedef WORD INTERNET_PORT;
typedef INTERNET_PORT * LPINTERNET_PORT;
#if (defined(_M_IX86) || defined(_M_IA64) || defined(_M_AMD64)) && !defined(MIDL_PASS)
#define DECLSPEC_IMPORT __declspec(dllimport)
#else
#define DECLSPEC_IMPORT
#endif
#if !defined(_WINHTTP_INTERNAL_)
#define WINHTTPAPI DECLSPEC_IMPORT
#else
#define WINHTTPAPI
#endif
#define INTERNET_DEFAULT_PORT 0 // use the protocol-specific default
#define INTERNET_DEFAULT_HTTP_PORT 80 // " " HTTP "
#define INTERNET_DEFAULT_HTTPS_PORT 443 // " " HTTPS "
#define WINHTTP_FLAG_ASYNC 0x10000000 // this session is asynchronous (where supported)
#define WINHTTP_FLAG_SECURE 0x00800000 // use SSL if applicable (HTTPS)
#define WINHTTP_FLAG_ESCAPE_PERCENT 0x00000004 // if escaping enabled, escape percent as well
#define WINHTTP_FLAG_NULL_CODEPAGE 0x00000008 // assume all symbols are ASCII, use fast convertion
#define WINHTTP_FLAG_BYPASS_PROXY_CACHE 0x00000100 // add "pragma: no-cache" request header
#define WINHTTP_FLAG_REFRESH WINHTTP_FLAG_BYPASS_PROXY_CACHE
#define WINHTTP_FLAG_ESCAPE_DISABLE 0x00000040 // disable escaping
#define WINHTTP_FLAG_ESCAPE_DISABLE_QUERY 0x00000080 // if escaping enabled escape path part, but do not escape query
#define SECURITY_FLAG_IGNORE_UNKNOWN_CA 0x00000100
#define SECURITY_FLAG_IGNORE_CERT_DATE_INVALID 0x00002000 // expired X509 Cert.
#define SECURITY_FLAG_IGNORE_CERT_CN_INVALID 0x00001000 // bad common name in X509 Cert.
#define SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE 0x00000200
#define WINHTTP_ACCESS_TYPE_DEFAULT_PROXY 0
#define WINHTTP_ACCESS_TYPE_NO_PROXY 1
#define WINHTTP_ACCESS_TYPE_NAMED_PROXY 3
#define WINHTTP_NO_PROXY_NAME NULL
#define WINHTTP_NO_PROXY_BYPASS NULL
#define WINHTTP_NO_REFERER NULL
#define WINHTTP_DEFAULT_ACCEPT_TYPES NULL
#define WINHTTP_NO_ADDITIONAL_HEADERS NULL
#define WINHTTP_NO_REQUEST_DATA NULL
//typedef BOOL (WINAPI *lpfnSetLayeredWindowAttributes)(HWND hWnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);
//lpfnSetLayeredWindowAttributes SetLayeredWindowAttributes;
typedef HINTERNET ( WINAPI *lpWinHttpOpen)
( LPCWSTR pszAgentW, DWORD dwAccessType, LPCWSTR pszProxyW, LPCWSTR pszProxyBypassW, DWORD dwFlags );
lpWinHttpOpen WinHttpOpen;
typedef HINTERNET (WINAPI *lpWinHttpConnect)
( HINTERNET hSession,LPCWSTR pswzServerName, INTERNET_PORT nServerPort, DWORD dwReserved);
lpWinHttpConnect WinHttpConnect;
typedef HINTERNET (WINAPI *lpWinHttpOpenRequest)
(HINTERNET hConnect, LPCWSTR pwszVerb, LPCWSTR pwszObjectName, LPCWSTR pwszVersion, LPCWSTR pwszReferrer OPTIONAL, LPCWSTR FAR * ppwszAcceptTypes OPTIONAL, DWORD dwFlags);
lpWinHttpOpenRequest WinHttpOpenRequest;
typedef HINTERNET (WINAPI *lpWinHttpSendRequest)
(HINTERNET hRequest, LPCWSTR pwszHeaders OPTIONAL, DWORD dwHeadersLength, LPVOID lpOptional OPTIONAL, DWORD dwOptionalLength, DWORD dwTotalLength, DWORD_PTR dwContext);
lpWinHttpSendRequest WinHttpSendRequest;
typedef BOOL (WINAPI *lpWinHttpReceiveResponse)
(HINTERNET hRequest, LPVOID lpReserved);
lpWinHttpReceiveResponse WinHttpReceiveResponse;
typedef BOOL WINAPI (WINAPI *lpWinHttpQueryDataAvailable)
(HINTERNET hRequest, LPDWORD lpdwNumberOfBytesAvailable);
lpWinHttpQueryDataAvailable WinHttpQueryDataAvailable;
typedef BOOL WINAPI (WINAPI *lpWinHttpReadData)
(HINTERNET hRequest, LPVOID lpBuffer, DWORD dwNumberOfBytesToRead, LPDWORD lpdwNumberOfBytesRead);
lpWinHttpReadData WinHttpReadData;
typedef BOOL WINAPI (WINAPI *lpWinHttpCloseHandle)
(HINTERNET hInternet);
lpWinHttpCloseHandle WinHttpCloseHandle;
HANDLE thread_handle;
DWORD thread_id; // thread id
DWORD maxSizeToDownload;
char loadNumString[64];
//#define SERVIDOR L"localhost"
#define SERVIDOR L"dl.dropbox.com"
//#define REMOTE_PATH "rc/"
#define REMOTE_PATH "u/270587/wwp/"
const char* humanReadableSize(DWORD size)
{
const int KB = 1024;
const int MB = 1048576;
const int GB = 1073741824;
DWORD gb,mb,kb,bt;
char txt[256];
if (size>=GB)
{
gb = floor((double)size/(double)GB);
mb = round( (size-gb*GB)/100 );
sprintf(txt,"%i,%iGB",gb,kb);
} else if (size>=MB)
{
mb = floor((double)size/(double)MB);
kb = round( (size-mb*MB)/100 );
sprintf(txt,"%i,%iMB",mb,kb);
} else if (size>=KB)
{
kb = floor((double)size/(double)KB);
bt = round( (size-kb*KB)/100 );
sprintf(txt,"%i,%ikB",kb,bt);
} else
{
sprintf(txt,"%iB", size);
}
return (const char*) txt;
}
bool makeDir(char* path)
{
char* tk = path;
char* ch = path;
char* mpath = new char[256];
char *finalPath = new char[512];
memset(finalPath,0,512);
sprintf(finalPath,".");
while(*ch!=0)
{
if (*ch=='/')
{
memset(mpath,0,128);
memcpy(mpath,tk,ch-tk);
strcat(finalPath,"\\");
strcat(finalPath,mpath);
printf("%s\n",finalPath);
CreateDirectory(finalPath,0);
tk = ch+1;
}
ch++;
}
delete [] finalPath;
delete [] mpath;
return true;
}
bool download(char* url, FILE* dst, DWORD fsize)
{
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
bool bResults = false;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
char texto[256];
DWORD total = 0;
DWORD totalACarregar = fsize;
time_t initTime;
time_t atualTime;
DWORD secLoaded = 0;
//url
char baseURL[512];
sprintf(baseURL,"%s%s",REMOTE_PATH,url);
printf("dow %s\n", baseURL);
int len = strlen(baseURL)+1;
wchar_t* wurl = new wchar_t[len];
memset(wurl,0,len);
MultiByteToWideChar( CP_ACP, NULL,baseURL, -1, wurl,len );
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen( L"HTTP Teste/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0 );
// Specify an HTTP server.
if( hSession )
hConnect = WinHttpConnect( hSession, SERVIDOR,
INTERNET_DEFAULT_HTTP_PORT, 0 );
// Create an HTTP request handle.
if( hConnect )
hRequest = WinHttpOpenRequest( hConnect, L"GET", (LPCWSTR) wurl,
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_REFRESH );
// Send a request.
if( hRequest )
bResults = WinHttpSendRequest( hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0,
0, 0 );
// End the request.
if( bResults )
bResults = WinHttpReceiveResponse( hRequest, NULL );
// Keep checking for data until there is nothing left.
initTime = 0;//time(0);
if( bResults )
{
do
{
// Check for available data.
dwSize = 0;
if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
{
printf( "Error %u in WinHttpQueryDataAvailable.\n",
GetLastError( ) );
sprintf(texto,"Error %u in WinHttpQueryDataAvailable.\n", GetLastError( ));
SendMessage(hwnd, WM_UPDATE_PROGRESS_DA_PARADA, (WORD) dwSize , LPARAM(texto));
}
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize+1];
if( !pszOutBuffer )
{
sprintf(texto,"Out of memory\n");
SendMessage(hwnd, WM_UPDATE_PROGRESS_DA_PARADA, (WORD) dwSize , LPARAM(texto));
dwSize=0;
}
else
{
// Read the data.
ZeroMemory( pszOutBuffer, dwSize+1 );
if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded ) )
{
printf( "Error %u in WinHttpReadData.\n", GetLastError( ) );
sprintf(texto,"Error %u in WinHttpReadData.\n", GetLastError( ));
SendMessage(hwnd, WM_UPDATE_PROGRESS_DA_PARADA, (WORD) dwSize , LPARAM(texto));
}
else
//printf( "%s", pszOutBuffer );
fwrite(pszOutBuffer,1,dwSize,dst);
total += dwSize;
secLoaded += dwSize;
if (totalACarregar==0)
{
sprintf(texto, "%s> %s de ??",loadNumString, humanReadableSize(total));
} else {
float p = 100.0*((long double)total/(long double) maxSizeToDownload); //totalACarregar);
int p1 = floor(p);
int p2 = round( (p-(float)p1)*100 );
int p3 = round( 100.0*((long double)total/(long double)totalACarregar));
// texto base
char t1[64];
char t2[64];
strcpy(t1,humanReadableSize(total));
strcpy(t2,humanReadableSize(maxSizeToDownload));//totalACarregar));
sprintf(texto, "%s> %s de %s (%i,%i%) ", loadNumString, t1, t2,p1,p2);
// tempo restante
atualTime = time(0);
if (atualTime>initTime)
{
DWORD dif = atualTime - initTime;
DWORD resto = maxSizeToDownload - total; //totalACarregar - total;
DWORD bytesPerSecond = secLoaded / dif;
secLoaded=0;
initTime = atualTime;
char _txt[128];
memset(_txt,0,128);
if (bytesPerSecond>0)
{
DWORD restSeconds = resto/bytesPerSecond;
DWORD min = restSeconds/60;
DWORD hours = min/60;
DWORD sec = restSeconds-min*60;
min -= hours*60;
sprintf(_txt,"falta %ih %im %is", hours, min, sec);
} else sprintf(_txt,"falta ? horas");
strcat(texto,_txt);
//printf("%u %i %i\n",bytesPerSecond, p1,p3 );
// envia texto ao sistema
WORD updateValues=(BYTE)p1 | (BYTE) p3<<8;
SendMessage(hwnd, WM_UPDATE_PROGRESS_DA_PARADA, updateValues , LPARAM(texto));
}
}
// Free the memory allocated to the buffer.
delete [] pszOutBuffer;
Sleep(8);
}
} while( dwSize > 0 );
}
// Report any errors.
if( !bResults )
// error messages: http://msdn.microsoft.com/en-us/library/windows/desktop/aa383770(v=vs.85).aspx
printf( "Error %d has occurred.\n", GetLastError( ) );
else
{
sprintf(texto,"%s carregado.", url );
}
// Close any open handles.
if( hRequest ) WinHttpCloseHandle( hRequest );
if( hConnect ) WinHttpCloseHandle( hConnect );
if( hSession ) WinHttpCloseHandle( hSession );
}
static DWORD WINAPI performNetwork(void *pArg)
{
printf("rodando thread\n");
FILE* config;
FILE* tmpFile;
char* configData;
// configurações
CreateDirectory("_tmp",0);
setLabel("Procurando arquivo de configuração...");
config = fopen("_tmp\\list","wb");
download("simplelist", config,0 ); //baixa arquivo lista
//download()
fclose(config);
config = fopen("_tmp\\list","r");
fseek(config , 0 , SEEK_END);
int configFileSize = ftell(config);
rewind(config);
configData = new char[configFileSize+1];
memset(configData,0,configFileSize+1);
fread(configData, 1, configFileSize, config );
fclose(config);
// loop
char* plin = configData;
char fnome[512];
char fdata[512];
char* tok=fdata;
int numDownloads = 0;
int currentDownload = 0;
maxSizeToDownload=0;
while(true)
{
if(*plin==' ')
tok = fdata;
else
if(*plin==10 || *plin==0)
{
*tok=0;
maxSizeToDownload += atoi(fdata);
numDownloads++;
} else {
*tok++ = *plin;
}
if(*plin==0) break;
plin++;
}
printf("Total a baixar: %i\n", maxSizeToDownload);
plin = configData;
tok = fdata;
while( true )
{
if(*plin==' ')
{
*tok=0;
memset(fnome,0,512);
strcpy(fnome,fdata);
tok = fdata;
} else
if(*plin==10 || *plin==0)
{
*tok=0;
if (strlen(fnome)>0)
{
char* tFNome = new char[512];
sprintf(tFNome,"_tmp\\%s", fnome);printf("%s\n",tFNome);
printf("arquivo: %s, tamanho: %u\n", fnome, atoi(fdata));
currentDownload++;
sprintf(loadNumString,"%i/%i", currentDownload, numDownloads );
makeDir(tFNome);
tmpFile = fopen(tFNome,"wb");
download(fnome, tmpFile, (DWORD) atoi(fdata));
fclose(tmpFile);
fnome[0]=0;
delete [] tFNome;
}
tok = fdata;
} else
{
*tok=*plin;
tok++;
}
if (*plin==0)
{
botao[1].visible=true;
break;
}
plin++;
}
delete [] configData;
if(currentDownload>=numDownloads)
{
botao[1].visible=true;
printf("Downloadei tudo\n");
botao[1].visible=true;
SendMessage(hwnd, WM_UPDATE_PROGRESS_DA_PARADA, (WORD) 0 , LPARAM("Carregado"));
}
}
void initNetwork()
{
HMODULE hWinHTTP;
if ( 0 == (hWinHTTP = GetModuleHandle("winhttp.dll")) )
{
if (0 == (hWinHTTP = LoadLibrary("winhttp.dll")) )
{
printf("nao achei\n");
}
}
if (hWinHTTP==0)
{
printf("Erro\n");
return;
}
//Monta os ponteiras de funções
WinHttpOpen = (lpWinHttpOpen)GetProcAddress(hWinHTTP, "WinHttpOpen");
WinHttpConnect = (lpWinHttpConnect)GetProcAddress(hWinHTTP, "WinHttpConnect");
WinHttpOpenRequest = (lpWinHttpOpenRequest)GetProcAddress(hWinHTTP, "WinHttpOpenRequest");
WinHttpSendRequest = (lpWinHttpSendRequest)GetProcAddress(hWinHTTP, "WinHttpSendRequest");
WinHttpReceiveResponse = (lpWinHttpReceiveResponse)GetProcAddress(hWinHTTP, "WinHttpReceiveResponse");
WinHttpQueryDataAvailable = (lpWinHttpQueryDataAvailable)GetProcAddress(hWinHTTP, "WinHttpQueryDataAvailable");
WinHttpReadData = (lpWinHttpReadData)GetProcAddress(hWinHTTP, "WinHttpReadData");
WinHttpCloseHandle = (lpWinHttpCloseHandle)GetProcAddress(hWinHTTP, "WinHttpCloseHandle");
if (WinHttpOpen==0) printf("Nao achei funcao\n");
// cria pasta
// inicia thread
thread_handle = CreateThread( 0,0,
performNetwork, (void*) hwnd, 0, &thread_id);
}
// fim da implementação usando WinHTTP
/**
// inicio implementação de rede usando URLMON.dll
typedef HRESULT (WINAPI *lpURLDownloadToFile)
(LPUNKNOWN pCaller, LPCTSTR szURL, LPCTSTR szFileName, DWORD dwReserved, LPBINDSTATUSCALLBACK lpfnCB);
lpURLDownloadToFile URLDownloadToFile;
void initNetwork()
{
HMODULE hURLMON;
if ( 0 == (hURLMON = GetModuleHandle("urlmon.dll")) )
{
if (0 == (hURLMON = LoadLibrary("urlmon.dll")) )
{
printf("nao achei\n");
}
}
if (hURLMON==0)
{ printf("Erro ao importar URLMON.DLL\n"); return; }
URLDownloadToFile = (lpURLDownloadToFile)GetProcAddress(hURLMON, "URLDownloadToFile");
}
// fim da implementação de rede usando URLMON.dll
**/
void setLabel(const char* txt)
{
SetWindowText(label, txt );
SetWindowText(labelS, txt );
RedrawWindow(hwnd,0,0,true);
printf("%s\n",txt);
}
void setLabel(char* txt)
{
setLabel( (const char*) txt );
}
// ---------------------------
// Manipul as mensagens do Windows
//
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
UINT uHitTest;
int xPos, yPos;
SHORT key;
RECT rec;
HFONT font;
static bool lBot = false;
static bool rBot = false;
switch (message) /* handle the messages */
{
case WM_CREATE:
prepareImagens();
slideTimmerID = SetTimer(hwnd, 0, 50, 0);
SetFocus(hwnd);
SetWindowPos(hwnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE);
SetWindowPos(hwnd,HWND_NOTOPMOST,0,0,0,0,SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
initNetwork();
break;
case WM_SETFOCUS:
SetWindowPos(hwnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE);
SetWindowPos(hwnd,HWND_NOTOPMOST,0,0,0,0,SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
//SetCapture(hwnd);
break;
case WM_KILLFOCUS:
//ReleaseCapture();
//std::cout<<"lost\n";
break;
case WM_DESTROY:
destroyImagens();
PostQuitMessage (0); /* send a WM_QUIT to the message queue */
break;
case WM_SHOWWINDOW:
//SetWindowLong(hwnd , GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_CLIENTEDGE);
//AdjustWindowRect();
break;
case WM_PAINT:
//instance->atualizaJanela();
HDC hDC;
PAINTSTRUCT Ps;
hDC = BeginPaint(hwnd, &Ps);
montaTela();
paintTela(hDC);
EndPaint(hwnd, &Ps);
return DefWindowProc(hwnd, message, wParam, lParam);
break;
case WM_TIMER:
sliderAnim();
break;
case WM_NCHITTEST:
uHitTest = DefWindowProc(hwnd, WM_NCHITTEST, wParam, lParam);
if(uHitTest == HTCLIENT)
{
GetWindowRect( hwnd, &rec);
xPos = (int)LOWORD(lParam) - rec.left;
yPos = (int)HIWORD(lParam) - rec.top;
mouseX = xPos;
mouseY = yPos;
if (botao[0].over(xPos,yPos))
RedrawWindow(hwnd,0,0,true);
// left button
key = GetAsyncKeyState( VK_LBUTTON );
if (!key && lBot)
{
lBot = false;
SendMessage(hwnd,WM_SETFOCUS, wParam,lParam);
if (botao[0].over(xPos,yPos)) contextMenu((int)LOWORD(lParam), (int)HIWORD(lParam));
if (botao[1].over(xPos,yPos))
{ // chama aplicacao
//MessageBox(hwnd,"Abir","Abrir", MB_ICONINFORMATION);
ShellExecute(NULL, "explore", "_tmp", NULL, NULL, SW_SHOWNORMAL);
SendMessage(hwnd, WM_CLOSE, 0,0);
}
} else if (key && !lBot)
lBot = true;
else
lBot = false;
// right button
key = GetAsyncKeyState( VK_RBUTTON );
if (!key && rBot)
{
rBot = false;
contextMenu((int)LOWORD(lParam), (int)HIWORD(lParam));
} else if (key && !rBot)
rBot = true;
else
rBot = false;
return HTCAPTION;
}
else
{
mouseX = mouseY = -1;
lBot = false;
return uHitTest;
}
break;
case WM_COMMAND:
switch ((int)LOWORD(wParam))
{
case MENU_CLOSE:
SendMessage(hwnd, WM_CLOSE, 0,0);
break;
case MENU_AJUDA:
showAjuda();
break;
case MENU_CONFIGURAR:
//printf("Config2\n");
MessageBox(hwnd,"Nada a configurar no momento","Configurações", MB_ICONASTERISK | MB_OK);
break;
}
break;
case WM_CTLCOLORSTATIC:
// cor
SetBkMode((HDC)wParam, TRANSPARENT);
if ((HWND)lParam==label) SetTextColor((HDC)wParam, RGB(255,255,255));
if ((HWND)lParam==labelS) SetTextColor((HDC)wParam, RGB(20,20,20));
// fonte
font = CreateFont(10,6, 0, 0,
FW_NORMAL, FALSE, FALSE, FALSE,
ANSI_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, PROOF_QUALITY,//DEFAULT_QUALITY,
DEFAULT_PITCH | FF_ROMAN,
"Arial");
SelectObject((HDC)wParam, font);
return (INT_PTR)(HBRUSH)GetStockObject(NULL_BRUSH);
break;
case WM_UPDATE_PROGRESS_DA_PARADA: // interna
setLabel((const char*) lParam);
percentTotal = ((float)(LOWORD(wParam)&255)) / 100;
percentCurrent = ((float)(LOWORD(wParam)>>8)) / 100;
//printf("%i e %i\n", LOWORD(wParam)&255, LOWORD(wParam)>>8);
break;
default: /* for messages that we don't deal with */
return DefWindowProc (hwnd, message, wParam, lParam);
}
return 0;
}
// ---------------------------
// Ponto de entrada inicial do aplicativo
//
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nCmdShow)
{
MSG messages; /* Here messages to the application are saved */
WNDCLASSEX wincl; /* Data structure for the windowclass */
hinstance = hThisInstance;
/* The Window structure */
wincl.hInstance = hThisInstance;
wincl.lpszClassName = szClassName;
wincl.lpfnWndProc = WindowProcedure; /* This function is called by windows */
wincl.style = NULL;//CS_DBLCLKS; /* Catch double-clicks */
wincl.cbSize = sizeof (WNDCLASSEX);
/* Use default icon and mouse-pointer */
wincl.hIcon = LoadIcon(hThisInstance,MAKEINTRESOURCE(ICONE));//LoadIcon (NULL, IDI_APPLICATION);
wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
wincl.lpszMenuName = NULL; /* No menu */
wincl.cbClsExtra = 0; /* No extra bytes after the window class */
wincl.cbWndExtra = 0; /* structure or the window instance */
/* Use Windows's default colour as the background of the window */
wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
/* Register the window class, and if it fails quit the program */
if (!RegisterClassEx (&wincl))
return 0;
// Tela
RECT resolution;
GetWindowRect(GetDesktopWindow(), &resolution);
int dW = resolution.right;
int dH = resolution.bottom;
int x = (dW/2) - (WIN_WIDTH/2);
int y = (dH/2) - (WIN_HEIGHT/2);
/* The class is registered, let's create the program*/
hwnd = CreateWindowEx (
0, /* Extended possibilites for variation */
szClassName, /* Classname */
"Code::Blocks Template Windows App", /* Title Text */
WS_CHILD,// | ~WS_BORDER | ~WS_THICKFRAME,// | ~WS_CAPTION | ~WS_BORDER | ~WS_HSCROLL | ~WS_VSCROLL,//WS_OVERLAPPEDWINDOW | WS_EX_LAYERED,// | WS_CHILD | WS_VISIBLE, // /* default window */
x,//CW_USEDEFAULT, /* Windows decides the position */
y,//CW_USEDEFAULT, /* where the window ends up on the screen */
WIN_WIDTH, /* The programs width */
WIN_HEIGHT, /* and height in pixels */
GetDesktopWindow(),//HWND_DESKTOP, /* The window is a child-window to desktop */
NULL, /* No menu */
hThisInstance, /* Program Instance handler */
NULL /* No Window Creation data */
);
/* Make the window visible on the screen */
//ShowWindow (hwnd, nCmdShow);
ShowWindow(hwnd, SW_SHOWNORMAL);
UpdateWindow(hwnd);
//SetWindowPos( hwnd, HWND_TOP, x,y ,WIN_WIDTH, WIN_HEIGHT, ~SWP_DRAWFRAME );
SendMessage( hwnd, WM_SETICON, NULL, (LPARAM) LoadIcon(hThisInstance,MAKEINTRESOURCE(ICONE)) );
// atributos avançados
DWORD dwStyle = (DWORD) GetWindowLong(hwnd, GWL_STYLE);
dwStyle &= ~WS_CAPTION;
HMODULE hUser32 = GetModuleHandle(("USER32.DLL"));
// get pointer to function from DLL
SetLayeredWindowAttributes = (lpfnSetLayeredWindowAttributes)GetProcAddress(hUser32, "SetLayeredWindowAttributes");
// error importing function
if(SetLayeredWindowAttributes == NULL)
MessageBox(0, "Error importing function", "Error!", MB_ICONSTOP | MB_OK);
if(SetLayeredWindowAttributes != NULL)
{
SetWindowLong(hwnd , GWL_EXSTYLE, dwStyle /*| GetWindowLong(hwnd, GWL_EXSTYLE)*/ | WS_EX_LAYERED);
SetLayeredWindowAttributes(hwnd, RGB(0,255,0), 255, LWA_COLORKEY | LWA_ALPHA); // 255 = opaco
}
// componentes
labelS = CreateWindow(
"static",
">",
WS_VISIBLE | WS_CHILD | ES_READONLY | WS_EX_COMPOSITED // | WS_BORDER | WS_HSCROLL |
, 15,169, 330,26,
hwnd, (HMENU)1, hinstance, NULL
);
label = CreateWindow(
"static",
">",
WS_VISIBLE | WS_CHILD | ES_READONLY | WS_EX_COMPOSITED // | WS_BORDER | WS_HSCROLL |
, 14,168, 338,26,
hwnd, (HMENU)1, hinstance, NULL
);
/* Run the message loop. It will run until GetMessage() returns 0 */
while (GetMessage (&messages, NULL, 0, 0))
{
/* Translate virtual-key messages into character messages */
TranslateMessage(&messages);
/* Send message to WindowProcedure */
DispatchMessage(&messages);
}
/* The program return-value is 0 - The value that PostQuitMessage() gave */
//return messages.wParam;
return 0;
}
添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论