Пример #1
0
infilelist * AllocUniqueFileEntry( char *name, path_entry *path )
/**********************************************************************/
{
    infilelist *        entry;

    for( entry = CachedLibFiles; entry != NULL; entry = entry->next ) {
        if( FNAMECMPSTR( entry->name, name ) == 0 ) {
            return entry;       // we found 1 with the same name.
        }
    }
    entry = AllocEntry( name, path );   // didn't find one, so allocate a new 1
    if( CachedLibFiles == NULL ) {      // add libraries to the end of the
        CachedLibFiles = entry;         // regular cached files list.
        LinkList( &CachedFiles, entry );
    } else {
        LinkList( &CachedLibFiles, entry );
    }
    return entry;
}
Пример #2
0
static void MakeListItem( name_list **list, char *item, int len )
/***************************************************************/
{
    name_list * entry;

    entry = MemAlloc( sizeof( name_list ) + len );
    entry->next = NULL;
    entry->lnameidx = 0;
    memcpy( entry->name, item, len );
    *(entry->name + len) = '\0';
    LinkList( (void **)list, entry );
}
Пример #3
0
static bool ProcExclude( char *item, int len )
/********************************************/
{
    char *  endptr;

    while( len > 0 ) {
        switch( ExcludeState ) {
        case EX_NONE:
            ExEntry = MemAlloc( sizeof( exclude_list ) + len );
            ExEntry->next = NULL;
            ExEntry->segidx = 0;
            ExEntry->lnameidx = 0;
            memcpy( ExEntry->name, item, len );
            *(ExEntry->name + len ) = '\0';
            ExcludeState = EX_GOT_SEG;
            return( FALSE );
        case EX_GOT_SEG:
            ExEntry->start_off = strtoul( item, &endptr, 16 );
            len -= endptr - item;
            item = endptr;
            ExcludeState = EX_GOT_START;
            break;
        case EX_GOT_START:
            if( *item == '-' ) {
                ExcludeState = EX_GOT_DASH;
            } else if( *item == ':' ) {
                ExcludeState = EX_GOT_COLON;
            } else {
                Warning( "invalid range separator" );
                ExcludeState = EX_NONE;
                MemFree( ExEntry );
                return( TRUE );
            }
            item++;
            len--;
            break;
        default:    // EX_GOT_DASH or EX_GOT_COLON
            ExEntry->end_off = strtoul( item, NULL, 16 );
            if( ExcludeState == EX_GOT_COLON ) {
                ExEntry->end_off += ExEntry->start_off;
            }
            LinkList( (void **)&ExcludeList, ExEntry );
            ExcludeState = EX_NONE;
            return( TRUE );     // want a list separator after this.
        }
    }
    return( FALSE );
}
Пример #4
0
//=============================================================================
//コンストラクタ
//=============================================================================
ShimmerParticle2D::ShimmerParticle2D(void)
{

	LPDIRECT3DDEVICE9 Device = Window::Instance()->Device();
	//バッファの作成

	//ステータスの初期化
	_Pos = D3DXVECTOR3(0,0,0);
	_Size = D3DXVECTOR3(1.0f,1.0f,1.0f);
	_Speed = D3DXVECTOR3(0,0,0);
	_Rot = D3DXVECTOR3(0,0,0);
	uv = D3DXVECTOR4(0,0,1.0f,1.0f);
	Texture = GetTexture(TEX_NONE);
	ReleaseFlag = false;
	frame = 0;
	_Num++;
	LinkList();
}
Пример #5
0
//=============================================================================
//コンストラクタ
//=============================================================================
Sprite::Sprite(int priority)
{

	//ステータスの初期化
	_Color =
	_MaskColor = WHITE(1.0f);
	_Pos	= D3DXVECTOR3(0,0,0);
	_Offset = D3DXVECTOR2(0,0);
	_Size	= D3DXVECTOR3(1.0f,1.0f,1.0f);
	_Speed	= D3DXVECTOR3(0,0,0);
	_Rot		= D3DXVECTOR3(0,0,0);
	uv		= 
	MaskUV	= D3DXVECTOR4(0,0,1.0f,1.0f);
	Texture = 
	Mask = GetTexture(TEX_NONE);
	ReleaseFlag = false;
	Priority = priority;
	_Pass = CShader2D::NORMAL;
	memcpy(_Quad,QuadBase,sizeof(D3DXVECTOR3)*4);
	PolygonNum++;
	LinkList();
}
Пример #6
0
void IlukGraph<LocalOrdinal,GlobalOrdinal,Node>::constructFilledGraph() {
  size_t NumIn, NumL, NumU;
  bool DiagFound;
 
  constructOverlapGraph();
 
  L_Graph_ = Teuchos::rcp( new TpetraCrsGraphType(OverlapGraph_->getRowMap(), OverlapGraph_->getRowMap(),  0));
  U_Graph_ = Teuchos::rcp( new TpetraCrsGraphType(OverlapGraph_->getRowMap(), OverlapGraph_->getRowMap(),  0));
 
 
  // Get Maximum Row length
  int MaxNumIndices = OverlapGraph_->getNodeMaxNumRowEntries();
 
  Teuchos::Array<LocalOrdinal> L(MaxNumIndices);
  Teuchos::Array<LocalOrdinal> U(MaxNumIndices);
 
  // First we copy the user's graph into L and U, regardless of fill level
 
  int NumMyRows = OverlapGraph_->getRowMap()->getNodeNumElements();
  NumMyDiagonals_ = 0;

  for (int i=0; i< NumMyRows; i++) {
 
    Teuchos::ArrayView<const LocalOrdinal> my_indices;
    OverlapGraph_->getLocalRowView(i,my_indices);
 
    // Split into L and U (we don't assume that indices are ordered).
    
    NumL = 0; 
    NumU = 0; 
    DiagFound = false;
    NumIn = my_indices.size();

    for (size_t j=0; j< NumIn; j++) {
      LocalOrdinal k = my_indices[j];
      
      if (k<NumMyRows) { // Ignore column elements that are not in the square matrix
        
        if (k==i) DiagFound = true;
        
        else if (k < i) {
          L[NumL] = k;
          NumL++;
        }
        else {
          U[NumU] = k;
          NumU++;
        }
      }
    }

    // Check in things for this row of L and U
 
    if (DiagFound) ++NumMyDiagonals_;
    if (NumL) {
      Teuchos::ArrayView<LocalOrdinal> Lview(&L[0], NumL);
      L_Graph_->insertLocalIndices(i, Lview );
    }
    if (NumU) {
      Teuchos::ArrayView<LocalOrdinal> Uview(&U[0], NumU);
      U_Graph_->insertLocalIndices(i, Uview );
    }
  }
 
  if (LevelFill_ > 0) {
    
    // Complete Fill steps
    Teuchos::RCP<const TpetraMapType> L_DomainMap = OverlapGraph_->getRowMap();
    Teuchos::RCP<const TpetraMapType> L_RangeMap = Graph_->getRangeMap();
    Teuchos::RCP<const TpetraMapType> U_DomainMap = Graph_->getDomainMap();
    Teuchos::RCP<const TpetraMapType> U_RangeMap = OverlapGraph_->getRowMap();
    Teuchos::RCP<Teuchos::ParameterList> params = Teuchos::rcp(new Teuchos::ParameterList());
    params->set("Optimize Storage",false);
    L_Graph_->fillComplete(L_DomainMap, L_RangeMap, params);
    U_Graph_->fillComplete(U_DomainMap, U_RangeMap, params);
    L_Graph_->resumeFill();
    U_Graph_->resumeFill();
    
    // At this point L_Graph and U_Graph are filled with the pattern of input graph, 
    // sorted and have redundant indices (if any) removed.  Indices are zero based.
    // LevelFill is greater than zero, so continue...
    
    int MaxRC = NumMyRows;
    std::vector<std::vector<int> > Levels(MaxRC);
    std::vector<int> LinkList(MaxRC);
    std::vector<int> CurrentLevel(MaxRC);
    Teuchos::Array<LocalOrdinal> CurrentRow(MaxRC+1);
    std::vector<int> LevelsRowU(MaxRC);
 
    for (int i=0; i<NumMyRows; i++)
    {
      int First, Next;

      // copy column indices of row into workspace and sort them

      size_t LenL = L_Graph_->getNumEntriesInLocalRow(i);
      size_t LenU = U_Graph_->getNumEntriesInLocalRow(i);
      size_t Len = LenL + LenU + 1;

      CurrentRow.resize(Len);

      L_Graph_->getLocalRowCopy(i, CurrentRow(), LenL);      // Get L Indices
      CurrentRow[LenL] = i;                                     // Put in Diagonal
      if (LenU > 0) {
        Teuchos::ArrayView<LocalOrdinal> URowView(&CurrentRow[LenL+1], LenU);
        // Get U Indices
        U_Graph_->getLocalRowCopy(i, URowView, LenU);
      }

      // Construct linked list for current row
      
      for (size_t j=0; j<Len-1; j++) {
        LinkList[CurrentRow[j]] = CurrentRow[j+1];
        CurrentLevel[CurrentRow[j]] = 0;
      }
      
      LinkList[CurrentRow[Len-1]] = NumMyRows;
      CurrentLevel[CurrentRow[Len-1]] = 0;
      
      // Merge List with rows in U
      
      First = CurrentRow[0];
      Next = First;
      while (Next < i)
      {
        int PrevInList = Next;
        int NextInList = LinkList[Next];
        int RowU = Next;
        // Get Indices for this row of U
        Teuchos::ArrayView<const LocalOrdinal> IndicesU;
        U_Graph_->getLocalRowView(RowU,IndicesU);
        int LengthRowU = IndicesU.size();
        
        int ii;
        
        // Scan RowU
        
        for (ii=0; ii<LengthRowU; /*nop*/)
        {
          int CurInList = IndicesU[ii];
          if (CurInList < NextInList)
          {
            // new fill-in
            int NewLevel = CurrentLevel[RowU] + Levels[RowU][ii+1] + 1;
            if (NewLevel <= LevelFill_)
            {
              LinkList[PrevInList]  = CurInList;
              LinkList[CurInList] = NextInList;
              PrevInList = CurInList;
              CurrentLevel[CurInList] = NewLevel;
            }
            ii++;
          }
          else if (CurInList == NextInList)
          {
            PrevInList = NextInList;
            NextInList = LinkList[PrevInList];
            int NewLevel = CurrentLevel[RowU] + Levels[RowU][ii+1] + 1;
            CurrentLevel[CurInList] = std::min(CurrentLevel[CurInList], NewLevel);
            ii++;
          }
          else // (CurInList > NextInList)
          {
            PrevInList = NextInList;
            NextInList = LinkList[PrevInList];
          }
        }
        Next = LinkList[Next];
      }
      
      // Put pattern into L and U
      
      CurrentRow.resize(0);
      
      Next = First;
      
      // Lower
      
      while (Next < i) {    
        CurrentRow.push_back(Next);
        Next = LinkList[Next];
      }

      L_Graph_->removeLocalIndices(i); // Delete current set of Indices
      if (CurrentRow.size() > 0) {
        L_Graph_->insertLocalIndices(i, CurrentRow());
      }
 
      // Diagonal
      
      TEUCHOS_TEST_FOR_EXCEPTION(Next != i, std::runtime_error,
                         "Ifpack2::IlukGraph::constructFilledGraph: FATAL: U has zero diagonal")

      LevelsRowU[0] = CurrentLevel[Next];
      Next = LinkList[Next];
      
      // Upper
      
      CurrentRow.resize(0);
      LenU = 0;
      
      while (Next < NumMyRows) {
        LevelsRowU[LenU+1] = CurrentLevel[Next];
        CurrentRow.push_back(Next);
        ++LenU;
        Next = LinkList[Next];
      }
      
      U_Graph_->removeLocalIndices(i); // Delete current set of Indices
      if (LenU > 0) {
        U_Graph_->insertLocalIndices(i, CurrentRow());
      }
 
      // Allocate and fill Level info for this row
      Levels[i] = std::vector<int>(LenU+1);
      for (size_t jj=0; jj<LenU+1; jj++) {
        Levels[i][jj] = LevelsRowU[jj];
      }
    }
  }    
  
  // Complete Fill steps
  Teuchos::RCP<const TpetraMapType> L_DomainMap = OverlapGraph_->getRowMap();
  Teuchos::RCP<const TpetraMapType> L_RangeMap  = Graph_->getRangeMap();
  Teuchos::RCP<const TpetraMapType> U_DomainMap = Graph_->getDomainMap();
  Teuchos::RCP<const TpetraMapType> U_RangeMap  = OverlapGraph_->getRowMap();
  L_Graph_->fillComplete(L_DomainMap, L_RangeMap);//DoOptimizeStorage is default here...
  U_Graph_->fillComplete(U_DomainMap, U_RangeMap);//DoOptimizeStorage is default here...

  Teuchos::reduceAll<int,size_t>(*(L_DomainMap->getComm()), Teuchos::REDUCE_SUM, 1, &NumMyDiagonals_, &NumGlobalDiagonals_);
}
Пример #7
0
bool ParseDivToFile(string DelimitedFile)
{
    /// Read Input Text
    ifstream LinkList(DelimitedFile.c_str());
    stringstream NewText;
    string line;
    iterator_range<string::iterator> range;

    NewText << LinkList.rdbuf();

    while(getline(NewText, line)) {
        range = algorithm::ifind_first(line, "http://");

        if(range.empty())
        {
           continue;
        }

        string FilePath = "/tmp/unit-test.html";

        string WgetCommandPrep = "wget " + line + " -O " + FilePath;
        const char* WgetCommandExecute = WgetCommandPrep.c_str();

        //< Download
        int lRet = std::system(WgetCommandExecute);

        if(lRet != 0) {
            cerr << "wget failed to run. Aborting...";
            _exit(EXIT_FAILURE);
        }

        filesystem::path file(FilePath);

        ostringstream OutputString;
        ifstream infile(FilePath);

        OutputString << infile.rdbuf();

        string FoundTitle = WebMigrate::ParseDiv(
            OutputString.str(),
            "<div class=\"title\">",
            "<div",
            "</div>",
            false
        );

        if(FoundTitle.empty()) {
            FoundTitle = WebMigrate::ParseDiv(
                OutputString.str(),
                "<div class=\"page_title\">",
                "<div",
                "</div>",
                false
            );
        }


        if(FoundTitle.empty())
        {
            remove(FilePath.c_str());
        }

        ofstream outfile(WebMigrate::ToSlug(FoundTitle) + ".php", ios::trunc);

        if(outfile.is_open()) {
            string FormatText = WebMigrate::GetBetween(
                OutputString.str(),
                "<div class=\"rightcontent\">",
                "<div class=\"footer\">"
            );

            algorithm::ireplace_last(FormatText, "</div>", "");

            outfile << FormatText;
        }

        remove(FilePath.c_str());
    }

    return true;
}
Пример #8
0
GameTable::GameTable(SDL_Renderer* pRenderer, const Uint32 w, const Uint32 h)
{
    // Game window size
    windowW = w;
    windowH = h;

    // Game table initialization
    table = new Table();

    // Timer initialization
    Uint32 timerW = 100;
    Uint32 timerH = 10;
    Uint32 timerX = static_cast<Uint32>((windowW * 0.5) - (timerW * 0.5f));
    Uint32 timerY = 5;
    timerRect = SDL_Rect{ timerX, timerY, timerW, timerH };
    timerFillColor = SDL_Color{ 250, 104, 87, 255 };
    timerBGColor = SDL_Color{ 255, 207, 201, 255 };
    timer = new SimpleTimer();
    animTimer = new SimpleTimer();

    // Upper Left position
    ulPos = new SDL_Point{ 50, 300 };

    // Table Rectangle delimiter
    tableDelimiter = new SDL_Rect{ ulPos->x, ulPos->y - (rowNum - 1) * 40, colLimit * 40, rowNum * 40 };

    // Initialize randomization
    distributionForColumn = uDist(minColNum, rowNum);

    // At max baseMaxBlockColor colors at first
    distributionForBlockColor = uDist(0, baseMaxBlockColor);

    // At first only normal blocks
    distributionForBlockType = uDist(0, 0);

    // Random functions
    // Defining on the fly seed for the random engine
    auto seed = static_cast<Uint32>(std::chrono::system_clock::now().time_since_epoch().count());
    generator = std::default_random_engine(1);

    // Binding for ease of use
    randColNum = std::bind(distributionForColumn, generator);
    randBlockColor = std::bind(distributionForBlockColor, generator);
    randBlockType = std::bind(distributionForBlockType, generator);

    // Loading background textures
    backgroundTexture = new SimpleTexture(pRenderer);
    backgroundTexture->LoadFromFileRGB(TABLE_BG_TEX_NAME, SDL_FALSE, nullptr);

    // Loading block textures
    blockTexture = new SimpleTexture(pRenderer);
    blockTexture->LoadFromFileRGB(BLOCK_TEX_NAME, SDL_FALSE, nullptr);

    blockTextureHighlighted = new SimpleTexture(pRenderer);
    blockTextureHighlighted->LoadFromFileRGB(BLOCK_TEX_HL_NAME, SDL_FALSE, nullptr);

    // Loading font
    gameFont = TTF_OpenFont(fontName.c_str(), 20);
    textTexture = new SimpleTexture(pRenderer);

    // Creating buttons
    btnAddFaceTexture = new SimpleTexture(pRenderer);
    btnAddFaceTexture->LoadFromFileRGB(PLUS_TEX_HL_NAME, SDL_FALSE, nullptr);
    btnAddColumn = new SimpleButton(pRenderer, blockTexture, blockTextureHighlighted, btnAddFaceTexture, SDL_Color{ 255, 255, 255, 255 }, ulPos->x + ((colLimit - 1) * 40), ulPos->y + 40, 40, 40);
    btnPauseGame = new SimpleButton(pRenderer, blockTexture, blockTextureHighlighted, nullptr, SDL_Color{ 255, 255, 255, 255 }, ulPos->x - 40 - 5, ulPos->y - ((rowNum - 1) * 40), 40, 40);

    // Initialize Linked block lists
    blockLinks = LinkList();
    newLink = new Link();

    // Score, experience and pause rendering settings
    scoreColor = SDL_Color{ 0xFF, 0xE4, 0xD1, 0xFF };
    scoreULPos = SDL_Point{ 100, static_cast<Uint32>(windowH * 0.8f) };
    levelULPos = SDL_Point{ 100, static_cast<Uint32>(windowH * 0.8f) + 30 };

    // Calculate pause string width
    int* posW = new int();
    int* posH = new int();
    TTF_SizeText(gameFont, pauseText.c_str(), posW, posH);
    auto textSize = *posW;
    pauseULPos = SDL_Point{ static_cast<Uint32>((windowW - textSize) * 0.5f), static_cast<Uint32>(windowH * 0.5f - 100) };

    // Calculate experience string width
    TTF_SizeText(gameFont, expText.c_str(), posW, posH);
    textSize = *posW;
    expULPos = SDL_Point{ static_cast<Uint32>((windowW - textSize) * 0.5f), ulPos->y + 35 };
    expRect = SDL_Rect{ static_cast<Uint32>(windowW * 0.5f - 100), expULPos.y + *posH + 5, 200, 15 };
    delete posW;
    delete posH;

    // Initialize all the game variables
    Init();
}
Пример #9
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;
}
Пример #10
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;
}
Пример #11
0
/****************************************************************************
 * Update the language files
 ***************************************************************************/
