Exemplo n.º 1
0
/**
 * This function reads all the data from a connection into a buffer.
 *
 * @param s32 connection The connection identifier to suck the response out of
 * @return bool True if data downloaded succesfully.
 */
bool tcp_readData(const s32 connection, u8 **buffer, const u32 length)
{
	u8 *p;
	u32 left, block, received;
	s64 t;
	s32 res;

	p = *buffer;
	left = length;
	received = 0;

	t = gettime ();
	while (left)
	{
		if (ticks_to_millisecs (diff_ticks (t, gettime ())) > TCP_BLOCK_RECV_TIMEOUT)
			break;

		// Update the progress bar
		if(displayProgressWindow)
		{
			ShowProgress(received, length);
			if(ProgressCanceled())
			{
				ProgressStop();
				break;
			}
		}

		// Get next block size
		block = left;
		if (block > TCP_BLOCK_SIZE)
			block = TCP_BLOCK_SIZE;

		if(http_port == 443)
			res = ssl_read (connection, p, block);
		else
			res = net_read (connection, p, block);

		if ((res == 0) || (res == -EAGAIN))
		{
			usleep (20 * 1000);
			continue;
		}

		if (res < 0) break;

		received += res;
		left -= res;
		p += res;

		// update timing after each downloaded block
		t = gettime ();
	}

	return left == 0;
}
/****************************************************************************
 * Download a file from a given url with a Progressbar
 ****************************************************************************/
int DownloadFileToMem(const char *url, u8 **inbuffer, u32 *size)
{
	if(strncasecmp(url, "http://", strlen("http://")) != 0)
	{
		ShowError(tr("Not a valid URL"));
		return -1;
	}
	char *path = strchr(url + strlen("http://"), '/');

	if(!path)
	{
		ShowError(tr("Not a valid URL path"));
		return -2;
	}

	int domainlength = path - url - strlen("http://");

	if(domainlength == 0)
	{
		ShowError(tr("Not a valid domain"));
		return -3;
	}

	char domain[domainlength + 1];
	strncpy(domain, url + strlen("http://"), domainlength);
	domain[domainlength] = '\0';

	int connection = GetConnection(domain);

	if(connection < 0)
	{
		ShowError(tr("Could not connect to the server."));
		return -4;
	}

	char header[1024];
	char * ptr = header;
	ptr += sprintf(ptr, "GET %s HTTP/1.1\r\n", path);
	ptr += sprintf(ptr, "Host: %s\r\n", domain);
	ptr += sprintf(ptr, "Referer: %s\r\n", domain);
	ptr += sprintf(ptr, "User-Agent: USB Loader GX\r\n");
	ptr += sprintf(ptr, "Pragma: no-cache\r\n");
	ptr += sprintf(ptr, "Cache-Control: no-cache\r\n");
	ptr += sprintf(ptr, "Connection: close\r\n\r\n");

	char filename[255];
	memset(filename, 0, sizeof(filename));

	int filesize = network_request(connection, header, filename);

	if(filesize <= 0)
	{
		net_close(connection);
		ShowError(tr("Filesize is 0 Byte."));
		return -5;
	}

	int blocksize = 4*1024;

	u8 * buffer = (u8 *) malloc(filesize);
	if(!buffer)
	{
		net_close(connection);
		ShowError(tr("Not enough memory."));
		return -6;
	}

	ProgressCancelEnable(true);
	StartProgress(tr("Downloading file..."), 0, filename, true, true);

	int done = 0;

	while(done < filesize)
	{
		if(ProgressCanceled())
		{
			done = PROGRESS_CANCELED;
			break;
		}

		ShowProgress(done, filesize);

		if(blocksize > filesize - done)
			blocksize = filesize - done;


		s32 read = network_read(connection, buffer+done, blocksize);

		if(read < 0)
		{
			done = -8;
			ShowError(tr("Transfer failed"));
			break;
		}
		else if(!read)
			break;

		done += read;
	}

	ProgressStop();
	ProgressCancelEnable(false);
	net_close(connection);

	if(done < 0)
	{
		free(buffer);
		return done;
	}

	*inbuffer = buffer;
	*size = filesize;

	return done;
}
/****************************************************************************
 * Download a file from a given url to a given path with a Progressbar
 ****************************************************************************/
int DownloadFileToPath(const char *orig_url, const char *dest, bool UseFilename)
{
	if(!orig_url || !dest)
	{
		ShowError(tr("No URL or Path specified."));
		return -2;
	}

	bool addhttp = false;

	if(strncasecmp(orig_url, "http://", strlen("http://")) != 0)
	{
		addhttp = true;
	}

	char url[strlen(orig_url) + (addhttp ? strlen("http://") : 0) + 1];

	if(addhttp)
		snprintf(url, sizeof(url), "http://%s", orig_url);
	else
		strcpy(url, orig_url);

	char *path = strchr(url + strlen("http://"), '/');

	if(!path)
	{
		ShowError(tr("Not a valid URL path"));
		return -2;
	}

	int domainlength = path - url - strlen("http://");

	if(domainlength == 0)
	{
		ShowError(tr("Not a valid domain"));
		return -3;
	}

	char domain[domainlength + 1];
	strncpy(domain, url + strlen("http://"), domainlength);
	domain[domainlength] = '\0';

	int connection = GetConnection(domain);

	if(connection < 0)
	{
		ShowError(tr("Could not connect to the server."));
		return -4;
	}

	char header[1024];
	char * ptr = header;
	ptr += sprintf(ptr, "GET %s HTTP/1.1\r\n", path);
	ptr += sprintf(ptr, "Host: %s\r\n", domain);
	ptr += sprintf(ptr, "Referer: %s\r\n", domain);
	ptr += sprintf(ptr, "User-Agent: WiiXplorer\r\n");
	ptr += sprintf(ptr, "Pragma: no-cache\r\n");
	ptr += sprintf(ptr, "Cache-Control: no-cache\r\n");
	ptr += sprintf(ptr, "Connection: close\r\n\r\n");

	char filename[255];
	memset(filename, 0, sizeof(filename));

	int filesize = network_request(connection, header, filename);

	if(filesize <= 0)
	{
		net_close(connection);
		ShowError(tr("Filesize is %i Byte."), filesize);
		return -5;
	}

	int blocksize = 4*1024;

	u8 *buffer = (u8 *) malloc(blocksize);
	if(!buffer)
	{
		net_close(connection);
		ShowError(tr("Not enough memory."));
		return -6;
	}

	if(UseFilename)
	{
		if(dest[strlen(dest)-1] != '/')
			strcat((char *) dest, "/");

		CreateSubfolder(dest);

		strcat((char *) dest, filename);
	}

	if(!UseFilename && strcmp(filename, "") == 0)
	{
		const char * ptr = strrchr(dest, '/');
		if(ptr) ptr++;
		else ptr = dest;

		snprintf(filename, sizeof(filename), "%s", ptr);
	}

	FILE *file = fopen(dest, "wb");
	if(!file)
	{
		net_close(connection);
		free(buffer);
		ShowError(tr("Cannot write to destination."));
		return -7;
	}

	ProgressCancelEnable(true);
	StartProgress(tr("Downloading file..."), 0, filename, true, true);

	int done = 0;

	while(done < filesize)
	{
		if(ProgressCanceled())
		{
			done = PROGRESS_CANCELED;
			break;
		}

		ShowProgress(done, filesize);

		if(blocksize > filesize - done)
			blocksize = filesize - done;

		s32 read = network_read(connection, buffer, blocksize);

		if(read < 0)
		{
			done = -8;
			ShowError(tr("Transfer failed"));
			break;
		}
		else if(!read)
			break;

		fwrite(buffer, 1, read, file);

		done += read;
	}

	free(buffer);
	ProgressStop();
	net_close(connection);
	fclose(file);
	ProgressStop();
	ProgressCancelEnable(false);

	return done;
}
int HomebrewReceiver::ReceiveFile()
{
	char filesizetxt[50];
	char temp[50];
	u32 filesize = 0;

	if (infilesize < MB_SIZE)
		snprintf(filesizetxt, sizeof(filesizetxt), tr( "Incoming file %0.2fKB" ), infilesize / KB_SIZE);
	else snprintf(filesizetxt, sizeof(filesizetxt), tr( "Incoming file %0.2fMB" ), infilesize / MB_SIZE);

	snprintf(temp, sizeof(temp), tr( "Load file from: %s ?" ), GetIncommingIP());

	int choice = WindowPrompt(filesizetxt, temp, tr( "Load" ), tr( "Cancel" ));

	if (choice == 0)
		return 0;

	u32 read = 0;
	int len = NET_BLOCKSIZE;
	filesize = infilesize;
	u8 * buffer = (u8 *) malloc(infilesize);
	if(!buffer)
	{
		CloseConnection();
		WindowPrompt(tr( "Not enough memory." ), 0, tr( "OK" ));
		return 0;
	}

	bool error = false;
	while (read < infilesize)
	{
		ShowProgress(tr( "Receiving file from:" ), GetIncommingIP(), NULL, read, infilesize, true);
		
		if (infilesize - read < (u32) len)
			len = infilesize - read;
		else len = NET_BLOCKSIZE;
		
		int result = network_read(connection, buffer+read, len);
		
		if (result < 0)
		{
			CloseConnection();
			ProgressStop();
			WindowPrompt(tr( "Error while transfering data." ), 0, tr( "OK" ));
			free(buffer);
			return 0;
		}
		if (!result)
		{
			break;
		}
		
		read += result;
	}

	char filename[101];
	memset(filename, 0, sizeof(filename));
	
	network_read(connection, (u8*) filename, 100);
	
	//! Uncompress Wiiload
	if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4)
	{
		u8 *unc = (u8 *) malloc(uncfilesize);
		if(!unc)
		{
			free(buffer);
			CloseConnection();
			ProgressStop();
			WindowPrompt(tr( "Not enough memory." ), 0, tr( "OK" ));
			return 0;
		}
		
		uLongf f = uncfilesize;
		error = uncompress(unc, &f, buffer, infilesize) != Z_OK;
		uncfilesize = f;
		filesize = uncfilesize;
		
		free(buffer);
		buffer = unc;
		free(unc);
	}

	CopyHomebrewMemory(buffer, 0, filesize);
	
	ProgressStop();

	if (error || read != infilesize)
	{
		WindowPrompt(tr( "Error:" ), tr( "No data could be read." ), tr( "OK" ));
		FreeHomebrewBuffer();
		return 0;
	}

	CloseConnection();
	
	AddBootArgument(filename);

	return BootHomebrewFromMem();
}
Exemplo n.º 5
0
int UpdateLanguageFiles()
{
	if(!CreateSubfolder(Settings.languagefiles_path))
	{
		ShowError(tr("Could not create path: %s"), Settings.languagefiles_path);
		return -1;
	}

	if(!IsNetworkInit())
	{
		ShowError(tr("Network is not initiated."));
		return -2;
	}

	DirList Dir(Settings.languagefiles_path, ".lang");

	//give up now if we didn't find any
	if (Dir.GetFilecount() == 0)
	{
		if(WindowPrompt(tr("Error:"), tr("No language files to update on your devices! Do you want to download new language files?"), tr("Yes"), tr("No")))
			return DownloadAllLanguageFiles();

		return -2;
	}

	char savepath[150];
	char codeurl[200];

	//we assume that the network will already be init by another function
	// ( that has gui eletents in it because this one doesn't)
	int done = 0;

	//build the URL, save path, and download each file and save it
	for(int i = 0; i < Dir.GetFilecount(); ++i)
	{
		snprintf(codeurl, sizeof(codeurl), "%s%s?p=%s", LanguageFilesURL, Dir.GetFilename(i), GetRev());
		snprintf(savepath, sizeof(savepath), "%s/%s", Settings.languagefiles_path, Dir.GetFilename(i));

		struct block file = downloadfile(codeurl);

		ShowProgress(tr("Updating Language Files:"), 0, Dir.GetFilename(i), i, Dir.GetFilecount(), false, true);

		if (file.data != NULL)
		{
			FILE * pfile;
			pfile = fopen(savepath, "wb");
			if (pfile != NULL)
			{
				fwrite(file.data, 1, file.size, pfile);
				fclose(pfile);
				done++;
			}
			free(file.data);
		}
	}

	ProgressStop();

	// reload current language file
	if(Settings.language_path[0] != 0)
		Settings.LoadLanguage(Settings.language_path, CONSOLE_DEFAULT);
	else
		Settings.LoadLanguage(NULL, CONSOLE_DEFAULT);

	// return the number of files we updated
	return done;
}
Exemplo n.º 6
0
int DownloadAllLanguageFiles(int revision)
{
	if(!CreateSubfolder(Settings.languagefiles_path))
	{
		ShowError(tr("Could not create path: %s"), Settings.languagefiles_path);
		return -1;
	}

	if(!IsNetworkInit())
	{
		ShowError(tr("Network is not initiated."));
		return -2;
	}
	char fullURL[300];

	URL_List LinkList(LanguageFilesURL);
	int listsize = LinkList.GetURLCount();
	int files_downloaded = 0;
	char target[6];
	if(revision > 0)
		snprintf(target, sizeof(target), "%d", revision);
	else
		snprintf(target, sizeof(target), "%s", GetRev());

	ShowProgress(tr("Updating Language Files:"), 0, 0, 0, listsize, false, true);

	for (int i = 0; i < listsize; i++)
	{
		const char * filename = strrchr(LinkList.GetURL(i), '/');
		if(filename) filename++;
		else filename = LinkList.GetURL(i);

		if(!filename)
			continue;

		const char * FileExt = strrchr(filename, '.');
		if (!FileExt || strcasecmp(FileExt, ".lang") != 0)
			continue;

		debughelper_printf("%s\n", filename);

		ShowProgress(tr("Updating Language Files:"), 0, filename, i, listsize, false, true);

		snprintf(fullURL, sizeof(fullURL), "%s%s?p=%s", LanguageFilesURL, filename, target);

		struct block file = downloadfile(fullURL);
		if (file.data)
		{
			char filepath[300];
			snprintf(filepath, sizeof(filepath), "%s/%s", Settings.languagefiles_path, filename);
			FILE * pfile = fopen(filepath, "wb");
			if(pfile)
			{
				fwrite(file.data, 1, file.size, pfile);
				fclose(pfile);
				files_downloaded++;
			}
			free(file.data);
		}
	}

	ProgressStop();

	// reload current language file
	if(Settings.language_path[0] != 0)
		Settings.LoadLanguage(Settings.language_path, CONSOLE_DEFAULT);
	else
		Settings.LoadLanguage(NULL, CONSOLE_DEFAULT);

	return files_downloaded;
}
Exemplo n.º 7
0
/****************************************************************************
 * MenuHomebrewBrowse
 ***************************************************************************/
