/* atsh_compute_SMR * ================ * computes the SMR data for a set of frames * *sound: pointer to an ATS_SOUND structure * from_frame: initial frame * to_frame: last frame */ void atsh_compute_SMR(ATS_SOUND *sound, int from_frame, int to_frame) { ATS_PEAK *peaks; int i, j, nValue=0; int todo = to_frame - from_frame; peaks = (ATS_PEAK *)malloc(sound->partials * sizeof(ATS_PEAK)); StartProgress("Computing SMR...", FALSE); for(i = from_frame; i < to_frame; i++) { //fprintf(stderr," frm=%d", i); make_peaks(sound,peaks,i); evaluate_smr(peaks, sound->partials); for(j = 0 ; j < sound->partials ; j++) { sound->smr[j][i] = peaks[j].smr; //fprintf(stderr,"%8.3f ",sound->smr[j][i] ); } //fprintf(stderr,"\n"); ++nValue; UpdateProgress(nValue,todo); } EndProgress(); smr_done=TRUE; free(peaks); }
// refills the PeakFile Cache void CommonPool::ResetIndexView() { if (sample_type == NONE) return; StartProgress(B_TRANSLATE("Indexing..."), size); Peak.Init(size+1, (Pool.sample_type == MONO) ); Peak.CreatePeaks(0, size+1, size+1); Pool.update_index = true; // update the draw cache HideProgress(); }
// refills the PeakFile Cache void CommonPool::ResetIndexView() { if (sample_type == NONE) return; StartProgress(Language.get("INDEXING"), size); Peak.Init(size+1, (Pool.sample_type == MONO) ); Peak.CreatePeaks(0, size+1, size+1); Pool.update_index = true; // update the draw cache HideProgress(); }
/**************************************************************************** * UpdateApp from a given url. The dol is downloaded and overwrites the old one. ***************************************************************************/ int UpdateTask::DownloadApp(const char *url) { if(!url) { ThrowMsg(tr("Error"), tr("URL is empty.")); return -1; } //! append slash if it is missing std::string destPath = Settings.UpdatePath; if(destPath.size() > 0 && destPath[destPath.size()-1] != '/') destPath += '/'; destPath += "boot.zip"; CreateSubfolder(Settings.UpdatePath); int res = DownloadFileToPath(url, destPath.c_str(), false); if(res < 102400) { RemoveFile(destPath.c_str()); ThrowMsg(tr("Update failed"), tr("Could not download file.")); return -1; } else { StartProgress(tr("Extracting file...")); ZipFile zip(destPath.c_str()); zip.ExtractAll(Settings.UpdatePath); RemoveFile(destPath.c_str()); StopProgress(); if(Settings.UpdateMetaxml) DownloadMetaXml(); if(Settings.UpdateIconpng) DownloadIconPNG(); } return 1; }
/**************************************************************************** * 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; }
void CProjectProcessingPage::OnStateChange( CProjectProcessingPageEvent& WXUNUSED(event) ) { CMainDocument* pDoc = wxGetApp().GetDocument(); CWizardAttachProject* pWAP = ((CWizardAttachProject*)GetParent()); ACCOUNT_IN* ai = &pWAP->account_in; ACCOUNT_OUT* ao = &pWAP->account_out; unsigned int i; PROJECT_ATTACH_REPLY reply; wxString strBuffer = wxEmptyString; wxDateTime dtStartExecutionTime; wxDateTime dtCurrentExecutionTime; wxTimeSpan tsExecutionTime; bool bPostNewEvent = true; int iReturnValue = 0; bool creating_account = false; wxASSERT(pDoc); wxASSERT(wxDynamicCast(pDoc, CMainDocument)); switch(GetCurrentState()) { case ATTACHPROJECT_INIT: pWAP->DisableNextButton(); pWAP->DisableBackButton(); StartProgress(m_pProgressIndicator); SetNextState(ATTACHPROJECT_ACCOUNTQUERY_BEGIN); break; case ATTACHPROJECT_ACCOUNTQUERY_BEGIN: SetNextState(ATTACHPROJECT_ACCOUNTQUERY_EXECUTE); break; case ATTACHPROJECT_ACCOUNTQUERY_EXECUTE: // Attempt to create the account or reterieve the authenticator. ai->clear(); ao->clear(); // Newer versions of the server-side software contain the correct // master url in the get_project_config response. If it is available // use it instead of what the user typed in. if (!pWAP->project_config.master_url.empty()) { ai->url = pWAP->project_config.master_url; } else { ai->url = (const char*)pWAP->m_ProjectInfoPage->GetProjectURL().mb_str(); } if (!pWAP->GetProjectAuthenticator().IsEmpty() || pWAP->m_bCredentialsCached || pWAP->m_bCredentialsDetected ) { if (!pWAP->m_bCredentialsCached || pWAP->m_bCredentialsDetected) { ao->authenticator = (const char*)pWAP->GetProjectAuthenticator().mb_str(); } SetProjectCommunitcationsSucceeded(true); } else { // Setup initial values for both the create and lookup API ai->email_addr = (const char*)pWAP->m_AccountInfoPage->GetAccountEmailAddress().mb_str(); ai->passwd = (const char*)pWAP->m_AccountInfoPage->GetAccountPassword().mb_str(); ai->user_name = (const char*)::wxGetUserName().mb_str(); ai->team_name = pWAP->team_name; if (ai->user_name.empty()) { ai->user_name = (const char*)::wxGetUserId().mb_str(); } if (pWAP->m_AccountInfoPage->m_pAccountCreateCtrl->GetValue()) { creating_account = true; // Wait until we are done processing the request. dtStartExecutionTime = wxDateTime::Now(); dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = 0; ao->error_num = ERR_RETRY; while ( !iReturnValue && ((ERR_IN_PROGRESS == ao->error_num) || (ERR_RETRY == ao->error_num)) && tsExecutionTime.GetSeconds() <= 60 && !CHECK_CLOSINGINPROGRESS() ) { if (ERR_RETRY == ao->error_num) { pDoc->rpc.create_account(*ai); } dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = pDoc->rpc.create_account_poll(*ao); IncrementProgress(m_pProgressIndicator); ::wxMilliSleep(500); ::wxSafeYield(GetParent()); } if ((!iReturnValue) && !ao->error_num) { pWAP->SetAccountCreatedSuccessfully(true); } } else { creating_account = false; // Wait until we are done processing the request. dtStartExecutionTime = wxDateTime::Now(); dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = 0; ao->error_num = ERR_RETRY; while ( !iReturnValue && ((ERR_IN_PROGRESS == ao->error_num) || (ERR_RETRY == ao->error_num)) && tsExecutionTime.GetSeconds() <= 60 && !CHECK_CLOSINGINPROGRESS() ) { if (ERR_RETRY == ao->error_num) { pDoc->rpc.lookup_account(*ai); } dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = pDoc->rpc.lookup_account_poll(*ao); IncrementProgress(m_pProgressIndicator); ::wxMilliSleep(500); ::wxSafeYield(GetParent()); } } if ((!iReturnValue) && !ao->error_num) { SetProjectCommunitcationsSucceeded(true); } else { SetProjectCommunitcationsSucceeded(false); if ((ao->error_num == ERR_DB_NOT_UNIQUE) || (ao->error_num == ERR_NONUNIQUE_EMAIL) || (ao->error_num == ERR_BAD_PASSWD && creating_account) ) { SetProjectAccountAlreadyExists(true); } else { SetProjectAccountAlreadyExists(false); } if ((ERR_NOT_FOUND == ao->error_num) || (ao->error_num == ERR_DB_NOT_FOUND) || (ERR_BAD_EMAIL_ADDR == ao->error_num) || (ERR_BAD_PASSWD == ao->error_num) ) { SetProjectAccountNotFound(true); } else { SetProjectAccountNotFound(false); } strBuffer = pWAP->m_CompletionErrorPage->m_pServerMessagesCtrl->GetLabel(); if ((HTTP_STATUS_NOT_FOUND == ao->error_num)) { strBuffer += _("Required wizard file(s) are missing from the target server.\n(lookup_account.php/create_account.php)\n"); } else if ((HTTP_STATUS_INTERNAL_SERVER_ERROR == ao->error_num)) { strBuffer += _("An internal server error has occurred.\n"); } else { if (ao->error_msg.size()) { strBuffer += wxString(ao->error_msg.c_str(), wxConvUTF8) + wxString(wxT("\n")); } } pWAP->m_CompletionErrorPage->m_pServerMessagesCtrl->SetLabel(strBuffer); } } SetNextState(ATTACHPROJECT_ATTACHPROJECT_BEGIN); break; case ATTACHPROJECT_ATTACHPROJECT_BEGIN: SetNextState(ATTACHPROJECT_ATTACHPROJECT_EXECUTE); break; case ATTACHPROJECT_ATTACHPROJECT_EXECUTE: if (GetProjectCommunitcationsSucceeded()) { // Wait until we are done processing the request. dtStartExecutionTime = wxDateTime::Now(); dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = 0; reply.error_num = ERR_RETRY; while ( !iReturnValue && ((ERR_IN_PROGRESS == reply.error_num) || (ERR_RETRY == reply.error_num)) && tsExecutionTime.GetSeconds() <= 60 && !CHECK_CLOSINGINPROGRESS() ) { if (ERR_RETRY == reply.error_num) { if (pWAP->m_bCredentialsCached) { pDoc->rpc.project_attach_from_file(); } else { pDoc->rpc.project_attach( ai->url.c_str(), ao->authenticator.c_str(), pWAP->project_config.name.c_str() ); } } dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = pDoc->rpc.project_attach_poll(reply); IncrementProgress(m_pProgressIndicator); ::wxMilliSleep(500); ::wxSafeYield(GetParent()); } if (!iReturnValue && !reply.error_num) { SetProjectAttachSucceeded(true); pWAP->SetAttachedToProjectSuccessfully(true); pWAP->SetProjectURL(wxString(ai->url.c_str(), wxConvUTF8)); pWAP->SetProjectAuthenticator(wxString(ao->authenticator.c_str(), wxConvUTF8)); } else { SetProjectAttachSucceeded(false); strBuffer = pWAP->m_CompletionErrorPage->m_pServerMessagesCtrl->GetLabel(); if ((HTTP_STATUS_INTERNAL_SERVER_ERROR == reply.error_num)) { strBuffer += _("An internal server error has occurred.\n"); } else { for (i=0; i<reply.messages.size(); i++) { strBuffer += wxString(reply.messages[i].c_str(), wxConvUTF8) + wxString(wxT("\n")); } } pWAP->m_CompletionErrorPage->m_pServerMessagesCtrl->SetLabel(wxString(strBuffer, wxConvUTF8)); } } else { SetProjectAttachSucceeded(false); } SetNextState(ATTACHPROJECT_CLEANUP); break; case ATTACHPROJECT_CLEANUP: FinishProgress(m_pProgressIndicator); SetNextState(ATTACHPROJECT_END); break; default: // Allow a glimps of what the result was before advancing to the next page. wxSleep(1); pWAP->EnableNextButton(); pWAP->EnableBackButton(); pWAP->SimulateNextButton(); bPostNewEvent = false; break; } Update(); if (bPostNewEvent && !CHECK_CLOSINGINPROGRESS()) { CProjectProcessingPageEvent TransitionEvent(wxEVT_PROJECTPROCESSING_STATECHANGE, this); AddPendingEvent(TransitionEvent); } }
void CProjectPropertiesPage::OnStateChange( CProjectPropertiesPageEvent& WXUNUSED(event) ) { CMainDocument* pDoc = wxGetApp().GetDocument(); CWizardAttach* pWAP = ((CWizardAttach*)GetParent()); PROJECT_CONFIG* pc = &pWAP->project_config; CC_STATUS status; wxDateTime dtStartExecutionTime; wxDateTime dtCurrentExecutionTime; wxTimeSpan tsExecutionTime; wxString strBuffer = wxEmptyString; bool bPostNewEvent = true; int iReturnValue = 0; wxASSERT(pDoc); wxASSERT(wxDynamicCast(pDoc, CMainDocument)); switch(GetCurrentState()) { case PROJPROP_INIT: pWAP->DisableNextButton(); pWAP->DisableBackButton(); StartProgress(m_pProgressIndicator); SetNextState(PROJPROP_RETRPROJECTPROPERTIES_BEGIN); break; case PROJPROP_RETRPROJECTPROPERTIES_BEGIN: SetNextState(PROJPROP_RETRPROJECTPROPERTIES_EXECUTE); break; case PROJPROP_RETRPROJECTPROPERTIES_EXECUTE: // Attempt to retrieve the project's account creation policies // Wait until we are done processing the request. dtStartExecutionTime = wxDateTime::Now(); dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = 0; pc->clear(); pc->error_num = ERR_RETRY; while ( !iReturnValue && ((ERR_IN_PROGRESS == pc->error_num) || (ERR_RETRY == pc->error_num)) && tsExecutionTime.GetSeconds() <= 60 && !CHECK_CLOSINGINPROGRESS() ) { if (ERR_RETRY == pc->error_num) { pDoc->rpc.get_project_config( (const char*)pWAP->m_ProjectInfoPage->GetProjectURL().mb_str() ); } dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = pDoc->rpc.get_project_config_poll(*pc); IncrementProgress(m_pProgressIndicator); ::wxMilliSleep(500); wxEventLoopBase::GetActive()->YieldFor(wxEVT_CATEGORY_USER_INPUT); } if ( !iReturnValue && (!pc->error_num || pc->error_num == ERR_ACCT_CREATION_DISABLED) ) { // We either successfully retrieved the project's // account creation policies or we were able to talk // to the web server and found out they do not support // account creation through the wizard. // In either case, claim success and set the correct flags // to show the correct 'next' page. // SetProjectPropertiesSucceeded(true); SetProjectAccountCreationDisabled(pc->account_creation_disabled); SetProjectClientAccountCreationDisabled(pc->client_account_creation_disabled); SetTermsOfUseRequired(!pc->terms_of_use.empty()); } else { SetProjectPropertiesSucceeded(false); SetProjectPropertiesURLFailure(pc->error_num == ERR_HTTP_PERMANENT); bool comm_failure = !iReturnValue && ( (ERR_GETHOSTBYNAME == pc->error_num) || (ERR_CONNECT == pc->error_num) || (ERR_XML_PARSE == pc->error_num) || (ERR_PROJECT_DOWN == pc->error_num) ); SetProjectPropertiesCommunicationFailure(comm_failure); bool server_reported_error = !iReturnValue && ( (ERR_HTTP_PERMANENT != pc->error_num) && (ERR_GETHOSTBYNAME != pc->error_num) && (ERR_CONNECT != pc->error_num) && (ERR_XML_PARSE != pc->error_num) && (ERR_PROJECT_DOWN != pc->error_num) ); SetServerReportedError(server_reported_error); if (server_reported_error) { strBuffer = pWAP->m_CompletionErrorPage->m_pServerMessagesCtrl->GetLabel(); if (pc->error_msg.size()) { strBuffer += wxString(pc->error_msg.c_str(), wxConvUTF8) + wxString(wxT("\n")); } pWAP->m_CompletionErrorPage->m_pServerMessagesCtrl->SetLabel(strBuffer); } } SetNextState(PROJPROP_DETERMINENETWORKSTATUS_BEGIN); break; case PROJPROP_DETERMINENETWORKSTATUS_BEGIN: SetNextState(PROJPROP_DETERMINENETWORKSTATUS_EXECUTE); break; case PROJPROP_DETERMINENETWORKSTATUS_EXECUTE: // Attempt to determine if we are even connected to a network // Wait until we are done processing the request. dtStartExecutionTime = wxDateTime::Now(); dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = 0; status.network_status = NETWORK_STATUS_LOOKUP_PENDING; while ((!iReturnValue && (NETWORK_STATUS_LOOKUP_PENDING == status.network_status)) && tsExecutionTime.GetSeconds() <= 60 && !CHECK_CLOSINGINPROGRESS() ) { dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = pDoc->GetCoreClientStatus(status); IncrementProgress(m_pProgressIndicator); ::wxMilliSleep(500); wxEventLoopBase::GetActive()->YieldFor(wxEVT_CATEGORY_USER_INPUT); } SetNetworkConnectionNotDetected(NETWORK_STATUS_WANT_CONNECTION == status.network_status); SetNextState(PROJPROP_DETERMINEACCOUNTINFOSTATUS_BEGIN); break; case PROJPROP_DETERMINEACCOUNTINFOSTATUS_BEGIN: SetNextState(PROJPROP_DETERMINEACCOUNTINFOSTATUS_EXECUTE); break; case PROJPROP_DETERMINEACCOUNTINFOSTATUS_EXECUTE: // Determine if the account settings are already pre-populated. // If so, advance to the Project Processing page. SetCredentialsAlreadyAvailable(pWAP->m_bCredentialsCached || pWAP->m_bCredentialsDetected); SetNextState(PROJPROP_CLEANUP); break; case PROJPROP_CLEANUP: FinishProgress(m_pProgressIndicator); SetNextState(PROJPROP_END); break; default: // Allow a glimps of what the result was before advancing to the next page. wxSleep(1); pWAP->EnableNextButton(); pWAP->EnableBackButton(); pWAP->SimulateNextButton(); bPostNewEvent = false; break; } Update(); if (bPostNewEvent && !CHECK_CLOSINGINPROGRESS()) { CProjectPropertiesPageEvent TransitionEvent(wxEVT_PROJECTPROPERTIES_STATECHANGE, this); AddPendingEvent(TransitionEvent); } }
void MoveTask::Execute(void) { TaskBegin(this); // No items to process if(Process.GetItemcount() == 0) { TaskEnd(this); return; } if(ProgressWindow::Instance()->IsRunning()) ProgressWindow::Instance()->SetTitle(tr("Calculating transfer size...")); else StartProgress(tr("Calculating transfer size...")); ProgressWindow::Instance()->SetTitle(this->getTitle().c_str()); string destPathSlash = (destPath.size() > 0 && destPath[destPath.size()-1] != '/') ? destPath + '/' : destPath; int result = 0; //! On same device we move files instead of copy them for(int i = 0; i < Process.GetItemcount(); ++i) { if(CompareDevices(Process.GetItemPath(i), destPathSlash.c_str())) { string srcpath = Process.GetItemPath(i); while(srcpath[srcpath.size()-1] == '/') srcpath.erase(srcpath.size()-1); const char *pathname = strrchr(srcpath.c_str(), '/'); if(!pathname) continue; string dstpath = destPathSlash + (pathname+1); if(strcasecmp(srcpath.c_str(), dstpath.c_str()) == 0) { //! nothing to be done here Process.RemoveItem(Process.GetItem(i)); i--; continue; } //! moving directory to a path where the same directory name exists //! we will move all files and remove src directory in the later process if(Process.IsItemDir(i) && CheckFile(dstpath.c_str())) continue; int ret = MoveFile(srcpath.c_str(), dstpath.c_str()); if(ret < 0) result = ret; Process.RemoveItem(Process.GetItem(i)); i--; } } list<ItemList> itemList; if(GetItemList(itemList, true) < 0) { result = -1; } //! free memory of process which is no longer required Process.Reset(); //! On same device we move files instead of copy them ProgressWindow::Instance()->SetCompleteValues(0, CopySize); for(list<ItemList>::iterator listItr = itemList.begin(); listItr != itemList.end(); listItr++) { //! first move/remove all files in all sub directories for(list<string>::iterator itr = listItr->files.begin(); itr != listItr->files.end(); itr++) { if(ProgressWindow::Instance()->IsCanceled()) break; string srcpath = listItr->basepath + *itr; string dstpath = destPathSlash + *itr; string folderpath = dstpath; size_t pos = folderpath.rfind('/'); if(pos != string::npos) folderpath.erase(pos); CreateSubfolder(folderpath.c_str()); int ret = MoveFile(srcpath.c_str(), dstpath.c_str()); if(ret < 0) result = ret; } //! Remove all dirs reversed as they were appended to the list for(list<string>::iterator itr = listItr->dirs.begin(); itr != listItr->dirs.end(); itr++) { if(ProgressWindow::Instance()->IsCanceled()) break; RemoveFile((listItr->basepath + *itr).c_str()); } if(ProgressWindow::Instance()->IsCanceled()) { result = PROGRESS_CANCELED; break; } } if(result < 0 && result != PROGRESS_CANCELED && !Application::isClosing()) { ThrowMsg(tr("Error:"), tr("Failed moving some item(s).")); } TaskEnd(this); }
//////////////////////////////////////////////////////////////////// /////////THIS IS THE MAIN SYNTHESIS LOOP//////////////////////////// //////////////////////////////////////////////////////////////////// void do_synthesis() { int i,x,z,j,maxlen, todo, curr, next, sflag=0; float dt=0., rfreq; float frame_samps, bw=.1; int ptout; float maxamp=0.; int bframe=0, eframe=0; int nValue=0; char stamp[16]; int written; int format,header; mus_sample_t *obuf[1]; float cxval, cyval, nxval, nyval, difx, dify; TIME_DATA *tdata; int nbp; float *dospt=NULL, *rospt=NULL; RANDI *rarray=NULL; float res_band_edges[ATSA_CRITICAL_BANDS+1]=ATSA_CRITICAL_BAND_EDGES; float res_band_centers[ATSA_CRITICAL_BANDS]; char str[100]; //ATTEMPT TO CATCH TWO POSSIBLE ERRORS........ if(*ats_tittle==0) { Popup("ERROR: ATS file undefined, select it first"); return; } if(*out_tittle==0) { Popup("ERROR: Output Soundfile undefined, select it first"); return; } if(sparams->amp==0. && sparams->ramp==0.) { Popup("ERROR: Deterministic and Residual output set to zero"); return; } //OPEN OUTPUT FILE set_output_type(&format, &header); if((ptout=mus_sound_open_output(out_tittle,(int)sparams->sr,1,format,header,"created by ATSH"))==-1) { Popup("ERROR: could not open Output Soundfile for writing"); return; } //do residual data transfer if (FILE_HAS_NOISE) for(i=0; i<(int)atshed->fra; ++i) band_energy_to_res(ats_sound, i); //NOW CHECK WHAT TO DO... if(sparams->amp > 0.) sflag |= SYNTH_DET; //deterministic synthesis only if(sparams->ramp > 0.) sflag |= SYNTH_RES; //residual synthesis only tl_sr = (float)TABLE_LENGTH / sparams->sr; //needed for ioscilator... nbp = get_nbp(timenv->curve); tdata = (TIME_DATA*)malloc(nbp * sizeof(TIME_DATA)); //g_print(" \nNPOINTS= %d \n", nbp); sparams->max_stretch=0.; todo=0; //We first must calculate data of each breakpoint timenv->dur=fabs(timenv->dur); //correct if negative for(i=0; i < nbp - 1; ++i){ //get the data from the time envelope and convert it to time cxval= timenv->dur * (get_x_value(timenv->curve,i)/100.); cyval= timenv->ymin + ((timenv->ymax - timenv->ymin) * (get_y_value(timenv->curve,i)/100.)); nxval= timenv->dur * (get_x_value(timenv->curve,i+1)/100.); nyval= timenv->ymin + ((timenv->ymax - timenv->ymin) * (get_y_value(timenv->curve,i+1)/100.)); //diff=0. is a special case we must take in account //here all we do is to set it to one millisecond (arbitrarly) difx= nxval - cxval; if(difx == 0.) difx=.001; dify= nyval - cyval; if(dify == 0.) dify=.001; //find out the max. stretching factor(needed to alocate the I/O buffer) if(fabs(difx) / fabs(dify) >= sparams->max_stretch) { sparams->max_stretch=fabs(difx) / fabs(dify); } //locate the frame for the beggining and end of segments if(i == 0){ if(dify < 0.) bframe= locate_frame((int)atshed->fra-1,cyval, dify); else bframe= locate_frame(0,cyval, dify); } eframe= locate_frame(bframe, nyval, dify); //collect the data to be used tdata[i].from=bframe; tdata[i].to =eframe; tdata[i].size= (int)(abs(eframe - bframe)) + 1; tdata[i].tfac=fabs(difx) / fabs(dify); todo+=tdata[i].size; //g_print("\n from frame=%d to frame=%d", bframe,eframe); bframe=eframe; //////////////////////////////////////////////////////// } //INITIALIZE PROGRESSBAR strcpy(str,"Writing File " ); strcat(str, out_tittle); StartProgress(str, TRUE); //ALLOCATE AND CLEAN AUDIO BUFFERS maxlen= (int)ceil(maxtim * sparams->sr * sparams->max_stretch); frbuf = (float *) malloc(maxlen * sizeof(float)); for(z = 0; z < maxlen; ++z) frbuf[z]=0.; obuf[0] = (mus_sample_t *)calloc(maxlen, sizeof(mus_sample_t)); switch(sflag) { //see which memory resources do we need and allocate them case SYNTH_DET: dospt = (float *) malloc( (int)atshed->par * sizeof(float)); for(z=0; z<(int)atshed->par; ++z) dospt[z]=0.; break; case SYNTH_RES: rospt = (float *) malloc((int)ATSA_CRITICAL_BANDS * sizeof(float)); rarray= (RANDI *) malloc((int)ATSA_CRITICAL_BANDS * sizeof(RANDI)); for(z=0; z<(int)ATSA_CRITICAL_BANDS; ++z) { res_band_centers[z]= res_band_edges[z]+((res_band_edges[z+1]-res_band_edges[z])*0.5); randi_setup(sparams->sr,res_band_edges[z+1]-res_band_edges[z],&rarray[z]); rospt[z]=0.; } break; case SYNTH_BOTH: dospt = (float *) malloc( (int)atshed->par * sizeof(float)); rarray= (RANDI *) malloc( (int)atshed->par * sizeof(RANDI)); for(z=0; z<(int)atshed->par; ++z) { rfreq=(ats_sound->frq[z][tdata[0].from] < 500.? 50. : ats_sound->frq[z][tdata[0].from] * bw); randi_setup(sparams->sr,rfreq,&rarray[z]); dospt[z]=0.; } break; } //NOW DO IT... written=0; stopper=FALSE; for(i = 0; i < nbp - 1; i++) { curr=tdata[i].from; for(j=0; j < tdata[i].size; j++) { next=(tdata[i].from < tdata[i].to ? curr+1 : curr-1 ); if(next < 0 || next >= (int)atshed->fra) break; dt=fabs(ats_sound->time[0][next] - ats_sound->time[0][curr]); frame_samps=dt * sparams->sr * tdata[i].tfac ; switch (sflag) { case SYNTH_DET: { //deterministic synthesis only for(x = 0; x < (int)atshed->par; x++) { synth_deterministic_only(ats_sound->amp[x][curr], ats_sound->amp[x][next], ats_sound->frq[x][curr] * sparams->frec, ats_sound->frq[x][next] * sparams->frec, frame_samps,x, dospt); } break; } case SYNTH_RES: { //residual synthesis only for(x = 0; x < (int)ATSA_CRITICAL_BANDS; x++) { synth_residual_only(ENG_RMS(ats_sound->band_energy[x][curr], atshed->ws), ENG_RMS(ats_sound->band_energy[x][next],atshed->ws) , res_band_centers[x],frame_samps,x,rospt,&rarray[x]); } break; } case SYNTH_BOTH: { //residual and deterministic synthesis for(x = 0; x < (int)atshed->par; x++) { rfreq=(ats_sound->frq[x][curr] < 500.? 50. : ats_sound->frq[x][curr]* bw); synth_both(ats_sound->amp[x][curr], ats_sound->amp[x][next], ats_sound->frq[x][curr] * sparams->frec, ats_sound->frq[x][next] * sparams->frec, frame_samps,x, dospt, ENG_RMS(ats_sound->res[x][curr] * sparams->ramp, atshed->ws), ENG_RMS(ats_sound->res[x][next] * sparams->ramp, atshed->ws), &rarray[x]); } break; } }//end switch for(z=0; z< maxlen; ++z) { //write and clean output buffer if(z < (int)frame_samps) { obuf[0][z] = MUS_FLOAT_TO_SAMPLE(frbuf[z]); written++; if (fabs(frbuf[z]) >= maxamp) {maxamp=fabs(frbuf[z]);} } frbuf[z]=0.; } mus_sound_write(ptout, 0, frame_samps-1, 1, obuf); if(stopper==TRUE) goto finish; ++nValue; UpdateProgress(nValue,todo); curr=(tdata[i].from < tdata[i].to ? curr+1 :curr-1 ); } } //CHANGE BREAKPOINT finish: free(frbuf); switch (sflag) { case SYNTH_DET: free(dospt); break; case SYNTH_RES: free(rospt); free(rarray); break; case SYNTH_BOTH: free(dospt); free(rarray); break; } mus_sound_close_output(ptout,written * mus_data_format_to_bytes_per_sample(format)); // *info=0; // strcat(info, "DONE OK...!!! MAXAMP= "); // sprintf(stamp,"%6.4f ",maxamp); // strcat(info, stamp); // Popup(info); free(obuf[0]); free(tdata); EndProgress(); strcpy(str, "DONE! MAXAMP= "); sprintf(stamp, "%6.4f", maxamp); strcat(str, stamp); Popup(str); }
void UnpackTask::Execute(void) { TaskBegin(this); // No items to process if(!archive || (Process.GetItemcount() == 0 && !fullUnpack)) { TaskEnd(this); return; } if(ProgressWindow::Instance()->IsRunning()) ProgressWindow::Instance()->SetTitle(tr("Calculating extract size...")); else StartProgress(tr("Calculating extract size...")); CopySize = GetUnpackSize(); ProgressWindow::Instance()->SetTitle(this->getTitle().c_str()); ProgressWindow::Instance()->SetCompleteValues(0, CopySize); string destPathSlash = (destPath.size() > 0 && destPath[destPath.size()-1] != '/') ? destPath + '/' : destPath; int result = 0; if(fullUnpack) { result = browser->ExtractAll(destPathSlash.c_str()); } else { for(int i = 0; i < Process.GetItemcount(); i++) { ArchiveFileStruct * currentItem = archive->GetFileStruct(Process.GetItemIndex(i)); if(currentItem->isdir) { int ret = browser->ExtractFolder(currentItem->filename, destPathSlash.c_str()); if(ret < 0) result = ret; } else { int ret = archive->ExtractFile(currentItem->fileindex, destPathSlash.c_str(), false); if(ret < 0) result = ret; } if(ProgressWindow::Instance()->IsCanceled()) { result = PROGRESS_CANCELED; break; } } } if((result < 0) && !Application::isClosing() && result != PROGRESS_CANCELED) { ThrowMsg(tr("Error:"), tr("Failed extracting some item(s).")); } TaskEnd(this); }
void CAccountManagerProcessingPage::OnStateChange( CAccountManagerProcessingPageEvent& WXUNUSED(event) ) { CMainDocument* pDoc = wxGetApp().GetDocument(); CWizardAttach* pWA = ((CWizardAttach*)GetParent()); wxDateTime dtStartExecutionTime; wxDateTime dtCurrentExecutionTime; wxTimeSpan tsExecutionTime; ACCT_MGR_RPC_REPLY reply; wxString strBuffer = wxEmptyString; std::string url = ""; std::string username = ""; std::string password = ""; bool bPostNewEvent = true; int iReturnValue = 0; unsigned int i; wxASSERT(pDoc); wxASSERT(wxDynamicCast(pDoc, CMainDocument)); switch(GetCurrentState()) { case ATTACHACCTMGR_INIT: pWA->DisableNextButton(); pWA->DisableBackButton(); StartProgress(m_pProgressIndicator); SetNextState(ATTACHACCTMGR_ATTACHACCTMGR_BEGIN); break; case ATTACHACCTMGR_ATTACHACCTMGR_BEGIN: SetNextState(ATTACHACCTMGR_ATTACHACCTMGR_EXECUTE); break; case ATTACHACCTMGR_ATTACHACCTMGR_EXECUTE: // Attempt to attach to the account manager. // Newer versions of the server-side software contain the correct // master url in the get_project_config response. If it is available // use it instead of what the user typed in. if (!pWA->project_config.master_url.empty()) { url = pWA->project_config.master_url; } else { url = (const char*)pWA->m_AccountManagerInfoPage->GetProjectURL().mb_str(); } if (pWA->project_config.uses_username) { username = (const char*)pWA->m_AccountInfoPage->GetAccountUsername().mb_str(); } else { username = (const char*)pWA->m_AccountInfoPage->GetAccountEmailAddress().mb_str(); } password = (const char*)pWA->m_AccountInfoPage->GetAccountPassword().mb_str(); // Wait until we are done processing the request. dtStartExecutionTime = wxDateTime::Now(); dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = 0; reply.error_num = ERR_RETRY; while ( !iReturnValue && ((ERR_IN_PROGRESS == reply.error_num) || (ERR_RETRY == reply.error_num)) && (tsExecutionTime.GetSeconds() <= 60) && !CHECK_CLOSINGINPROGRESS() ) { if (ERR_RETRY == reply.error_num) { pDoc->rpc.acct_mgr_rpc( url.c_str(), username.c_str(), password.c_str(), pWA->m_bCredentialsCached ); } dtCurrentExecutionTime = wxDateTime::Now(); tsExecutionTime = dtCurrentExecutionTime - dtStartExecutionTime; iReturnValue = pDoc->rpc.acct_mgr_rpc_poll(reply); IncrementProgress(m_pProgressIndicator); ::wxMilliSleep(500); wxEventLoopBase::GetActive()->YieldFor(wxEVT_CATEGORY_USER_INPUT); } if (!iReturnValue && !reply.error_num) { SetProjectAttachSucceeded(true); pWA->SetAttachedToProjectSuccessfully(true); } else { SetProjectAttachSucceeded(false); if ((ERR_NOT_FOUND == reply.error_num) || (ERR_DB_NOT_FOUND == reply.error_num) || (ERR_BAD_EMAIL_ADDR == reply.error_num) || (ERR_BAD_PASSWD == reply.error_num) ) { // For any logon error, make sure we do not attempt to use cached credentials // on any follow-ups. pWA->m_bCredentialsCached = false; SetProjectAccountNotFound(true); } else { SetProjectAccountNotFound(false); } strBuffer = pWA->m_CompletionErrorPage->m_pServerMessagesCtrl->GetLabel(); if ((HTTP_STATUS_INTERNAL_SERVER_ERROR == reply.error_num)) { strBuffer += _("An internal server error has occurred.\n"); } else { for (i=0; i<reply.messages.size(); i++) { strBuffer += wxString(reply.messages[i].c_str(), wxConvUTF8) + wxString(wxT("\n")); } } pWA->m_CompletionErrorPage->m_pServerMessagesCtrl->SetLabel(strBuffer); } SetNextState(ATTACHACCTMGR_CLEANUP); break; case ATTACHACCTMGR_CLEANUP: FinishProgress(m_pProgressIndicator); SetNextState(ATTACHACCTMGR_END); break; default: // Allow a glimps of what the result was before advancing to the next page. wxSleep(1); pWA->EnableNextButton(); pWA->EnableBackButton(); pWA->SimulateNextButton(); bPostNewEvent = false; break; } Update(); if (bPostNewEvent && !CHECK_CLOSINGINPROGRESS()) { CAccountManagerProcessingPageEvent TransitionEvent(wxEVT_ACCOUNTMANAGERPROCESSING_STATECHANGE, this); AddPendingEvent(TransitionEvent); } }
const u8 * NetReceiver::ReceiveData() { if(connection < 0) return NULL; if(filebuffer) free(filebuffer); filebuffer = NULL; filebuffer = (u8 *) malloc(filesize); if(!filebuffer) { ShowError(tr("Not enough memory.")); return NULL; } StartProgress(tr("Receiving file...")); u32 done = 0; u32 blocksize = 5*1024; char tmptxt[200]; snprintf(tmptxt, sizeof(tmptxt), "Incomming from: %s", incommingIP); int retries = 5; do { if(ProgressWindow::Instance()->IsCanceled()) { FreeData(); StopProgress(); ShowError(tr("Transfer cancelled.")); return NULL; } if (blocksize > filesize - done) blocksize = filesize - done; ShowProgress(done, filesize, tmptxt); int result = network_read(connection, filebuffer+done, blocksize); if(result < 0) { --retries; if(retries == 0) { FreeData(); StopProgress(); ShowError(tr("Transfer failed.")); return NULL; } } if(!result) { --retries; if(!retries) break; } done += result; } while(done < filesize); // finish up the progress FinishProgress(filesize); StopProgress(); if(done != filesize) { FreeData(); ShowError(tr("Filesize doesn't match.")); } char temp[50]; network_read(connection, (u8 *) temp, 49); temp[49] = 0; snprintf(FileName, sizeof(FileName), "%s", temp); if(UncompressData() == NULL) { FreeData(); ShowError(tr("Could not decompress the file.")); } return filebuffer; }
/** * 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; }