bool UpdateTask::UpdateLanguageFiles(void)
{
	if(!IsNetworkInit())
		return false;

	char langpath[150];
	snprintf(langpath, sizeof(langpath), "%s", Settings.LanguagePath);
	if(langpath[strlen(langpath)-1] != '/')
	{
		char * ptr = strrchr(langpath, '/');
		if(ptr)
			ptr[1] = '\0';
	}

	if(!CreateSubfolder(langpath))
	{
		ThrowMsg(tr("Error:"), "%s", tr("Cannot create directory: "), langpath);
		return -1;
	}

	URL_List LinkList(languageUpdateURL);

	if(LinkList.GetURLCount() <= 0)
	{
		ThrowMsg(tr("Error:"), tr("No files found."));
		return -1;
	}

	ProgressWindow::Instance()->StartProgress(tr("Downloading files..."));
	ProgressWindow::Instance()->SetUnit(tr("files"));

	u32 FilesDownloaded = 0;

	for (int i = 0; i < LinkList.GetURLCount(); i++)
	{
		if(ProgressWindow::Instance()->IsCanceled())
			continue;

		ShowProgress(i, LinkList.GetURLCount(), LinkList.GetURL(i));

		char * fileext = strrchr(LinkList.GetURL(i), '.');
		if(!fileext)
			continue;

		if (strcasecmp(fileext, ".lang") != 0)
			continue;

		char fullURL[MAXPATHLEN];
		if(LinkList.IsFullURL(i))
			snprintf(fullURL, sizeof(fullURL), "%s", LinkList.GetURL(i));
		else
			snprintf(fullURL, sizeof(fullURL), "%s%s", languageUpdateURL, LinkList.GetURL(i));

		struct block file = downloadfile(fullURL);

		if (file.data && file.size > 0)
		{
			snprintf(fullURL, sizeof(fullURL), "%s%s", langpath, LinkList.GetURL(i));
			FILE * filePtr = fopen(fullURL, "wb");
			if(filePtr)
			{
				fwrite(file.data, 1, file.size, filePtr);
				fclose(filePtr);
				FilesDownloaded++;
			}
		}

		if(file.data)
			free(file.data);
	}

	// finish up the progress for this file
	ProgressWindow::Instance()->FinishProgress((LinkList.GetURLCount()-1)*20*1024);
	ProgressWindow::Instance()->StopProgress();
	ProgressWindow::Instance()->SetUnit(NULL);

	return FilesDownloaded;
}