int MenuHomebrewBrowse() {
    int menu = MENU_NONE;
    int choice = 0;

    HomebrewFiles HomebrewFiles(Settings.homebrewapps_path);

    u32 filecount = HomebrewFiles.GetFilecount();

    if (!filecount) {
        WindowPrompt(tr("No .dol or .elf files found."),0, tr("OK"));
        return MENU_DISCLIST;
    }

    enum {
        FADE,
        LEFT,
        RIGHT
    };

    if (IsNetworkInit())
        ResumeNetworkWait();

    int slidedirection = FADE;

    /*** Sound Variables ***/
    GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume);
	// because destroy GuiSound must wait while sound playing is finished, we use a global sound
	if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);
	//	GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);
    GuiSound btnClick1(button_click_pcm, button_click_pcm_size, Settings.sfxvolume);

    /*** Image Variables ***/
    char imgPath[150];
    snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path);
    GuiImageData btnOutline(imgPath, button_dialogue_box_png);

    snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path);
    GuiImageData bgData(imgPath, settings_background_png);

    snprintf(imgPath, sizeof(imgPath), "%ssettings_title.png", CFG.theme_path);
    GuiImageData MainButtonImgData(imgPath, settings_title_png);

    snprintf(imgPath, sizeof(imgPath), "%ssettings_title_over.png", CFG.theme_path);
    GuiImageData MainButtonImgOverData(imgPath, settings_title_over_png);

    snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_left.png", CFG.theme_path);
    GuiImageData arrow_left(imgPath, startgame_arrow_left_png);

    snprintf(imgPath, sizeof(imgPath), "%sstartgame_arrow_right.png", CFG.theme_path);
    GuiImageData arrow_right(imgPath, startgame_arrow_right_png);

    snprintf(imgPath, sizeof(imgPath), "%sWifi_btn.png", CFG.theme_path);
    GuiImageData wifiImgData(imgPath, Wifi_btn_png);

    snprintf(imgPath, sizeof(imgPath), "%sChannel_btn.png", CFG.theme_path);
    GuiImageData channelImgData(imgPath, Channel_btn_png);


    GuiImage background(&bgData);

    /*** Trigger Variables ***/
    GuiTrigger trigA;
    trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);
    GuiTrigger trigHome;
    trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0);
    GuiTrigger trigB;
    trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B);
    GuiTrigger trigL;
    trigL.SetButtonOnlyTrigger(-1, WPAD_BUTTON_LEFT | WPAD_CLASSIC_BUTTON_LEFT, PAD_BUTTON_LEFT);
    GuiTrigger trigR;
    trigR.SetButtonOnlyTrigger(-1, WPAD_BUTTON_RIGHT | WPAD_CLASSIC_BUTTON_RIGHT, PAD_BUTTON_RIGHT);
    GuiTrigger trigMinus;
    trigMinus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_MINUS | WPAD_CLASSIC_BUTTON_MINUS, 0);
    GuiTrigger trigPlus;
    trigPlus.SetButtonOnlyTrigger(-1, WPAD_BUTTON_PLUS | WPAD_CLASSIC_BUTTON_PLUS, 0);

    GuiText titleTxt(tr("Homebrew Launcher"), 28, (GXColor) {0, 0, 0, 255});
    titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    titleTxt.SetPosition(0,40);

    GuiImageData *IconData[4];
    GuiImage *IconImg[4];

    for (int i = 0; i < 4; i++) {
        IconData[i] = NULL;
        IconImg[i] = NULL;
    }
    /*** Buttons ***/

    GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext);
    backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30);
    GuiImage backBtnImg(&btnOutline);
    if (Settings.wsprompt == yes) {
        backBtnTxt.SetWidescreen(CFG.widescreen);
        backBtnImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton backBtn(&backBtnImg,&backBtnImg, 2, 3, -180, 400, &trigA, &btnSoundOver, btnClick2,1);
    backBtn.SetLabel(&backBtnTxt);
    backBtn.SetTrigger(&trigB);

    GuiButton h**o(1,1);
    h**o.SetTrigger(&trigHome);

    GuiImage GoLeftImg(&arrow_left);
    GuiButton GoLeftBtn(GoLeftImg.GetWidth(), GoLeftImg.GetHeight());
    GoLeftBtn.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    GoLeftBtn.SetPosition(25, -25);
    GoLeftBtn.SetImage(&GoLeftImg);
    GoLeftBtn.SetSoundOver(&btnSoundOver);
    GoLeftBtn.SetSoundClick(btnClick2);
    GoLeftBtn.SetEffectGrow();
    GoLeftBtn.SetTrigger(&trigA);
    GoLeftBtn.SetTrigger(&trigL);
    GoLeftBtn.SetTrigger(&trigMinus);

    GuiImage GoRightImg(&arrow_right);
    GuiButton GoRightBtn(GoRightImg.GetWidth(), GoRightImg.GetHeight());
    GoRightBtn.SetAlignment(ALIGN_RIGHT, ALIGN_MIDDLE);
    GoRightBtn.SetPosition(-25, -25);
    GoRightBtn.SetImage(&GoRightImg);
    GoRightBtn.SetSoundOver(&btnSoundOver);
    GoRightBtn.SetSoundClick(btnClick2);
    GoRightBtn.SetEffectGrow();
    GoRightBtn.SetTrigger(&trigA);
    GoRightBtn.SetTrigger(&trigR);
    GoRightBtn.SetTrigger(&trigPlus);

    char MainButtonText[50];
    snprintf(MainButtonText, sizeof(MainButtonText), "%s", " ");

    GuiImage MainButton1Img(&MainButtonImgData);
    GuiImage MainButton1ImgOver(&MainButtonImgOverData);
    GuiText MainButton1Txt(MainButtonText, 18, (GXColor) {0, 0, 0, 255});
    MainButton1Txt.SetMaxWidth(MainButton1Img.GetWidth()-150, GuiText::DOTTED);
    MainButton1Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton1Txt.SetPosition(148, -12);
    GuiText MainButton1DescTxt(MainButtonText, 18, (GXColor) {0, 0, 0, 255});
    MainButton1DescTxt.SetMaxWidth(MainButton1Img.GetWidth()-150, GuiText::DOTTED);
    MainButton1DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton1DescTxt.SetPosition(148, 15);
    GuiText MainButton1DescOverTxt(MainButtonText, 18, (GXColor) { 0, 0, 0, 255});
    MainButton1DescOverTxt.SetMaxWidth(MainButton1Img.GetWidth()-150, GuiText::SCROLL);
    MainButton1DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton1DescOverTxt.SetPosition(148, 15);
    GuiButton MainButton1(MainButton1Img.GetWidth(), MainButton1Img.GetHeight());
    MainButton1.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    MainButton1.SetPosition(0, 90);
    MainButton1.SetImage(&MainButton1Img);
    MainButton1.SetImageOver(&MainButton1ImgOver);
    MainButton1.SetLabel(&MainButton1Txt);
    MainButton1.SetLabel(&MainButton1DescTxt,1);
    MainButton1.SetLabelOver(&MainButton1DescOverTxt,1);
    MainButton1.SetSoundOver(&btnSoundOver);
    MainButton1.SetSoundClick(&btnClick1);
    MainButton1.SetEffectGrow();
    MainButton1.SetTrigger(&trigA);

    GuiImage MainButton2Img(&MainButtonImgData);
    GuiImage MainButton2ImgOver(&MainButtonImgOverData);
    GuiText MainButton2Txt(MainButtonText, 18, (GXColor) {0, 0, 0, 255 });
    MainButton2Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton2Txt.SetPosition(148, -12);
    MainButton2Txt.SetMaxWidth(MainButton2Img.GetWidth()-150, GuiText::DOTTED);
    GuiText MainButton2DescTxt(MainButtonText, 18, (GXColor) { 0, 0, 0, 255});
    MainButton2DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton2DescTxt.SetPosition(148, 15);
    MainButton2DescTxt.SetMaxWidth(MainButton2Img.GetWidth()-150, GuiText::DOTTED);
    GuiText MainButton2DescOverTxt(MainButtonText, 18, (GXColor) {0, 0, 0, 255});
    MainButton2DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton2DescOverTxt.SetPosition(148, 15);
    MainButton2DescOverTxt.SetMaxWidth(MainButton2Img.GetWidth()-150, GuiText::SCROLL);
    GuiButton MainButton2(MainButton2Img.GetWidth(), MainButton2Img.GetHeight());
    MainButton2.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    MainButton2.SetPosition(0, 160);
    MainButton2.SetImage(&MainButton2Img);
    MainButton2.SetImageOver(&MainButton2ImgOver);
    MainButton2.SetLabel(&MainButton2Txt);
    MainButton2.SetLabel(&MainButton2DescTxt,1);
    MainButton2.SetLabelOver(&MainButton2DescOverTxt,1);
    MainButton2.SetSoundOver(&btnSoundOver);
    MainButton2.SetSoundClick(&btnClick1);
    MainButton2.SetEffectGrow();
    MainButton2.SetTrigger(&trigA);

    GuiImage MainButton3Img(&MainButtonImgData);
    GuiImage MainButton3ImgOver(&MainButtonImgOverData);
    GuiText MainButton3Txt(MainButtonText, 18, (GXColor) {0, 0, 0, 255});
    MainButton3Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton3Txt.SetPosition(148, -12);
    MainButton3Txt.SetMaxWidth(MainButton3Img.GetWidth()-150, GuiText::DOTTED);
    GuiText MainButton3DescTxt(MainButtonText, 18, (GXColor) { 0, 0, 0, 255});
    MainButton3DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton3DescTxt.SetPosition(148, 15);
    MainButton3DescTxt.SetMaxWidth(MainButton3Img.GetWidth()-150, GuiText::DOTTED);
    GuiText MainButton3DescOverTxt(MainButtonText, 18, (GXColor) {0, 0, 0, 255 });
    MainButton3DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton3DescOverTxt.SetPosition(148, 15);
    MainButton3DescOverTxt.SetMaxWidth(MainButton3Img.GetWidth()-150, GuiText::SCROLL);
    GuiButton MainButton3(MainButton3Img.GetWidth(), MainButton3Img.GetHeight());
    MainButton3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    MainButton3.SetPosition(0, 230);
    MainButton3.SetImage(&MainButton3Img);
    MainButton3.SetImageOver(&MainButton3ImgOver);
    MainButton3.SetLabel(&MainButton3Txt);
    MainButton3.SetLabel(&MainButton3DescTxt,1);
    MainButton3.SetLabelOver(&MainButton3DescOverTxt,1);
    MainButton3.SetSoundOver(&btnSoundOver);
    MainButton3.SetSoundClick(&btnClick1);
    MainButton3.SetEffectGrow();
    MainButton3.SetTrigger(&trigA);

    GuiImage MainButton4Img(&MainButtonImgData);
    GuiImage MainButton4ImgOver(&MainButtonImgOverData);
    GuiText MainButton4Txt(MainButtonText, 18, (GXColor) {0, 0, 0, 255} );
    MainButton4Txt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton4Txt.SetPosition(148, -12);
    MainButton4Txt.SetMaxWidth(MainButton4Img.GetWidth()-150, GuiText::DOTTED);
    GuiText MainButton4DescTxt(MainButtonText, 18, (GXColor) {0, 0, 0, 255});
    MainButton4DescTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton4DescTxt.SetPosition(148, 15);
    MainButton4DescTxt.SetMaxWidth(MainButton4Img.GetWidth()-150, GuiText::DOTTED);
    GuiText MainButton4DescOverTxt(MainButtonText, 18, (GXColor) { 0, 0, 0, 255});
    MainButton4DescOverTxt.SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
    MainButton4DescOverTxt.SetPosition(148, 15);
    MainButton4DescOverTxt.SetMaxWidth(MainButton4Img.GetWidth()-150, GuiText::SCROLL);
    GuiButton MainButton4(MainButton4Img.GetWidth(), MainButton4Img.GetHeight());
    MainButton4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    MainButton4.SetPosition(0, 300);
    MainButton4.SetImage(&MainButton4Img);
    MainButton4.SetImageOver(&MainButton4ImgOver);
    MainButton4.SetLabel(&MainButton4Txt);
    MainButton4.SetLabel(&MainButton4DescTxt,1);
    MainButton4.SetLabelOver(&MainButton4DescOverTxt,1);
    MainButton4.SetSoundOver(&btnSoundOver);
    MainButton4.SetSoundClick(&btnClick1);
    MainButton4.SetEffectGrow();
    MainButton4.SetTrigger(&trigA);

    GuiImage wifiImg(&wifiImgData);
    if (Settings.wsprompt == yes) {
        wifiImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton wifiBtn(wifiImg.GetWidth(), wifiImg.GetHeight());
    wifiBtn.SetImage(&wifiImg);
    wifiBtn.SetPosition(500, 400);
    wifiBtn.SetSoundOver(&btnSoundOver);
    wifiBtn.SetSoundClick(&btnClick1);
    wifiBtn.SetEffectGrow();
    wifiBtn.SetAlpha(80);
    wifiBtn.SetTrigger(&trigA);

    GuiImage channelBtnImg(&channelImgData);
    channelBtnImg.SetWidescreen(CFG.widescreen);
    GuiButton channelBtn(channelBtnImg.GetWidth(), channelBtnImg.GetHeight());
    channelBtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
    channelBtn.SetPosition(440, 400);
    channelBtn.SetImage(&channelBtnImg);
    channelBtn.SetSoundOver(&btnSoundOver);
    channelBtn.SetSoundClick(btnClick2);
    channelBtn.SetEffectGrow();
    channelBtn.SetTrigger(&trigA);

    GuiTooltip * titleTT = NULL;


    GuiWindow w(screenwidth, screenheight);

    /*** XML Variables ***/
    HomebrewXML XMLInfo[4];

    int pageToDisplay = 1;
    const int pages = roundup(filecount/4.0f);
    bool wifi_btn_loaded=false;

    while (menu == MENU_NONE) { //set pageToDisplay to 0 to quit
        VIDEO_WaitVSync ();

        menu = MENU_NONE;
        bool changed = false;
        int fileoffset = pageToDisplay*4-4;

        /** Standard procedure made in all pages **/
        MainButton1.StopEffect();
        MainButton2.StopEffect();
        MainButton3.StopEffect();
        MainButton4.StopEffect();

        if (slidedirection == RIGHT) {
            MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60);
            MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60);
            MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60);
            MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_OUT, 60);
            while (MainButton1.GetEffect()>0) usleep(50);
        } else if (slidedirection == LEFT) {
            MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60);
            MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60);
            MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60);
            MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_OUT, 60);
            while (MainButton1.GetEffect()>0) usleep(50);
        }

        HaltGui();

        mainWindow->RemoveAll();

        /** Set new icons **/
        for (int i = 0; i < 4; i++) {
            if (IconData[i] != NULL) {
                delete IconData[i];
                IconData[i] = NULL;
            }
            if (IconImg[i] != NULL) {
                delete IconImg[i];
                IconImg[i] = NULL;
            }
            if (fileoffset+i < (int) filecount) {
                char iconpath[200];
                snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset+i));
                IconData[i] = new GuiImageData(iconpath, 0);
                if (IconData[i]->GetImage()) {
                    IconImg[i] = new GuiImage(IconData[i]);
                    IconImg[i]->SetAlignment(ALIGN_LEFT, ALIGN_MIDDLE);
                    IconImg[i]->SetPosition(12, 0);
                    IconImg[i]->SetScale(0.95);
                }
            }
        }

        if (IconImg[0] != 0)
            MainButton1.SetIcon(IconImg[0]);
        else
            MainButton1.SetIcon(NULL);
        if (IconImg[1] != 0)
            MainButton2.SetIcon(IconImg[1]);
        else
            MainButton2.SetIcon(NULL);
        if (IconImg[2] != 0)
            MainButton3.SetIcon(IconImg[2]);
        else
            MainButton3.SetIcon(NULL);
        if (IconImg[3] != 0)
            MainButton4.SetIcon(IconImg[3]);
        else
            MainButton4.SetIcon(NULL);

        mainWindow->Append(&w);
        w.RemoveAll();
        w.Append(&background);
        w.Append(&titleTxt);
        w.Append(&backBtn);
        w.Append(&h**o);
        w.Append(&wifiBtn);
        w.Append(&channelBtn);
        w.Append(&GoRightBtn);
        w.Append(&GoLeftBtn);

        if (pageToDisplay == pages) {
            int buttonsleft = filecount-(pages-1)*4;
            char * shortpath = NULL;
            char temp[200];

            if (buttonsleft > 0) {
                snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset));
                if (XMLInfo[0].LoadHomebrewXMLData(temp) > 0) {
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[0].GetName());
                    MainButton1Txt.SetText(MainButtonText);
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[0].GetShortDescription());
                    MainButton1DescTxt.SetText(MainButtonText);
                    MainButton1DescOverTxt.SetText(MainButtonText);
                } else {
                    snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset)), "%s", HomebrewFiles.GetFilepath(fileoffset));
                    shortpath = strrchr(temp, '/');
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset));
                    XMLInfo[0].SetName(MainButtonText);
                    MainButton1Txt.SetText(MainButtonText);
                    snprintf(MainButtonText, sizeof(MainButtonText), " ");
                    MainButton1DescTxt.SetText(MainButtonText);
                    MainButton1DescOverTxt.SetText(MainButtonText);
                }
                w.Append(&MainButton1);
            }
            if (buttonsleft > 1) {
                snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+1));
                if (XMLInfo[1].LoadHomebrewXMLData(temp) > 0) {
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[1].GetName());
                    MainButton2Txt.SetText(MainButtonText);
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[1].GetShortDescription());
                    MainButton2DescTxt.SetText(MainButtonText);
                    MainButton2DescOverTxt.SetText(MainButtonText);
                } else {
                    snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset+1)), "%s", HomebrewFiles.GetFilepath(fileoffset+1));
                    shortpath = strrchr(temp, '/');
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset+1));
                    XMLInfo[1].SetName(MainButtonText);
                    MainButton2Txt.SetText(MainButtonText);
                    snprintf(MainButtonText, sizeof(MainButtonText), " ");
                    MainButton2DescTxt.SetText(MainButtonText);
                    MainButton2DescOverTxt.SetText(MainButtonText);
                }
                w.Append(&MainButton2);
            }
            if (buttonsleft > 2) {
                snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+2));
                if (XMLInfo[3].LoadHomebrewXMLData(temp) > 0) {
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetName());
                    MainButton3Txt.SetText(MainButtonText);
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetShortDescription());
                    MainButton3DescTxt.SetText(MainButtonText);
                    MainButton3DescOverTxt.SetText(MainButtonText);
                } else {
                    snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset+2)), "%s", HomebrewFiles.GetFilepath(fileoffset+2));
                    shortpath = strrchr(temp, '/');
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset+2));
                    XMLInfo[2].SetName(MainButtonText);
                    MainButton3Txt.SetText(MainButtonText);
                    snprintf(MainButtonText, sizeof(MainButtonText), " ");
                    MainButton3DescTxt.SetText(MainButtonText);
                    MainButton3DescOverTxt.SetText(MainButtonText);
                }
                w.Append(&MainButton3);
            }
            if (buttonsleft > 3) {
                snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+3));
                if (XMLInfo[3].LoadHomebrewXMLData(temp) > 0) {
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetName());
                    MainButton4Txt.SetText(MainButtonText);
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetShortDescription());
                    MainButton4DescTxt.SetText(MainButtonText);
                    MainButton4DescOverTxt.SetText(MainButtonText);
                } else {
                    snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset+3)), "%s", HomebrewFiles.GetFilepath(fileoffset+3));
                    shortpath = strrchr(temp, '/');
                    snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset+3));
                    XMLInfo[3].SetName(MainButtonText);
                    MainButton4Txt.SetText(MainButtonText);
                    snprintf(MainButtonText, sizeof(MainButtonText), " ");
                    MainButton4DescTxt.SetText(MainButtonText);
                    MainButton4DescOverTxt.SetText(MainButtonText);
                }
                w.Append(&MainButton4);
            }
        } else {
            char temp[200];
            char *shortpath = NULL;

            snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset));
            if (XMLInfo[0].LoadHomebrewXMLData(temp) > 0) {
                snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[0].GetName());
                MainButton1Txt.SetText(MainButtonText);
                snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[0].GetShortDescription());
                MainButton1DescTxt.SetText(MainButtonText);
                MainButton1DescOverTxt.SetText(MainButtonText);
            } else {
                snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset)), "%s", HomebrewFiles.GetFilepath(fileoffset));
                shortpath = strrchr(temp, '/');
                snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset));
                XMLInfo[0].SetName(MainButtonText);
                MainButton1Txt.SetText(MainButtonText);
                snprintf(MainButtonText, sizeof(MainButtonText), " ");
                MainButton1DescTxt.SetText(MainButtonText);
                MainButton1DescOverTxt.SetText(MainButtonText);
            }

            w.Append(&MainButton1);

            snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+1));
            if (XMLInfo[1].LoadHomebrewXMLData(temp) > 0) {
                snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[1].GetName());
                MainButton2Txt.SetText(MainButtonText);
                snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[1].GetShortDescription());
                MainButton2DescTxt.SetText(MainButtonText);
                MainButton2DescOverTxt.SetText(MainButtonText);
            } else {
                snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset+1)), "%s", HomebrewFiles.GetFilepath(fileoffset+1));
                shortpath = strrchr(temp, '/');
                snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset+1));
                XMLInfo[1].SetName(MainButtonText);
                MainButton2Txt.SetText(MainButtonText);
                snprintf(MainButtonText, sizeof(MainButtonText), " ");
                MainButton2DescTxt.SetText(MainButtonText);
                MainButton2DescOverTxt.SetText(MainButtonText);
            }

            w.Append(&MainButton2);

            snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+2));
            if (XMLInfo[3].LoadHomebrewXMLData(temp) > 0) {
                snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetName());
                MainButton3Txt.SetText(MainButtonText);
                snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetShortDescription());
                MainButton3DescTxt.SetText(MainButtonText);
                MainButton3DescOverTxt.SetText(MainButtonText);
            } else {
                snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset+2)), "%s", HomebrewFiles.GetFilepath(fileoffset+2));
                shortpath = strrchr(temp, '/');
                snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset+2));
                XMLInfo[2].SetName(MainButtonText);
                MainButton3Txt.SetText(MainButtonText);
                snprintf(MainButtonText, sizeof(MainButtonText), " ");
                MainButton3DescTxt.SetText(MainButtonText);
                MainButton3DescOverTxt.SetText(MainButtonText);
            }
            w.Append(&MainButton3);

            snprintf(temp, sizeof(temp), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+3));
            if (XMLInfo[3].LoadHomebrewXMLData(temp) > 0) {
                snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetName());
                MainButton4Txt.SetText(MainButtonText);
                snprintf(MainButtonText, sizeof(MainButtonText), "%s", XMLInfo[3].GetShortDescription());
                MainButton4DescTxt.SetText(MainButtonText);
                MainButton4DescOverTxt.SetText(MainButtonText);
            } else {
                snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset+3)), "%s", HomebrewFiles.GetFilepath(fileoffset+3));
                shortpath = strrchr(temp, '/');
                snprintf(MainButtonText, sizeof(MainButtonText), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset+3));
                XMLInfo[3].SetName(MainButtonText);
                MainButton4Txt.SetText(MainButtonText);
                snprintf(MainButtonText, sizeof(MainButtonText), " ");
                MainButton4DescTxt.SetText(MainButtonText);
                MainButton4DescOverTxt.SetText(MainButtonText);
            }

            w.Append(&MainButton4);
        }

        MainButton1.StopEffect();
        MainButton2.StopEffect();
        MainButton3.StopEffect();
        MainButton4.StopEffect();

        MainButton1.SetEffectGrow();
        MainButton2.SetEffectGrow();
        MainButton3.SetEffectGrow();
        MainButton4.SetEffectGrow();

        if (slidedirection == FADE) {
            MainButton1.SetEffect(EFFECT_FADE, 20);
            MainButton2.SetEffect(EFFECT_FADE, 20);
            MainButton3.SetEffect(EFFECT_FADE, 20);
            MainButton4.SetEffect(EFFECT_FADE, 20);
        } else if (slidedirection == LEFT) {
            MainButton1.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60);
            MainButton2.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60);
            MainButton3.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60);
            MainButton4.SetEffect(EFFECT_SLIDE_LEFT | EFFECT_SLIDE_IN, 60);
        } else if (slidedirection == RIGHT) {
            MainButton1.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60);
            MainButton2.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60);
            MainButton3.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60);
            MainButton4.SetEffect(EFFECT_SLIDE_RIGHT | EFFECT_SLIDE_IN, 60);
        }

        mainWindow->Append(&w);

        ResumeGui();

        while (MainButton1.GetEffect() > 0) usleep(50);

        while (!changed) {
            VIDEO_WaitVSync ();

            if (MainButton1.GetState() == STATE_CLICKED) {
                char temp[200];
                char iconpath[200];
                char metapath[200];
                char * shortpath = NULL;

                //write iconpath
                snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset));

                //write iconpath
                snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset));

                //get filesize
                u64 filesize = HomebrewFiles.GetFilesize(fileoffset);
                //write short filename
                snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset)), "%s", HomebrewFiles.GetFilepath(fileoffset));
                shortpath = strrchr(temp, '/');
                snprintf(temp, sizeof(temp), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset));

                int choice = HBCWindowPrompt(XMLInfo[0].GetName(), XMLInfo[0].GetCoder(), XMLInfo[0].GetVersion(), XMLInfo[0].GetReleasedate(), XMLInfo[0].GetLongDescription(), iconpath, filesize);
                if (choice == 1) {
                    boothomebrew = 1;
                    menu = MENU_EXIT;
                    snprintf(Settings.selected_homebrew, sizeof(Settings.selected_homebrew), "%s%s",  HomebrewFiles.GetFilepath(fileoffset), HomebrewFiles.GetFilename(fileoffset));
                    break;
                }
                MainButton1.ResetState();
            } else if (MainButton2.GetState() == STATE_CLICKED) {
                char temp[200];
                char iconpath[200];
                char metapath[200];
                char * shortpath = NULL;

                //write iconpath
                snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+1));

                //write iconpath
                snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset+1));

                //get filesize
                u64 filesize = HomebrewFiles.GetFilesize(fileoffset+1);
                //write short filename
                snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset+1)), "%s", HomebrewFiles.GetFilepath(fileoffset+1));
                shortpath = strrchr(temp, '/');
                snprintf(temp, sizeof(temp), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset+1));

                int choice = HBCWindowPrompt(XMLInfo[1].GetName(), XMLInfo[1].GetCoder(), XMLInfo[1].GetVersion(), XMLInfo[1].GetReleasedate(), XMLInfo[1].GetLongDescription(), iconpath, filesize);
                if (choice == 1) {
                    boothomebrew = 1;
                    menu = MENU_EXIT;
                    snprintf(Settings.selected_homebrew, sizeof(Settings.selected_homebrew), "%s%s",  HomebrewFiles.GetFilepath(fileoffset+1), HomebrewFiles.GetFilename(fileoffset+1));
                    break;
                }
                MainButton2.ResetState();
            } else if (MainButton3.GetState() == STATE_CLICKED) {
                char temp[200];
                char iconpath[200];
                char metapath[200];
                char * shortpath = NULL;

                //write iconpath
                snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+2));

                //write iconpath
                snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset+2));

                //get filesize
                u64 filesize = HomebrewFiles.GetFilesize(fileoffset+2);
                //write short filename
                snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset+2)), "%s", HomebrewFiles.GetFilepath(fileoffset+2));
                shortpath = strrchr(temp, '/');
                snprintf(temp, sizeof(temp), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset+2));

                int choice = HBCWindowPrompt(XMLInfo[2].GetName(), XMLInfo[2].GetCoder(), XMLInfo[2].GetVersion(), XMLInfo[2].GetReleasedate(), XMLInfo[2].GetLongDescription(), iconpath, filesize);
                if (choice == 1) {
                    boothomebrew = 1;
                    menu = MENU_EXIT;
                    snprintf(Settings.selected_homebrew, sizeof(Settings.selected_homebrew), "%s%s",  HomebrewFiles.GetFilepath(fileoffset+2), HomebrewFiles.GetFilename(fileoffset+2));
                    break;
                }
                MainButton3.ResetState();
            } else if (MainButton4.GetState() == STATE_CLICKED) {
                char temp[200];
                char iconpath[200];
                char metapath[200];
                char * shortpath = NULL;

                //write iconpath
                snprintf(metapath, sizeof(metapath), "%smeta.xml", HomebrewFiles.GetFilepath(fileoffset+3));

                //write iconpath
                snprintf(iconpath, sizeof(iconpath), "%sicon.png", HomebrewFiles.GetFilepath(fileoffset+3));

                //get filesize
                u64 filesize = HomebrewFiles.GetFilesize(fileoffset+3);
                //write short filename
                snprintf(temp, strlen(HomebrewFiles.GetFilepath(fileoffset+3)), "%s", HomebrewFiles.GetFilepath(fileoffset+3));
                shortpath = strrchr(temp, '/');
                snprintf(temp, sizeof(temp), "%s/%s", shortpath, HomebrewFiles.GetFilename(fileoffset+3));

                int choice = HBCWindowPrompt(XMLInfo[3].GetName(), XMLInfo[3].GetCoder(), XMLInfo[3].GetVersion(), XMLInfo[3].GetReleasedate(), XMLInfo[3].GetLongDescription(), iconpath, filesize);
                if (choice == 1) {
                    boothomebrew = 1;
                    menu = MENU_EXIT;
                    snprintf(Settings.selected_homebrew, sizeof(Settings.selected_homebrew), "%s%s",  HomebrewFiles.GetFilepath(fileoffset+3), HomebrewFiles.GetFilename(fileoffset+3));
                    break;
                }
                MainButton4.ResetState();
            }

            else if (shutdown == 1)
                Sys_Shutdown();
            else if (reset == 1)
                Sys_Reboot();

            else if (backBtn.GetState() == STATE_CLICKED) {
                menu = MENU_DISCLIST;
                changed = true;
            }

            else if (GoLeftBtn.GetState() == STATE_CLICKED) {
                pageToDisplay--;
                /** Change direction of the flying buttons **/
                if (pageToDisplay < 1)
                    pageToDisplay = pages;
                slidedirection = LEFT;
                changed = true;
                GoLeftBtn.ResetState();
            }

            else if (GoRightBtn.GetState() == STATE_CLICKED) {
                pageToDisplay++;
                /** Change direction of the flying buttons **/
                if (pageToDisplay > pages)
                    pageToDisplay = 1;
                slidedirection = RIGHT;
                changed = true;
                GoRightBtn.ResetState();
            }

            else if (wifiBtn.GetState() == STATE_CLICKED) {

                ResumeNetworkWait();
                wifiBtn.ResetState();
            }

            else if (h**o.GetState() == STATE_CLICKED) {
                cfg_save_global();
                bgMusic->Pause();
                choice = WindowExitPrompt();
                bgMusic->Resume();

                if (choice == 3) {
                    Sys_LoadMenu(); // Back to System Menu
                } else if (choice == 2) {
                    Sys_BackToLoader();
                } else {
                    h**o.ResetState();
                }
            }

            else if (infilesize > 0) {
                char filesizetxt[50];
                char temp[50];

                if (infilesize < MB_SIZE)
                    snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fKB"), infilesize/KB_SIZE);
                else
                    snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fMB"), infilesize/MB_SIZE);

                snprintf(temp, sizeof(temp), tr("Load file from: %s ?"), GetIncommingIP());

                int choice = WindowPrompt(filesizetxt, temp, tr("OK"), tr("Cancel"));

                if (choice == 1) {

                    int res = AllocHomebrewMemory(infilesize);

                    if (res < 0) {
                        CloseConnection();
                        WindowPrompt(tr("Not enough free memory."), 0, tr("OK"));
                    } else {
                        u32 read = 0;
                        u8 *temp = NULL;
                        int len = NETWORKBLOCKSIZE;
                        temp = (u8 *) malloc(infilesize);

						bool error = false;
						u8 *ptr = temp;
                        while (read < infilesize) {

                            ShowProgress(tr("Receiving file from:"), GetIncommingIP(), NULL, read, infilesize, true);

                            if (infilesize - read < (u32) len)
                                len = infilesize-read;
                            else
                                len = NETWORKBLOCKSIZE;

                            int result = network_read(ptr, len);

                            if (result < 0) {
                                WindowPrompt(tr("Error while transfering data."), 0, tr("OK"));
								error = true;
                                break;
                            }
                            if (!result) {
                                break;
							}

							ptr += result;

                            read += result;
                        }
						
						char filename[101];
						if (!error) {
						
							network_read((u8*) &filename, 100);
							
							// Do we need to unzip this thing?
							if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) {

								// We need to unzip...
								if (temp[0] == 'P' && temp[1] == 'K' && temp[2] == 0x03 && temp[3] == 0x04) {
									// It's a zip file, unzip to the apps directory
									
									// Zip archive, ask for permission to install the zip
									char zippath[255];
									sprintf((char *) &zippath, "%s%s", Settings.homebrewapps_path, filename);
									
									FILE *fp = fopen(zippath, "wb");
									if (fp != NULL)
									{
										fwrite(temp, 1, infilesize, fp);
										fclose(fp);
										
										// Now unzip the zip file...
										unzFile uf = unzOpen(zippath);
										if (uf==NULL) {
											error = true;
										} else {
											extractZip(uf,0,1,0, Settings.homebrewapps_path);
											unzCloseCurrentFile(uf);
											
											remove(zippath);
											
											// Reload this menu here...
											menu = MENU_HOMEBREWBROWSE;
											break;
										}
									} else {
										error = true;
									}
								} else if (uncfilesize != 0) { // if uncfilesize == 0, it's not compressed
									// It's compressed, uncompress
									u8 *unc = (u8 *) malloc(uncfilesize);
									uLongf f = uncfilesize;
									error = uncompress(unc, &f, temp, infilesize) != Z_OK;
									uncfilesize = f;
									
									free(temp);
									temp = unc;
								}
							}
							
							if (!error && strstr(filename,".zip") == NULL) {
								innetbuffer = temp;
							}
						}
						
                        ProgressStop();

                        if (error || read != infilesize) {
                            WindowPrompt(tr("Error:"), tr("No data could be read."), tr("OK"));
                            FreeHomebrewBuffer();
                        } else {
                            if (strstr(filename,".dol") || strstr(filename,".DOL")
                                || strstr(filename,".elf") || strstr(filename,".ELF")) {
                                boothomebrew = 2;
                                menu = MENU_EXIT;
                                CloseConnection();
                                break;
                            } else if (strstr(filename,".zip")) {
                                WindowPrompt(tr("Success:"), tr("Uploaded ZIP file installed to homebrew directory."), tr("OK"));
								CloseConnection();
                            } else {
                                FreeHomebrewBuffer();
                                WindowPrompt(tr("ERROR:"), tr("Not a DOL/ELF file."), tr("OK"));
							}
                        }
                    }
                }
                CloseConnection();
                ResumeNetworkWait();
            }

            else if (channelBtn.GetState() == STATE_CLICKED) {
                w.SetState(STATE_DISABLED);
                //10001 are the channels that are installed as channels, not including shop channel/mii channel etc
                u32 num = 0x00010001;
                TitleBrowser(num);
                //if they didn't boot a channel reset this window
                w.SetState(STATE_DEFAULT);
                channelBtn.ResetState();


            }

            if (IsNetworkInit()) {
                if (!wifi_btn_loaded) {
                    wifiBtn.SetAlpha(255);

                    titleTT = new GuiTooltip(GetNetworkIP());
                    titleTT->SetAlpha(THEME.tooltipAlpha);
                    wifiBtn.SetToolTip(titleTT,0,-50,0,5);
                    wifi_btn_loaded=true;
                }
            }
        }
    }

    w.SetEffect(EFFECT_FADE, -20);
    while (w.GetEffect()>0) usleep(50);

    HaltGui();

    for (int i = 0; i < 4; i++) {
        if (IconData[i] != NULL) {
            delete IconData[i];
            IconData[i] = NULL;
        }
        if (IconImg[i] != NULL) {
            delete IconImg[i];
            IconImg[i] = NULL;
        }
    }

    delete titleTT;
    titleTT = NULL;

    if (IsNetworkInit())
        HaltNetworkThread();

    mainWindow->RemoveAll();
    mainWindow->Append(bgImg);

    ResumeGui();

    return menu;
}
Exemplo n.º 8
0
/****************************************************************************
 * MenuLanguageSelect
 ***************************************************************************/
int MenuLanguageSelect() {
    int cnt = 0;
    int ret = 0, choice = 0;
    int scrollon;
    int returnhere = 0;

    GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume);
	// because destroy GuiSound must wait while sound playing is finished, we use a global sound
	if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);
	//	GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);

    char imgPath[100];

    snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path);
    GuiImageData btnOutline(imgPath, button_dialogue_box_png);
    snprintf(imgPath, sizeof(imgPath), "%ssettings_background.png", CFG.theme_path);
    GuiImageData settingsbg(imgPath, settings_background_png);

    GuiTrigger trigA;
    trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);
    GuiTrigger trigB;
    trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B);

    char fullpath[100];
    int countfiles = GetAllDirFiles(Settings.languagefiles_path);

    if (!strcmp("", Settings.languagefiles_path)) {
        sprintf(fullpath, "%s", tr("Standard"));
    } else {
        sprintf(fullpath, "%s", Settings.languagefiles_path);
    }

    GuiText titleTxt(fullpath, 24, (GXColor) {0, 0, 0, 255});
    titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);
    titleTxt.SetPosition(0,0);
    GuiButton pathBtn(300, 50);
    pathBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    pathBtn.SetPosition(0,28);
    pathBtn.SetLabel(&titleTxt);
    pathBtn.SetSoundOver(&btnSoundOver);
    pathBtn.SetSoundClick(btnClick2);
    pathBtn.SetTrigger(&trigA);
    pathBtn.SetEffectGrow();

    GuiImage oggmenubackground(&settingsbg);
    oggmenubackground.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
    oggmenubackground.SetPosition(0, 0);

    GuiText backBtnTxt(tr("Back") , 22, THEME.prompttext);
    backBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30);
    GuiImage backBtnImg(&btnOutline);
    if (Settings.wsprompt == yes) {
        backBtnTxt.SetWidescreen(CFG.widescreen);
        backBtnImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton backBtn(btnOutline.GetWidth(), btnOutline.GetHeight());
    backBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    backBtn.SetPosition(-190, 400);
    backBtn.SetLabel(&backBtnTxt);
    backBtn.SetImage(&backBtnImg);
    backBtn.SetSoundOver(&btnSoundOver);
    backBtn.SetSoundClick(btnClick2);
    backBtn.SetTrigger(&trigA);
    backBtn.SetTrigger(&trigB);
    backBtn.SetEffectGrow();

    GuiText defaultBtnTxt(tr("Default") , 22, THEME.prompttext);
    defaultBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30);
    GuiImage defaultBtnImg(&btnOutline);
    if (Settings.wsprompt == yes) {
        defaultBtnTxt.SetWidescreen(CFG.widescreen);
        defaultBtnImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton defaultBtn(btnOutline.GetWidth(), btnOutline.GetHeight());
    defaultBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    defaultBtn.SetPosition(190, 400);
    defaultBtn.SetLabel(&defaultBtnTxt);
    defaultBtn.SetImage(&defaultBtnImg);
    defaultBtn.SetSoundOver(&btnSoundOver);
    defaultBtn.SetSoundClick(btnClick2);
    defaultBtn.SetTrigger(&trigA);
    defaultBtn.SetEffectGrow();

    GuiText updateBtnTxt(tr("Update Files") , 22, THEME.prompttext);
    updateBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30);
    GuiImage updateBtnImg(&btnOutline);
    if (Settings.wsprompt == yes) {
        updateBtnTxt.SetWidescreen(CFG.widescreen);
        updateBtnImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton updateBtn(btnOutline.GetWidth(), btnOutline.GetHeight());
    updateBtn.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    updateBtn.SetPosition(0, 400);
    updateBtn.SetLabel(&updateBtnTxt);
    updateBtn.SetImage(&updateBtnImg);
    updateBtn.SetSoundOver(&btnSoundOver);
    updateBtn.SetSoundClick(btnClick2);
    updateBtn.SetTrigger(&trigA);
    updateBtn.SetEffectGrow();

    customOptionList options2(countfiles);

    for (cnt = 0; cnt < countfiles; cnt++) {
        char filename[64];
        strlcpy(filename, GetFileName(cnt), sizeof(filename));
        char *dot = strchr(filename, '.');
        if (dot) *dot='\0';
        options2.SetName(cnt, "%s", filename);
        options2.SetValue(cnt, NULL);

    }

    if (cnt < 9) {
        scrollon = 0;
    } else {
        scrollon = 1;
    }

    GuiCustomOptionBrowser optionBrowser4(396, 280, &options2, CFG.theme_path, "bg_options_settings.png", bg_options_settings_png, scrollon, 10);
    optionBrowser4.SetPosition(0, 90);
    optionBrowser4.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);

    HaltGui();
    GuiWindow w(screenwidth, screenheight);
    w.Append(&oggmenubackground);
    w.Append(&pathBtn);
    w.Append(&backBtn);
    w.Append(&defaultBtn);
    w.Append(&updateBtn);
    w.Append(&optionBrowser4);
    mainWindow->Append(&w);

    w.SetEffect(EFFECT_FADE, 20);
    ResumeGui();

    while (w.GetEffect()>0) usleep(50);

    while (!returnhere) {

        if (shutdown == 1)
            Sys_Shutdown();
        else if (reset == 1)
            Sys_Reboot();

        else if (backBtn.GetState() == STATE_CLICKED) {

            backBtn.ResetState();
            break;
        }

        else if (defaultBtn.GetState() == STATE_CLICKED) {
            choice = WindowPrompt(tr("Loading standard language."),0,tr("OK"), tr("Cancel"));
            if (choice == 1) {
                sprintf(Settings.language_path, "notset");
                cfg_save_global();
                gettextCleanUp();
				HaltGui();
                CFG_Load();
				ResumeGui();
                returnhere = 2;
            }
            defaultBtn.ResetState();
			//optionBrowser4.SetFocus(1); // commented out to prevent crash
        }

        else if (updateBtn.GetState() == STATE_CLICKED) {
            choice = WindowPrompt(tr("Update all Language Files"),tr("Do you wish to update/download all language files?"),tr("OK"), tr("Cancel"));
            if (choice == 1) {

                bool network = true;
                if (!IsNetworkInit()) {
                    network = NetworkInitPrompt();
                }

                if (network) {
                    const char URL[60] = "http://usbloader-gui.googlecode.com/svn/trunk/Languages/";
                    char fullURL[300];
                    FILE *pfile;

                    URL_List LinkList(URL);
                    int listsize = LinkList.GetURLCount();

                    subfoldercreate(Settings.languagefiles_path);

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

                        ShowProgress(tr("Updating Language Files:"), 0, LinkList.GetURL(i), i, listsize-1);

                        if (strcasecmp(".lang", strrchr(LinkList.GetURL(i), '.')) == 0) {

                            snprintf(fullURL, sizeof(fullURL), "%s%s", URL, LinkList.GetURL(i));

                            struct block file = downloadfile(fullURL);

                            if (file.data && file.size) {
                                char filepath[300];

                                snprintf(filepath, sizeof(filepath), "%s%s", Settings.languagefiles_path, LinkList.GetURL(i));
                                pfile = fopen(filepath, "wb");
                                fwrite(file.data, 1, file.size, pfile);
                                fclose(pfile);

                            }

                            free(file.data);
                        }
                    }
                    ProgressStop();
                    returnhere = 1;
                    break;
                }
            }
			updateBtn.ResetState();
			//optionBrowser4.SetFocus(1); // commented out to prevent crash
        }

        else if (pathBtn.GetState() == STATE_CLICKED) {
            w.Remove(&optionBrowser4);
            w.Remove(&backBtn);
            w.Remove(&pathBtn);
            w.Remove(&defaultBtn);
            char entered[43] = "";
            strlcpy(entered, Settings.languagefiles_path, sizeof(entered));
            int result = OnScreenKeyboard(entered,43,0);
            w.Append(&optionBrowser4);
            w.Append(&pathBtn);
            w.Append(&backBtn);
            w.Append(&defaultBtn);
            if ( result == 1 ) {
                int len = (strlen(entered)-1);
                if (entered[len] !='/')
                    strncat (entered, "/", 1);
                strlcpy(Settings.languagefiles_path, entered, sizeof(Settings.languagefiles_path));
                WindowPrompt(tr("Languagepath changed."),0,tr("OK"));
                if (isInserted(bootDevice)) {
                    cfg_save_global();
                    returnhere = 1;
                    break;
                } else {
                    WindowPrompt(tr("No SD-Card inserted!"), tr("Insert an SD-Card to save."), tr("OK"));
                }
            }
            if (countfiles > 0) {
                optionBrowser4.SetFocus(1);
            }
            pathBtn.ResetState();
        }

        ret = optionBrowser4.GetClickedOption();

        if (ret>=0) {
            choice = WindowPrompt(tr("Do you want to change language?"), 0, tr("Yes"), tr("Cancel"));
            if (choice == 1) {
                if (isInserted(bootDevice)) {
                    snprintf(Settings.language_path, sizeof(Settings.language_path), "%s%s", Settings.languagefiles_path, GetFileName(ret));
                    cfg_save_global();
                    if (!checkfile(Settings.language_path)) {
                        sprintf(Settings.language_path, tr("not set"));
                        WindowPrompt(tr("File not found."),tr("Loading standard language."),tr("OK"));
                    }
                    gettextCleanUp();
					HaltGui();
					CFG_Load();
					ResumeGui();
                    returnhere = 2;
                    break;
                } else {
                    WindowPrompt(tr("No SD-Card inserted!"), tr("Insert an SD-Card to save."), tr("OK"), 0,0,0,-1);
                }
            }
            optionBrowser4.SetFocus(1);
        }

    }

    w.SetEffect(EFFECT_FADE, -20);
    while (w.GetEffect()>0) usleep(50);

    HaltGui();
    mainWindow->Remove(&w);
    ResumeGui();

    return returnhere;
}
Exemplo n.º 9
0
/********************************************************************************
* TitleBrowser- opens a browser with a list of installed Titles
* relies on code from any title deleter.
*********************************************************************************/
int TitleBrowser(u32 type) {

	u32 num_titles;
	u32 titles[100] ATTRIBUTE_ALIGN(32);
	u32 num_sys_titles;
	u32 sys_titles[10] ATTRIBUTE_ALIGN(32);
	s32 ret = -1;
	int numtitle;//to get rid of a stupid compile wrning
	//open the database file
	FILE *f;
	char path[100];

	ISFS_Initialize();

	sprintf(path,"%s/config/database.txt",bootDevice);
	f = fopen(path, "r");

	// Get count of titles of our requested type
	ret = getTitles_TypeCount(type, &num_titles);
	if (ret < 0) {
		//printf("\tError! Can't get count of titles! (ret = %d)\n", ret);
		//exit(1);
	}

	// Get titles of our requested type
	ret = getTitles_Type(type, titles, num_titles);
	if (ret < 0) {
		//printf("\tError! Can't get list of titles! (ret = %d)\n", ret);
		//exit(1);
	}

	// Get count of system titles
	ret = getTitles_TypeCount(0x00010002, &num_sys_titles);
	if (ret < 0) {
		//printf("\tError! Can't get count of titles! (ret = %d)\n", ret);
		//exit(1);
	}

	// Get system titles
	ret = getTitles_Type(0x00010002, sys_titles, num_sys_titles);
	if (ret < 0) {
		//printf("\tError! Can't get list of titles! (ret = %d)\n", ret);
		//exit(1);
	}


	//this array will hold all the names for the titles so we only have to get them one time
	char name[num_titles+num_sys_titles][50];

	customOptionList options3(num_titles+num_sys_titles+1);
	//write the titles on the option browser
	u32 i = 0;



	//first add the good stuff
	while (i < num_titles) {
		//start from the beginning of the file each loop
		if (f)rewind(f);
		//char name[50];
		char text[15];
		strcpy(name[i],"");//make sure name is empty
		u8 found=0;
		//set the title's name, number, ID to text
		sprintf(text, "%s", titleText(type, titles[i]));

		//get name from database cause i dont like the ADT function
		char line[200];
		char tmp[50];
		snprintf(tmp,50," ");
		
		//check if the content.bin is on the SD card for that game
		//if there is content.bin,then the game is on the SDmenu and not the wii
		sprintf(line,"SD:/private/wii/title/%s/content.bin",text);
		if (!checkfile(line))
			{
				if (f) {
					while (fgets(line, sizeof(line), f)) {
						if (line[0]== text[0]&&
								line[1]== text[1]&&
								line[2]== text[2]) {
							int j=0;
							found=1;
							for (j=0;(line[j+4]!='\0' || j<51);j++)

								tmp[j]=line[j+4];
							snprintf(name[i],sizeof(name[i]),"%s",tmp);
							//break;
						}
					}
				}
				if (!found) {
					if (getName00(name[i], TITLE_ID(type, titles[i]),CONF_GetLanguage()*2)>=0)
						found=2;

					if (!found) {
						if (getNameBN(name[i], TITLE_ID(type, titles[i]))>=0)
							found=3;

						if (!found)
							snprintf(name[i],sizeof(name[i]),"Unknown Title (%08x)",titles[i]);
					}
				}

				//set the text to the option browser
				options3.SetName(i, "%s",text);
				options3.SetValue(i, "%s",name[i]);
				//options3.SetValue(i, " (%08x) %s",titles[i],name[i]);//use this line to show the number to call to launch the channel
				//move on to the next title
			}
        i++;
    }

    // now add the crappy system titles
    while (i < num_titles+num_sys_titles) {
        //start from the beginning of the file each loop
        if (f)rewind(f);
        //char name[50];
        char text[15];
        strcpy(name[i],"");//make sure name is empty
        u8 found=0;
        //set the title's name, number, ID to text
        sprintf(text, "%s", titleText(0x00010002, sys_titles[i-num_titles]));

        //get name from database cause i dont like the ADT function
        char line[200];
        char tmp[50];
        snprintf(tmp,50," ");
        //snprintf(name[i],sizeof(name[i]),"Unknown Title");
        if (f) {
            while (fgets(line, sizeof(line), f)) {
                if (line[0]== text[0]&&
                        line[1]== text[1]&&
                        line[2]== text[2]) {
                    int j=0;
                    found=1;
                    for (j=0;(line[j+4]!='\0' || j<51);j++)

                        tmp[j]=line[j+4];
                    snprintf(name[i],sizeof(name[i]),"%s",tmp);
                    break;
                }
            }
        }
        if (!found) {
            if (getName00(name[i], TITLE_ID(0x00010002, sys_titles[i-num_titles]))>=0)
                found=2;

            if (!found) {
                if (getNameBN(name[i], TITLE_ID(0x00010002, sys_titles[i-num_titles]))>=0)
                    found=3;

                if (!found)
                    snprintf(name[i],sizeof(name[i]),"Unknown Title (%08x)",sys_titles[i-num_titles]);
            }
        }

        //set the text to the option browser
        options3.SetName(i, "%s",text);
        options3.SetValue(i, "%s",name[i]);
        //options3.SetValue(i, " (%08x) %s",titles[i],name[i]);//use this line to show the number to call to launch the channel
        //move on to the next title
        i++;
    }
    if (i == num_titles+num_sys_titles) {
        options3.SetName(i, " ");
        options3.SetValue(i, "%s",tr("Wii Settings"));
    }
    //we have all the titles we need so close the database and stop poking around in the wii
    fclose(f);

    //get rid of our footprints in there
    Uninstall_FromTitle(TITLE_ID(1, 0));
    ISFS_Deinitialize();
    bool exit = false;

    if (IsNetworkInit())
        ResumeNetworkWait();

    GuiSound btnSoundOver(button_over_pcm, button_over_pcm_size, Settings.sfxvolume);
	// because destroy GuiSound must wait while sound playing is finished, we use a global sound
	if(!btnClick2) btnClick2=new GuiSound(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);
	//	GuiSound btnClick(button_click2_pcm, button_click2_pcm_size, Settings.sfxvolume);

    char imgPath[100];

    snprintf(imgPath, sizeof(imgPath), "%sbutton_dialogue_box.png", CFG.theme_path);
    GuiImageData btnOutline(imgPath, button_dialogue_box_png);
    snprintf(imgPath, sizeof(imgPath), "%sgamesettings_background.png", CFG.theme_path);
    GuiImageData settingsbg(imgPath, settings_background_png);

    GuiTrigger trigA;
    trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);
    GuiTrigger trigHome;
    trigHome.SetButtonOnlyTrigger(-1, WPAD_BUTTON_HOME | WPAD_CLASSIC_BUTTON_HOME, 0);
    GuiTrigger trigB;
    trigB.SetButtonOnlyTrigger(-1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B);

    GuiText titleTxt(tr("Title Launcher"), 28, (GXColor) {0, 0, 0, 255});
    titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);
    titleTxt.SetPosition(12,40);
    titleTxt.SetMaxWidth(356, GuiText::SCROLL);

    GuiImage settingsbackground(&settingsbg);
    GuiButton settingsbackgroundbtn(settingsbackground.GetWidth(), settingsbackground.GetHeight());
    settingsbackgroundbtn.SetAlignment(ALIGN_LEFT, ALIGN_TOP);
    settingsbackgroundbtn.SetPosition(0, 0);
    settingsbackgroundbtn.SetImage(&settingsbackground);

    GuiText cancelBtnTxt(tr("Back"), 22, THEME.prompttext);
    cancelBtnTxt.SetMaxWidth(btnOutline.GetWidth()-30);
    GuiImage cancelBtnImg(&btnOutline);
    if (Settings.wsprompt == yes) {
        cancelBtnTxt.SetWidescreen(CFG.widescreen);
        cancelBtnImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton cancelBtn(&cancelBtnImg,&cancelBtnImg, 2, 3, 180, 400, &trigA, &btnSoundOver, btnClick2,1);
    cancelBtn.SetScale(0.9);
    cancelBtn.SetLabel(&cancelBtnTxt);
    cancelBtn.SetTrigger(&trigB);

    u8 scrollbaron = 0;
    if (num_titles > 9)
        scrollbaron = 1;

    GuiCustomOptionBrowser optionBrowser3(396, 280, &options3, CFG.theme_path, "bg_options_gamesettings.png", bg_options_settings_png, num_titles+num_sys_titles>9?1:0, 200);
    optionBrowser3.SetPosition(0, 90);
    optionBrowser3.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);

    snprintf(imgPath, sizeof(imgPath), "%sWifi_btn.png", CFG.theme_path);
    GuiImageData wifiImgData(imgPath, Wifi_btn_png);
    GuiImage wifiImg(&wifiImgData);
    if (Settings.wsprompt == yes) {
        wifiImg.SetWidescreen(CFG.widescreen);
    }
    GuiButton wifiBtn(wifiImg.GetWidth(), wifiImg.GetHeight());
    wifiBtn.SetImage(&wifiImg);
    wifiBtn.SetPosition(100, 400);
    wifiBtn.SetEffectGrow();
    wifiBtn.SetAlpha(80);
    wifiBtn.SetTrigger(&trigA);

    GuiTrigger trigZ;
    trigZ.SetButtonOnlyTrigger(-1, WPAD_NUNCHUK_BUTTON_Z | WPAD_CLASSIC_BUTTON_ZL, PAD_TRIGGER_Z);

    GuiButton screenShotBtn(0,0);
    screenShotBtn.SetPosition(0,0);
    screenShotBtn.SetTrigger(&trigZ);

    HaltGui();
    GuiWindow w(screenwidth, screenheight);
    w.Append(&screenShotBtn);
    w.Append(&settingsbackgroundbtn);
    w.Append(&titleTxt);
    w.Append(&cancelBtn);
    w.Append(&wifiBtn);
    w.Append(&optionBrowser3);

    mainWindow->Append(&w);


    int tmp=num_titles+num_sys_titles;
    ResumeGui();
    numtitle=num_titles;
    while (!exit) {
        VIDEO_WaitVSync();

        if (shutdown == 1)
            Sys_Shutdown();
        if (reset == 1)
            Sys_Reboot();

        else if (wifiBtn.GetState() == STATE_CLICKED) {

                ResumeNetworkWait();
                wifiBtn.ResetState();
        }

        if (IsNetworkInit()) {
                wifiBtn.SetAlpha(255);
        }

        ret = optionBrowser3.GetClickedOption();

        if (ret > -1) {//if a click happened

            //char name[50];
            char text[15];
            if (f)rewind(f);
            //strcpy(name,"");//make sure name is empty

            if (ret<numtitle) {
                //set the title's name, number, ID to text
                sprintf(text, "%s", titleText(type, titles[ret]));

                char temp[100];
                //prompt to boot selected title
                snprintf(temp, sizeof(temp), "%s : %s",text,name[ret]);
                int  choice = WindowPrompt(tr("Boot?"), temp, tr("OK"), tr("Cancel"));
                if (choice) {//if they say yes


                    //stop all this stuff before starting the channel

                    CloseXMLDatabase();
                    ExitGUIThreads();
                    ShutdownAudio();
                    StopGX();
                    WII_Initialize();
                    WII_LaunchTitle(TITLE_ID(type,titles[ret]));
                    //this really shouldn't be needed because the title will be booted
                    exit = true;
                    break;
                } else {
                    //if they said no to booting the title
                    ret = -1;
                    optionBrowser3.ResetState();
                }

            } else { //if they clicked a system title
                if (ret == tmp) {
                    CloseXMLDatabase();
                    ExitGUIThreads();
                    ShutdownAudio();
                    StopGX();
                    WII_Initialize();
                    WII_ReturnToSettings();

                } else {
                    //set the title's name, number, ID to text
                    sprintf(text, "%s", titleText(0x00010002, sys_titles[ret-num_titles]));

                    char temp[112];
                    //prompt to boot selected title
					snprintf(temp, sizeof(temp), tr("%s : %s May not boot correctly if your System Menu is not up to date."),text,name[ret]);
                    int  choice = WindowPrompt(tr("Boot?"), temp, tr("OK"), tr("Cancel"));
                    if (choice) {//if they say yes


                        //stop all this stuff before starting the channel

                        CloseXMLDatabase();
                        ExitGUIThreads();
                        ShutdownAudio();
                        StopGX();
                        WII_Initialize();
                        WII_LaunchTitle(TITLE_ID(0x00010002,sys_titles[ret-num_titles]));
                        //this really shouldn't be needed because the title will be booted
                        exit = true;
                        break;
                    } else {
                        //if they said no to booting the title
                        ret = -1;
                        optionBrowser3.ResetState();
                    }
                }
            }
        }

        if(infilesize > 0) {

                char filesizetxt[50];
                char temp[50];
                char filepath[100];
//				u32 read = 0;
				
				//make sure there is a folder for this to be saved in
				struct stat st;
                snprintf(filepath, sizeof(filepath), "%s/wad/", bootDevice);
				if (stat(filepath, &st) != 0) {
						if (subfoldercreate(filepath) != 1) {
							WindowPrompt(tr("Error !"),tr("Can't create directory"),tr("OK"));
						}
					}
				snprintf(filepath, sizeof(filepath), "%s/wad/tmp.tmp", bootDevice);
				

                if (infilesize < MB_SIZE)
                    snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fKB"), infilesize/KB_SIZE);
                else
                    snprintf(filesizetxt, sizeof(filesizetxt), tr("Incoming file %0.2fMB"), infilesize/MB_SIZE);

                snprintf(temp, sizeof(temp), tr("Load file from: %s ?"), GetIncommingIP());

                int choice = WindowPrompt(filesizetxt, temp, tr("OK"), tr("Cancel"));
		gprintf("\nchoice:%d",choice);

		if (choice == 1) {

			u32 read = 0;
			u8 *temp = NULL;
			int len = NETWORKBLOCKSIZE;
			temp = (u8 *) malloc(infilesize);

						bool error = false;
						u8 *ptr = temp;
						gprintf("\nrecieving shit");
			while (read < infilesize) {

			    ShowProgress(tr("Receiving file from:"), GetIncommingIP(), NULL, read, infilesize, true);

			    if (infilesize - read < (u32) len)
				len = infilesize-read;
			    else
				len = NETWORKBLOCKSIZE;

			    int result = network_read(ptr, len);

			    if (result < 0) {
				WindowPrompt(tr("Error while transfering data."), 0, tr("OK"));
				error = true;
				break;
			    }
			    if (!result) {
				gprintf("\n!RESULT");
				break;
							}
			    ptr += result;
			    read += result;
			}
			ProgressStop();

						char filename[101];
						char tmptxt[200];



						//bool installWad=0;
						if (!error) {
						    gprintf("\nno error yet");

							network_read((u8*) &filename, 100);
							gprintf("\nfilename: %s",filename);

							// Do we need to unzip this thing?
							if (wiiloadVersion[0] > 0 || wiiloadVersion[1] > 4) {
							    gprintf("\nusing newer wiiload version");

								if (uncfilesize != 0) { // if uncfilesize == 0, it's not compressed
								    gprintf("\ntrying to uncompress");
									// It's compressed, uncompress
									u8 *unc = (u8 *) malloc(uncfilesize);
									uLongf f = uncfilesize;
									error = uncompress(unc, &f, temp, infilesize) != Z_OK;
									uncfilesize = f;

									free(temp);
									temp = unc;
								}
							}

							if (!error) {
								sprintf(tmptxt,"%s",filename);
								//if we got a wad
								if (strcasestr(tmptxt,".wad")) {
								    FILE *file = fopen(filepath, "wb");
								    fwrite(temp, 1, (uncfilesize>0?uncfilesize:infilesize), file);
								    fclose(file);

								    sprintf(tmptxt,"%s/wad/%s",bootDevice,filename);
								    if (checkfile(tmptxt))remove(tmptxt);
								    rename(filepath, tmptxt);

								    //check and make sure the wad we just saved is the correct size
								    u32 lSize;
								    file = fopen(tmptxt, "rb");

								    // obtain file size:
								    fseek (file , 0 , SEEK_END);
								    lSize = ftell (file);

								    rewind (file);
								    if (lSize==(uncfilesize>0?uncfilesize:infilesize)) {
									gprintf("\nsize is ok");
									int pick = WindowPrompt(tr(" Wad Saved as:"), tmptxt, tr("Install"),tr("Uninstall"),tr("Cancel"));
									//install or uninstall it
									if (pick==1)
										{
											HaltGui();
											w.Remove(&titleTxt);
											w.Remove(&cancelBtn);
											w.Remove(&wifiBtn);
											w.Remove(&optionBrowser3);
											ResumeGui();

											Wad_Install(file);

											HaltGui();
											w.Append(&titleTxt);
											w.Append(&cancelBtn);
											w.Append(&wifiBtn);
											w.Append(&optionBrowser3);
											ResumeGui();

										}
									if (pick==2)Wad_Uninstall(file);
								    }
								    else gprintf("\nBad size");
								    //close that beast, we're done with it
								    fclose (file);

								    //do we want to keep the file in the wad folder
								    if (WindowPrompt(tr("Delete ?"), tmptxt, tr("Delete"),tr("Keep"))!=0)
									remove(tmptxt);
								    }
								else {
								    WindowPrompt(tr("ERROR:"), tr("Not a WAD file."), tr("OK"));
								    }
							}
						}



			if (error || read != infilesize) {
			    WindowPrompt(tr("Error:"), tr("No data could be read."), tr("OK"));


			}
			if(temp)free(temp);
		}



		CloseConnection();
                ResumeNetworkWait();
        }

        if (cancelBtn.GetState() == STATE_CLICKED) {
            //break the loop and end the function
            exit = true;
            ret = -10;
        }
	else if (screenShotBtn.GetState() == STATE_CLICKED) {
			gprintf("\n\tscreenShotBtn clicked");
			screenShotBtn.ResetState();
			ScreenShot();
			gprintf("...It's easy, mmmmmmKay");
		    }
    }

    CloseConnection();
    if (IsNetworkInit())
        HaltNetworkThread();

    fclose(f);
    HaltGui();
    mainWindow->Remove(&w);
    ResumeGui();

    return ret;
}
Exemplo n.º 10
0
/**
 * Downloads the contents of a URL to memory
 * This method is not threadsafe (because networking is not threadsafe on the Wii)
 */
struct block downloadfile(const char *url)
{
	int sslcontext = -1;

	//Check if the url starts with "http://", if not it is not considered a valid url
	if (strncmp(url, "http://", strlen("http://")) == 0)
		http_port = 80;
	else if(strncmp(url, "https://", strlen("https://")) == 0)
	{
		http_port = 443;
		gprintf("Initializing ssl...\n");
		if(ssl_init() < 0)
			return emptyblock;
	}
	else
		return emptyblock;

	//Locate the path part of the url by searching for '/' past "http://"
	char *path = 0;
	if(http_port == 443)
		path = strchr(url + strlen("https://"), '/');
	else
		path = strchr(url + strlen("http://"), '/');

	//At the very least the url has to end with '/', ending with just a domain is invalid
	if (path == NULL)
	{
		//printf("URL '%s' has no PATH part\n", url);
		return emptyblock;
	}

	//Extract the domain part out of the url
	int domainlength = path - url - strlen("http://") - (http_port == 443 ? 1 : 0);

	if (domainlength == 0)
	{
		//printf("No domain part in URL '%s'\n", url);
		return emptyblock;
	}

	char domain[domainlength + 1];
	strlcpy(domain, url + strlen("http://") + (http_port == 443 ? 1 : 0), domainlength + 1);

	//Parsing of the URL is done, start making an actual connection
	u32 ipaddress = getipbynamecached(domain);

	if (ipaddress == 0)
	{
		//printf("\ndomain %s could not be resolved", domain);
		return emptyblock;
	}

	s32 connection = tcp_connect(ipaddress, http_port);

	if (connection < 0)
	{
		//printf("Error establishing connection");
		return emptyblock;
	}

	if(http_port == 443)
	{
		//patched out anyways so just to set something
		sslcontext = ssl_new((u8*)domain,0);

		if(sslcontext < 0)
		{
			//gprintf("ssl_new\n");
			result = HTTPR_ERR_CONNECT;
			net_close (connection);
			return emptyblock;
		}
		//patched out anyways so just to set something
		ssl_setbuiltinclientcert(sslcontext,0);
		if(ssl_connect(sslcontext,connection) < 0)
		{
			//gprintf("ssl_connect\n");
			result = HTTPR_ERR_CONNECT;
			ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
		int ret = ssl_handshake(sslcontext);
		if(ret < 0)
		{
			//gprintf("ssl_handshake %i\n", ret);
			result = HTTPR_ERR_STATUS;
			ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
	}

	// Remove Referer from the request header for incompatible websites (ex. Cloudflare proxy)
	char referer[domainlength + 12];
	snprintf(referer, sizeof(referer), "Referer: %s\r\n", domain);
	if(strstr(url, "geckocodes"))
	{
		strcpy(referer, "");
	}

	//Form a nice request header to send to the webserver
	char* headerformat = "GET %s HTTP/1.0\r\nHost: %s\r\n%sUser-Agent: USBLoaderGX r%s\r\n\r\n";
	char header[strlen(headerformat) + strlen(path) + strlen(domain) + strlen(referer) + 100];
	sprintf(header, headerformat, path, domain, referer, GetRev());
	//gprintf("\nHTTP Request:\n");
	//gprintf("%s\n",header);

	//Do the request and get the response
	tcp_write(http_port == 443 ? sslcontext : connection, header);
	read_header( http_port == 443 ? sslcontext : connection);

	if (http_status >= 400) // Not found
	{
		//gprintf("HTTP ERROR: %d\n", http_status);
		return emptyblock;
	}

	if(!content_length)
		content_length = 0;

	// create data buffer to return
	struct block response;
	response.data = malloc(content_length);
	response.size = content_length;
	if (response.data == NULL)
	{
		return emptyblock;
	}

	if (http_status == 200)
	{
		if(displayProgressWindow)
		{
			ProgressCancelEnable(true);
			StartProgress(tr("Downloading file..."), tr("Please wait"), 0, false, false);
		}

		int ret = tcp_readData(http_port == 443 ? sslcontext : connection, &response.data, content_length);
		if(!ret)
		{
			free(response.data);
			result = HTTPR_ERR_RECEIVE;
			if(http_port == 443)
				ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
	}
	else if (http_status == 302) // 302 FOUND (redirected link)
	{
		// close current connection
		if(http_port == 443)
			ssl_shutdown(sslcontext);
		net_close (connection);

		// prevent infinite loops
		retryloop++;
		if(retryloop > 3)
		{
			retryloop = 0;
			return emptyblock;
		}

		struct block redirected = downloadfile(content_location);
		if(redirected.size == 0)
			return emptyblock;

		// copy the newURL data into the original data
		u8 * tmp = realloc(response.data, redirected.size);
		if (tmp == NULL)
		{
			gprintf("Could not allocate enough memory for new URL. Download canceled.\n");
			free(response.data);
			response.size = 0;
			free(redirected.data);
			result = HTTPR_ERR_RECEIVE;
			if(http_port == 443)
				ssl_shutdown(sslcontext);
			net_close (connection);
			return emptyblock;
		}
		response.data = tmp;
		memcpy(response.data, redirected.data, redirected.size);
		free(redirected.data);
		response.size = redirected.size;

	}
	retryloop = 0;
	
	// reset progress window if used
	if(displayProgressWindow)
	{
		ProgressStop();
		ProgressCancelEnable(false);
		displayProgressWindow = false;
	}

	return response;
}