void DemoCollection::PopulateList( void ) {
	std::string fullPath = std::string( PATH_ROOT ) + ( IsRoot() ? "" : "/" + path );

	// populate the list of directories and demo files
	demoList.clear();

	if( !IsRoot() ) {
		// back dir ".."
		demoList.push_back( PATH_PARENT );
	}

	DirList dirList;
	dirList.clear();

	getFileList( dirList, fullPath, "/", true );
	for( DirList::iterator it = dirList.begin(); it != dirList.end(); ++it ) {
		std::string fullName = *it + "/";
		demoList.push_back( fullName );
	}

	// populate directories
	numDirectories = demoList.size();

	getFileList( demoList, fullPath, demoExtension.c_str(), true );
}
/** Extract training pairs from all sgf files found in the
specified directory.
@params path The directory to search for SGF files.
@params db The NNDatabase to store the training pairs in. */
void Urgency3BPNGoTrainer::extractPairsFromDirectory(string path, NNDatabase* db, const GoRankRange* rankRange /*=NULL*/) const
{
	LogWriter log;
	char buffer[200];
	if(_getcwd(buffer, 200)==NULL)
	{
		log.println("Error with _getcwd");
		return;
	}
	if(_chdir(path.c_str())==-1)
	{
		log.println("Error changing directory");
		return;
	}

	vector<string> files;
	getFileList(files, "*.mgt");
	getFileList(files, "*.sgf");


	if(files.size()<=0)
	{
		string message = "No appropriate files found in ";
		message+=path;
		log.println(message);
		// change back to original directory
		_chdir(buffer);
		return;
	}
	
	extractPairs(files, db, 0, 0, rankRange);
	// change back to original directory
	_chdir(buffer);
}
Exemple #3
0
void initResources(void)
{
	char **filenames;
	int i;

	numBackgrounds = numPlanets = numMusicFiles = 0;

	filenames = getFileList("gfx/backgrounds", &numBackgrounds);
	backgrounds = malloc(sizeof(char*) * numBackgrounds);

	for (i = 0 ; i < numBackgrounds ; i++)
	{
		backgrounds[i] = malloc(sizeof(char) * MAX_FILENAME_LENGTH);
		sprintf(backgrounds[i], "gfx/backgrounds/%s", filenames[i]);

		SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "Adding AUTO %s", filenames[i]);
		
		free(filenames[i]);
	}

	free(filenames);

	filenames = getFileList("gfx/planets", &numPlanets);
	planets = malloc(sizeof(char*) * numPlanets);

	for (i = 0 ; i < numPlanets ; i++)
	{
		planets[i] = malloc(sizeof(char) * MAX_FILENAME_LENGTH);
		sprintf(planets[i], "gfx/planets/%s", filenames[i]);
		
		SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "Adding AUTO %s", filenames[i]);
		
		free(filenames[i]);
	}

	free(filenames);

	filenames = getFileList("music/battle/", &numMusicFiles);

	musicFiles = malloc(sizeof(char*) * numMusicFiles);

	for (i = 0 ; i < numMusicFiles ; i++)
	{
		musicFiles[i] = malloc(sizeof(char) * MAX_FILENAME_LENGTH);
		sprintf(musicFiles[i], "music/battle/%s", filenames[i]);
		
		SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "Adding AUTO %s", filenames[i]);
		
		free(filenames[i]);
	}

	free(filenames);
}
Exemple #4
0
	// function that reads in data from file into data maps
	static bool readFromFile(DataManager<T>& data, 
						     const std::string& dataPath) {
		// declare vector for saving file names
		std::vector<std::string> fileList;
        try {
			// get file list
			getFileList(fileList, dataPath);
			// count number of files
			size_t noOfFiles{fileList.size()};
			// loop through all files
			for (size_t i{}; i < noOfFiles; ++i) {
				// declare experiment object
				Experiment<T> userExperiment;
				// pass file name to experiment read from file function
				userExperiment.readFromFile(fileList[i]);
				// insert data into maps
				data.insertExperiment(userExperiment);
			}  
        }
        catch (const std::invalid_argument& e) {
            ErrorMsg::print(e.what());
            return false;
        }
        return true;
	}	
Exemple #5
0
void SelectFlashPage::reload() // TODO: we could do that more efficient :P
{
	fileList.clear();

	QDateTime time_now = QDateTime::currentDateTime();
	int row = 0;
	QList<QFileInfo> allFiles;
	getFileList(&allFiles);

	for(QList<QFileInfo>::const_iterator itr = allFiles.begin(); itr != allFiles.end(); itr++, row++)
	{
		QDateTime lastChanged = itr->lastModified();
		if( lastChanged.daysTo(time_now) == 0 )
			if( lastChanged.secsTo(time_now) <= 3600 ) { // TODO: make 3600 flexible
				int minutesLeft = (int) lastChanged.secsTo(time_now) / 60;
				if( minutesLeft < 1 ) {
					fileList.addItem(
					QString("Still loading: %1")
					.arg(itr->absoluteFilePath())
					);
					puts("a");
					fileList.item(row)->setFlags(fileList.item(row)->flags() ^ Qt::ItemIsEnabled);
					puts("c");
				}
				else
					fileList.addItem(
					QString("%1 Minutes ago: %2")
					.arg(minutesLeft)
					.arg(itr->absoluteFilePath())
					);

		}

	}
}
void pslCopyInClones(char *listFile, char *partDir, char *outName)
/* Copy in the .psl files corresponding to the clones named in listFile. */
{
struct slName *inList, *inEl;
FILE *out = mustOpen(outName, "w");
struct psl *psl;
int pslCount = 0;
int fileCount = 0;

pslWriteHead(out);
inList = getFileList(listFile, partDir);
for (inEl = inList; inEl != NULL; inEl = inEl->next)
    {
    char *inName = inEl->name;
    struct lineFile *lf = pslFileOpen(inName);
    ++fileCount;
    while ((psl = pslNext(lf)) != NULL)
	{
	pslTabOut(psl, out);
	pslFree(&psl);
	++pslCount;
	}
    lineFileClose(&lf);
    }
printf("%d psls in %d files written to %s\n", pslCount, fileCount, outName);
fclose(out);
}
Exemple #7
0
    bool getFileList(std::string path, std::string mask, bool case_sensitive, std::vector<std::string> & tabfiles, bool rec, bool addFiles, bool addDir)
        {
        path = mtools::toUtf8(mtools::trailingSlash(path, true));
        dirent** list = nullptr;
        int nb = fl_filename_list(path.c_str(), &list);
        if (nb < 0) return false;
        for (int i = 0; i < nb; i++)
            {
            std::string f = mtools::toIso8859(list[i]->d_name);
            if (( f == std::string("./")) || (f == std::string("../"))) continue;

            if (!fl_filename_isdir((path + list[i]->d_name).c_str()))
                {
                if ((addFiles) && (mtools::matchFileMask(f, mask,case_sensitive))) tabfiles.push_back(f);
                }
            else
                {
                if (addDir) tabfiles.push_back(f);
                if (rec)
                    {
                    size_t pos = tabfiles.size();
                    if (!getFileList(path + list[i]->d_name, mask, case_sensitive, tabfiles, rec, addFiles, addDir)) { fl_filename_free_list(&list, nb); return false; }
                    for (size_t j = pos; j < tabfiles.size(); j++) { tabfiles[j] = f + tabfiles[j]; }
                    }
                }
            }
        fl_filename_free_list(&list, nb);
        return true;
        }
Exemple #8
0
/*
 * Load Train Data (Signatures and respective names) from a directory
 * Returns the number of signatures read
 * TODO: make this windows compatible
 */
TrainData *Database::loadTrainDataFromDir(string dir, int *n)
{
	Sig sig;
	vector<string> files = vector<string>();
	string fname, temp;
	char buf[1024];
	unsigned int ii;
	TrainData *data;

    getFileList(dir, files);
    
    data = new TrainData [files.size()];
    getcwd(buf, 1024);		// save current dir
//    cout << "Changing CWD to " << dir << "." << endl;
    chdir(dir.c_str());		// change current dir to data dir
    for (ii = 0; ii < files.size(); ii++) {
        fname = files[ii];
//        cout << "Reading " << fname << "." << endl;
        sig.load(fname);
        data[ii].name = filenameToName(files[ii]);	// Get Name from sig file
        data[ii].sigArr = sig.toArray();			// convert sig to array
        data[ii].value = (double) tableLookup(data[ii].name);	/* get value
        														 * (table index)
        														 */
    }
//    cout << "Back to previous CWD." << endl;
    chdir(buf);			// change back to original working dir
//    cout << "Read a total of " << ii << " files." << endl;
    *n = ii;
    return data;
}
Exemple #9
0
void ofxGuiFiles::init(int id, string name, int x, int y, int width, int height, string value, string path, string suffix)
{
	int	textHeight	= (name == "") ? 0 : mGlobals->mParamFontHeight;
	
	mParamId		= id;
	mParamName		= name;
	
	mObjX			= x; 
	mObjY			= y;
	
	mPath			= path;
	mSuffix			= suffix;

	int maxWidth	= getFileList();
	
	if(maxWidth > width)
		width = maxWidth;
	
	mObjWidth		= width;
	mObjHeight		= textHeight + height;
			
	setValue(value);
	setControlRegion(0, textHeight, width, height);

	// used for drawing the background state
	mState = 0;
	num_states = 3;
}
Exemple #10
0
 bool getFileList(std::wstring & path, std::wstring & mask, bool case_sensitive, std::vector<std::wstring> & tabfiles, bool rec, bool addFiles, bool addDir)
     {
     std::vector<std::string> tab;
     bool r = getFileList(toString(path,enc_iso8859), toString(mask,enc_iso8859), case_sensitive, tab, rec, addFiles, addDir);
     for (auto it = tab.begin(); it != tab.end(); it++) { tabfiles.push_back(toWString(*it,enc_iso8859)); }
     return r;
     }
Exemple #11
0
 size_t copyFiles(std::wstring sourcepath, std::wstring destpath, std::wstring mask, bool case_sensitive, bool rec, bool overwrite)
     {
     #if defined (_MSC_VER)
     int copied = 0;
     if ((sourcepath.length() != 0) && (sourcepath[sourcepath.length() - 1] != L'\\'))  { sourcepath += L"\\"; }
     if ((destpath.length() != 0) && (destpath[destpath.length() - 1] != L'\\'))        { destpath += L"\\"; }
     std::vector<std::wstring> tabsource;
     if (getFileList(sourcepath, mask, case_sensitive, tabsource, rec, true, rec) == false) { return(-1); }
     for (std::vector<std::wstring>::iterator it = tabsource.begin(); it != tabsource.end(); it++)
         {
         if ((it->length() != 0) && ((*it)[it->length() - 1] == L'\\'))
             {
             if (CreateDirectoryW((destpath + (*it)).c_str(), NULL) == 0) { if (GetLastError() != ERROR_ALREADY_EXISTS) { return -1; } }
             }
         else
             {
             bool fie = false; if (overwrite == false) { fie = true; }
             if (CopyFileW((sourcepath + (*it)).c_str(), (destpath + (*it)).c_str(), fie) == 0) { return -1; }
             }
         copied++;
         }
     return copied;
     #else
     // TODO
     #endif
     return -1;
     }
void ModelsDataSource::UpdateModelsList( void )
{
	// clear the list
	modelsList.clear();

	// scan for directories, storing results in temporary list
	ModelsList tempList;
	getFileList( tempList, "models/players", "/" );

	// now scan for proper models:
	// we need the main model file, animation config and default skin
	for( ModelsList::const_iterator it = tempList.begin(); it != tempList.end(); ++it ) {
		size_t i;
		static const std::string mustHaveFiles[] = { "tris.iqm", "animation.cfg", "default.skin" };
		static const size_t numMustHaveFiles = sizeof( mustHaveFiles ) / sizeof( mustHaveFiles[0] );

		std::string basePath = std::string( "models/players/" ) + *it + "/";
		for( i = 0; i < numMustHaveFiles; i++ ) {
			std::string filePath = basePath + mustHaveFiles[i];
			if( trap::FS_FOpenFile( filePath.c_str(), NULL, FS_READ ) < 0 ) {
				break;
			}
		}

		// we didn't find all files we need, ignore
		if( i != numMustHaveFiles ) {
			continue;
		}

		modelsList.push_back( *it );
	}

	NotifyRowAdd( TABLE_NAME, 0, modelsList.size() );
}
/******************************************************************************
* OnManufacturingGrid
*/
void CCEtoODBDoc::OnManufacturingGrid() 
{
   CExtent extents;
   FileStruct* pcbFile = NULL;
   
   for (POSITION pos=getFileList().GetHeadPosition(); pos != NULL;)
   {
      FileStruct *file = getFileList().GetNext(pos);

      if (file->getBlockType() == BLOCKTYPE_PCB && file->isShown())
      {
         pcbFile = file;
         extents = calcFileOutlineExtents(pcbFile);
         break;
      }
   }

   if (pcbFile == NULL)
   {
      ErrorMessage("No PCB File is Visible", "Manufacturing Grid");
      return;
   }

   if (!extents.isValid())
   {
      ErrorMessage("Using Page Size for Manufacturing Grid.\nCancel and set Primary Board Outline is recommended.", "No Primary Board Outline Found");
      extents.update(getSettings().getXmin(),getSettings().getYmin());
      extents.update(getSettings().getXmax(),getSettings().getYmax());
   }

   PCB_Grid dlg;
   dlg.doc = this;
   dlg.pcbFile = pcbFile;
   dlg.m_board.Format("Board Name : %s", pcbFile->getName());
   int decimals = GetDecimals(getSettings().getPageUnits());
   dlg.left   = extents.getXmin();
   dlg.right  = extents.getXmax();
   dlg.bottom = extents.getYmin();
   dlg.top    = extents.getYmax();
   dlg.sizeX = dlg.right - dlg.left;
   dlg.sizeY = dlg.top - dlg.bottom;
   dlg.m_size.Format("Board Size: Width=%.*lg, Height=%.*lg",
      decimals, dlg.sizeX * Units_Factor(UNIT_INCHES,getSettings().getPageUnits()), 
      decimals, dlg.sizeY * Units_Factor(UNIT_INCHES,getSettings().getPageUnits()) );

   dlg.DoModal(); 
}
GameTypesDataSource::GameTypesDataSource() : Rocket::Controls::DataSource( "gametypes_source" ) {
	std::vector<std::string> listedGameTypes;
	getFileList( listedGameTypes, "progs/gametypes", ".gt" );

	for( std::vector<std::string>::const_iterator it = listedGameTypes.begin();
		 it != listedGameTypes.end(); ++it ) {
		if( std::find_if( gameTypes.begin(), gameTypes.end(), std::bind2nd( cmp_gametypes_by_id(), *it ) ) == gameTypes.end() ) {
			gametype gt( *it );

			if( gt.name == "tutorial" ) {
				// HACK
				continue;
			}

			std::string filepath = std::string( "progs/gametypes" ) + "/" + gt.name + ".gtd";
			int filenum, filelen;

			filelen = trap::FS_FOpenFile( filepath.c_str(), &filenum, FS_READ );
			if( filenum ) {
				if( filelen > 0 ) {
					char *buffer = new char[filelen + 1], *end = buffer + filelen;
					trap::FS_Read( buffer, filelen, filenum );
					buffer[filelen] = '\0';

					// parse title and description
					char *ptr = buffer;

					// parse single line of title
					while( ptr ) {
						const char *token = COM_ParseExt( &ptr, true );
						if( *token ) {
							gt.title.clear();
						}
						while( *token ) {
							gt.title += ( gt.title.empty() ? "" : " " );
							gt.title += token;
							token = COM_ParseExt( &ptr, false );
						}
						break;
					}

					// the rest is description
					while( ptr && ptr < end && ( *ptr == '\n' || *ptr == '\r' || *ptr == ' ' ) ) ptr++;
					if( ptr && ptr != end ) {
						gt.description = ptr;
					}

					delete[] buffer;
				}

				trap::FS_FCloseFile( filenum );
			}

			gameTypes.push_back( gt );
		}
	}
}
void testDir( std::string path )
{
	getFileList(path);

	std::set< std::string >::iterator it = _files.begin();
	for( ; it != _files.end(); it++ )
	{
		findImageContext( path+"/"+*it );
	}
}
Exemple #16
0
bool Info::init(const String &path) {
	_file = cocos2d::unzOpen2_64((void *)&path, &s_fileApi.pathFunc);
	if (_file) {
		_manifest = getFileList(_file);
		_rootFile = getRootPath();
		_rootPath = filepath::root(_rootFile);

		processPublication();
	}
	return valid();
}
void StreamCache::PurgeCache( void )
{
	std::string cacheDir( WSW_UI_STREAMCACHE_DIR );

	std::vector<std::string> cachedFiles;
	getFileList( cachedFiles, cacheDir, "*", true );

	for( std::vector<std::string>::const_iterator it = cachedFiles.begin(); it != cachedFiles.end(); ++it ) {
		trap::FS_RemoveFile( (cacheDir + "/" + *it).c_str() );
	}
}
void
TodaysPlanWorkoutDownload::refreshClicked()
{
    // reset download information
    status->setText("");
    downloads = fails = 0;
    download->show();
    close->show();
    files->clear(); // delete existing entries
    QString error;

    // check period - download is only possible for future workouts !
    if (from->date() < QDate::currentDate()) {
        QMessageBox::warning(this, tr("Today's Plan Workout Download"), QString(tr("You can only download future workouts, 'From' will be adjusted to current date")));
        from->setDate(QDate::currentDate());
    }
    if (from->date() > to->date()) {
        QMessageBox::warning(this, tr("Today's Plan Workout Download"), QString(tr("Invalid date range, please check your input.")));
        return;
    }

    QList<TodaysPlanWorkoutListEntry*> workouts = getFileList(error, from->dateTime(), to->dateTime());
    if (error != "") {
        QMessageBox::warning(this, tr("Today's Plan Workout Download"), QString(tr("The following error occured: %1").arg(error)));
        return;
    }


    foreach(TodaysPlanWorkoutListEntry *item, workouts) {

       QTreeWidgetItem *add = new QTreeWidgetItem(files->invisibleRootItem());
       add->setFlags(add->flags() | Qt::ItemIsEditable);

       // selector
       QCheckBox *checkBox = new QCheckBox("", this);
       checkBox->setChecked(true);
       files->setItemWidget(add, 0, checkBox);

       add->setText(1, item->planDate.toString(tr("dd MMM yyyy")));
       add->setText(2, item->description);
       add->setText(3, QString::number(item->tScore));
       add->setText(4, time_to_string_minutes(item->duration));

       // interval action
       add->setText(5, tr("Download"));

       // hide away the id
       add->setText(6, QString("%1").arg(item->workoutId));
    }
void pslGlueRna(char *listFile, char *partDir, char *pslName, char *gluName)
/* Reduce a psl files for only the gluing mRNA/EST components. */
{
FILE *pslOut;
FILE *gluOut;
struct psl *pslList = NULL, *psl, *nextPsl;
struct psl *localList = NULL;
int glueCount = 0;
int pslCount = 0;
struct slName *inList, *inEl;

inList = getFileList(listFile, partDir);
for (inEl = inList; inEl != NULL; inEl = inEl->next)
    {
    char *inName = inEl->name;
    struct lineFile *lf = pslFileOpen(inName);
    while ((psl = pslNext(lf)) != NULL)
	{
	slAddHead(&pslList, psl);
	++pslCount;
	}
    lineFileClose(&lf);
    }
slSort(&pslList, pslCmpQuery);

pslOut = mustOpen(pslName, "w");
gluOut = mustOpen(gluName, "w");
pslWriteHead(pslOut);

/* Chop this up into chunks that share the same query. */
for (psl = pslList; psl != NULL; psl = nextPsl)
    {
    nextPsl = psl->next;
    if (localList != NULL)
	{
	if (!sameString(localList->qName, psl->qName))
	    {
	    glueCount += output(pslOut, gluOut, &localList);
	    localList = NULL;
	    }
	}
    slAddHead(&localList, psl);
    }
glueCount += output(pslOut, gluOut, &localList);
printf("Got %d gluing mRNAs out of %d psls in %d bundles %d ltot %d mtot to %s\n", 
	glueCount, pslCount, outCount, ltot, mtot, gluName);
fclose(pslOut);
fclose(gluOut);
}
Exemple #20
0
void
RemoteHandler::
dispatch(char* command){
	char* opcode = strtok(command, "|\n");
	if (strcmp(opcode, "getFileList") == 0)
		getFileList();
	else if (strcmp(opcode, "getFile") == 0)
		getFile(strtok(NULL, "|\n"));
	else if (strcmp(opcode, "changeDir") == 0)
		changeDir(strtok(NULL, "|\n"));
	else if (strcmp(opcode, "deleteFile") == 0)
		deleteFile(strtok(NULL, "|\n"));
	else if (strcmp(opcode, "closeHandler") == 0)
		closeHandler();
	else
		cout << "else?? " << opcode;

}
Exemple #21
0
Fichier : sr.cpp Projet : koturn/sr
/*!
 * @brief プログラムのエントリポイント
 * @param [in] argc コマンドライン引数の数
 * @param [in] argv コマンドライン引数
 * @return  終了ステータス
 */
int main(int argc, char *argv[])
{
  std::string lang = DEFAULT_LANG;
  int remidx = parseArguments(argc, argv, lang);
  if (argc == remidx) {  // 引数のチェック
    std::cerr << "Invalid argument" << std::endl;
    showUsage(argv[0], EXIT_FAILURE);
  }

  try {
    std::vector<std::string> arg_list;
    for (int i = remidx; i < argc; i++) {
      arg_list.push_back(argv[i]);
    }
    clx::http session(clx::uri::encode(URL_HOST), HTTP_PORT);
    for (std::vector<std::string>::iterator arg = arg_list.begin(); arg != arg_list.end(); ++arg) {
      if (isDirectory(*arg)) {  // ディレクトリだった場合
        std::vector<std::string> file_list = getFileList(*arg);
        for (std::vector<std::string>::iterator fn = file_list.begin(); fn != file_list.end(); ++fn) {
          if (checkSuffix(*fn, "wav")) {
            std::cout << *fn << " ... ";
            try {
              speachToText(session, lang, *fn, *fn + ".txt");
              std::cout << "Proccessed" << std::endl;
            } catch (const char *errmsg) {
              std::cerr << errmsg << std::endl;
            }
          }
        }
      } else {  // ファイルだった場合
        std::cout << *arg << " ... ";
        try {
          speachToText(session, lang, *arg, *arg + ".txt");
          std::cout << "Proccessed" << std::endl;
        } catch (const char *errmsg) {
          std::cerr << errmsg << std::endl;
        }
      }
    }
  } catch (clx::socket_error &e) {
    std::cerr << e.what() << std::endl;
  }
  return EXIT_SUCCESS;
}
Exemple #22
0
static void loadFighterDefList(char *dir)
{
	char **filenames;
	char path[MAX_FILENAME_LENGTH];
	int count, i;

	filenames = getFileList(dir, &count);

	for (i = 0 ; i < count ; i++)
	{
		sprintf(path, "%s/%s", dir, filenames[i]);

		loadFighterDef(path);

		free(filenames[i]);
	}

	free(filenames);
}
int main(int argc, char* argv[])
{
    fileList *mylist;

    char name[1024] = "/home/shell-s-source/dirinfo/";

    if(argc == 2)
        strcpy(name, argv[1]);
    else
        strcpy(name, "/home/shell-s-source/dirinfo/");

    mylist = getFileList(name);
    strcpy(mylist->file.fullName, name);

    showAllNode(mylist);
    printf("\n");

    return 0;
}
void showAllNode(fileList *head)
{
    fileList *temp;

    int i = 0, j = 0;
    fileList *headArray[1024];

    if(head == NULL)
        return;

    printf("%s", head->file.fullName);
    printf("\n");

    temp = head->nextfile;

    while(temp)
    {
        if(strcmp(temp->file.type, "file") == 0)
        {
            printf("file:%s\n", temp->file.fullName);
        }else{
            if(i >= 1024)
            {
                printf("there are too many directory\n");
                return;
            }

            headArray[i] = getFileList(temp->file.fullName);
            strcpy(headArray[i]->file.fullName, temp->file.fullName);
            i++;

        }

        temp = temp->nextfile;
    }

    for(j = 0; j < i; j++)
            showAllNode(headArray[j]);

    return;
}
Exemple #25
0
UT_Error IE_Exp_EPUB::compress()
{

    GsfInfile* oebpsDir = gsf_infile_stdio_new(
            UT_go_filename_from_uri(m_oebpsDir.c_str()), NULL);

    if (oebpsDir == NULL)
    {
        UT_DEBUGMSG(("RUDYJ: Can`t open temporary OEBPS directory\n"));
        return UT_ERROR;
    }

    std::vector<std::string> listing = getFileList(
            UT_go_filename_from_uri(m_oebpsDir.c_str()));
    for (std::vector<std::string>::iterator i = listing.begin(); i
            != listing.end(); i++)
    {
        GsfOutput* item = gsf_outfile_new_child(GSF_OUTFILE(m_oebps),
                (*i).c_str(), FALSE);
	std::string fullPath = m_oebpsDir + G_DIR_SEPARATOR_S + *i;
        GsfInput* file = UT_go_file_open(fullPath.c_str(), NULL);

        if (file == NULL)
        {
            UT_DEBUGMSG(("RUDYJ: Can`t open file\n"));
            return UT_ERROR;
        }

        gsf_output_seek(item, 0, G_SEEK_SET);
        gsf_input_seek(file, 0, G_SEEK_SET);
        gsf_input_copy(file, item);
        gsf_output_close(item);
        // Time to delete temporary file
        UT_go_file_remove(fullPath.c_str(), NULL);
    }

    UT_go_file_remove((m_oebpsDir + G_DIR_SEPARATOR_S + "index.xhtml_files").c_str(), NULL);
    UT_go_file_remove(m_oebpsDir.c_str(), NULL);
	return UT_OK;
}
bool ofxGuiFiles::update(int id, int task, void* data, int length)
{
    bool handled = false;

    if(id == mParamId)
    {
        if(task == kofxGui_Set_Bool)
        {
            if((*(bool*)data))
                getFileList();

        }
        else if(task == kofxGui_Set_String)
        {
            setValue((*(string*)data));
        }

        handled = true;
    }

    return handled;
}
Exemple #27
0
void loadCapitalShipDefs(void)
{
	char **filenames;
	char path[MAX_FILENAME_LENGTH];
	int count, i;

	memset(&defHead, 0, sizeof(Entity));
	defTail = &defHead;

	filenames = getFileList("data/capitalShips", &count);

	for (i = 0 ; i < count ; i++)
	{
		sprintf(path, "data/capitalShips/%s", filenames[i]);

		loadCapitalShipDef(path);

		free(filenames[i]);
	}

	free(filenames);
}
Exemple #28
0
void ofxGuiFiles::init(/*int id, */string name, int x, int y, int width, int height, string value, string path, string suffix)
{
	int	textHeight	= (name == "") ? 0 : mGlobals->mParamFontHeight;
	
	/*mParamId		= id;*/
	mParamName		= name;
	
	mObjX			= x; 
	mObjY			= y;
	
	mPath			= path;
	mSuffix			= suffix;

	int maxWidth	= getFileList();
	
	if(maxWidth > width)
		width = maxWidth;
	
	mObjWidth		= width;
	mObjHeight		= textHeight + height;
			
	setValue(value);
	setControlRegion(0, textHeight, width, height);
}
Exemple #29
0
int main (int argc, const char * argv[])
{
  
    
    mainWindow = new sf::RenderWindow(sf::VideoMode(1440,900), "Alpha & Omega",sf::Style::Fullscreen);
   
    ezCursor cursor;
    std::vector<std::string> klm;
    getFileList(getResourcePath(0), "ttf", klm);
    
    
   // std::cout<<klm.size()<<std::endl;
    
    sf::Texture texture;
    if (!texture.loadFromFile(getResourcePath(1) + "davsan.png"))
    	return EXIT_FAILURE;
    
    
    sf::Texture background;
    if(!background.loadFromFile(getResourcePath(1)+"ConfusedOrc.png"))
        return EXIT_FAILURE;
    
    
    
    sf::Sprite backSprite(background);
    backSprite.setPosition(0, 0);
    
    sf::Sprite back1(background);
    back1.setPosition(backSprite.getPosition().x+backSprite.getGlobalBounds().width, backSprite.getPosition().y);
    
    
    sf::Sprite back2(background);
    back2.setPosition(back1.getPosition().x+back1.getGlobalBounds().width, back1.getPosition().y);
    
    sf::Sprite sprite(texture);
    sprite.setPosition(720, 450);

    sf::Clock frameClock;
    
    
    
    
    int i=0,j=0;
 

    sf::View view = mainWindow->getView();
    
    sf::View newView(sf::FloatRect(0,0,1440,900));
    
    mainWindow->setFramerateLimit(90);
    while (mainWindow->isOpen())
    {
        
    	// Process events
        mainWindow->clear();
    	sf::Event event;
    	while (mainWindow->pollEvent(event))
    	{
    		// Close window : exit
    		if (event.type == sf::Event::Closed)
    			mainWindow->close();
    
    		// Escape pressed : exit
    		if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)
    			mainWindow->close();
            
            if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Left)
            {
                newView.move(-10,0);
                
            }	
            if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Right)
            {
                newView.move(10,0);
            }
            if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Up)
            {
                newView.move(0,-10);
            }
            if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Down)
            {
             
                newView.move(0,10);
                
            }
        }
        //sf::FloatRect rect(sf::Vector2f(view.getCenter() - sf::Vector2f(view.getSize().x/2, view.getSize().y/2)), sf::Vector2f(view.getSize()));
        //sprite.setPosition(rect.left+(rect.width/2), rect.top+(rect.height/2));
    
        
        
        

        
       // sf::Vector2f paka=mainWindow->convertCoords(sf::Vector2i(ty,kl), view);
      //  sf::Mouse::setPosition(sf::Vector2i(paka.x,paka.y));
        if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
        {
            std::cout<<"Mouse = "<<cursor.getPosition(newView).x<<"   "<<cursor.getPosition(newView).y<<std::endl;   
            std::cout<<"img  = "<<back2.getGlobalBounds().left<<"   "<<back2.getGlobalBounds().top<<std::endl;
        }
        
        
        
        //sprite.move(8.f*frameClock.getElapsedTime().asSeconds(),0.f*frameClock.getElapsedTime().asSeconds());
        
        if(frameClock.getElapsedTime().asMilliseconds() >= 10000/100)
        {
            frameClock.restart();   
            i++;
            if(i==11)
            {
                j++;
                i=0;
                
            }
            if(j==5)
            {
                j=0;
            }
                
            
        }
        
   
      //  std::cout<<i<<"  "<<j<<std::endl;
        sprite.setTextureRect(sf::IntRect(100*i,120*0,100,120));
        //sprite2.setTextureRect(sf::IntRect(100*i,120*0,100,120));

    	// Clear screen
    	
        mainWindow->setView(newView);
        mainWindow->draw(backSprite);
        
        mainWindow->draw(back1);
    
        mainWindow->draw(back2);
    	// Draw the sprite
    
    	
    
        mainWindow->setView(mainWindow->getDefaultView());
        mainWindow->draw(sprite);
        cursor.render();
        
        
        
    	mainWindow->display();
    }

	return EXIT_SUCCESS;
}
// ./client_PFS <Client Name> <Server IP> <Server Port> <Private Key> <Certificate of this Client> <CA Cert>
int main(int argc, char const *argv[])
{
    const char *keyName = argv[4]; 
    const char *certName = argv[5];
    const char *CACert = argv[6];
    // ssl setup
    SSL_CTX *ctx;
    SSL *clieSSL, *p2pSSL;
    SSL_METHOD *meth;
    // Load encryption & hashing algorithms for the SSL program
    SSL_library_init();
    // Load the error strings for SSL & CRYPTO APIs
    SSL_load_error_strings();
    // Create an SSL_METHOD structure (choose an SSL/TLS protocol version)
    meth = SSLv3_method();
    // Create an SSL_CTX structure
    ctx = SSL_CTX_new(meth);
    // Create an SSL_CTX structure
    ctx = SSL_CTX_new(meth);

    if(ctx == NULL)
    {
        ERR_print_errors_fp(stderr);
        exit(1);
    }
    // Load the client certificate into the SSL_CTX structure
    if(SSL_CTX_use_certificate_file(ctx, argv[5], SSL_FILETYPE_PEM) <= 0)
    {
        ERR_print_errors_fp(stderr);
        exit(1);
    }
    // Load the private-key corresponding to the client certificate
    if(SSL_CTX_use_PrivateKey_file(ctx, argv[4], SSL_FILETYPE_PEM) <= 0)
    {
        ERR_print_errors_fp(stderr);
        exit(1);
    }
    // Check if the client certificate and private-key matches
    if(!SSL_CTX_check_private_key(ctx))
    {
        printf("Private key does not match the certificate public key\n");
        exit(1);
    }   
    // Load the RSA CA certificate into the SSL_CTX structure
    // This will allow this client to verify the server's certificate
    if(!SSL_CTX_load_verify_locations(ctx, argv[6], NULL))
    {
        ERR_print_errors_fp(stderr);
        exit(1);
    }
    // Set flag in context to require peer (server) certificate verification
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
    SSL_CTX_set_verify_depth(ctx, 1);

	struct sockaddr_in remoteAddr, p2pAddr;
	int clieSock;   // for connecting to server
	int p2pSock;    // for p2p transfer
    int peerSock = -1;

	// setup sockaddr
	bzero(&remoteAddr, sizeof(remoteAddr));
	remoteAddr.sin_family = AF_INET;
	remoteAddr.sin_addr.s_addr = inet_addr(argv[2]);
	remoteAddr.sin_port = htons(atoi(argv[3]));

	bzero(&p2pAddr, sizeof(p2pAddr));
	p2pAddr.sin_family = AF_INET;
	p2pAddr.sin_addr.s_addr = inet_addr(argv[2]);
	p2pAddr.sin_port = htons((int)(9500 + (argv[1][0] - 'A')));

	// create socket
	clieSock = socket(AF_INET, SOCK_STREAM, 0);
	p2pSock = socket(AF_INET, SOCK_STREAM, 0);
	if(clieSock < 0 || p2pSock < 0){
		perror("socket creation");
		exit(1);
	}

	if (fcntl(p2pSock, F_SETFL, O_NDELAY)<0)
    {
        perror("error set non-block for client-p2p socket");
        exit(1);
    }
    // bind socket with p2p port
	if(bind(p2pSock, (struct sockaddr *)&p2pAddr, sizeof(p2pAddr)) < 0){
		perror("bind socket");
		exit(1);
	}

	// listen on the p2p port
	if(listen(p2pSock, MAX) < 0){
		perror("listen on the port");
		exit(1);
	}

	// connect to server
	if(connect(clieSock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
		perror("connect to server");
		exit(1);
	}

    // create ssl struct
    clieSSL = SSL_new(ctx);
    // Assign the socket into the SSL structure
    SSL_set_fd(clieSSL, clieSock);
    // Perform SSL Handshake on the SSL client
    if(SSL_connect(clieSSL) == 1)
    {
        printf("ssl connected to server\n");
    }

    // set sockets to non-block mode
    if (fcntl(clieSock, F_SETFL, O_NDELAY) < 0)
    {
        perror("error set non-block for client-server socket");
        exit(1);
    }
	// get local file info list
    FileList masterList;
    Packet localFileListPacket, sendCmdPacket, recvPacket;
    localFileListPacket.type = 1;
    sendCmdPacket.type = 0;
	
    struct stat st;
	getFileList(&(localFileListPacket.fileList));
	strcpy(localFileListPacket.fileList.owner, argv[1]);
    strcpy(sendCmdPacket.fileList.owner, argv[1]);
	int i;
	for(i = 0; i < localFileListPacket.fileList.num; i++)
    {
		stat(localFileListPacket.fileList.files[i].fileName, &st);
		localFileListPacket.fileList.files[i].fileSize = st.st_size;
		strcpy(localFileListPacket.fileList.files[i].fileOwner, argv[1]);
		strcpy(localFileListPacket.fileList.files[i].ownerIP, argv[2]);
		localFileListPacket.fileList.files[i].ownerPort = 9500 + (argv[1][0] - 'A');
	}
	printFileList(&(localFileListPacket.fileList));

	// upload file list to server
	int nbytes;
    nbytes = SSL_write(clieSSL, &localFileListPacket, sizeof(Packet));
	if(nbytes < 0){
		perror("init upload");
		exit(1);
	}

	char command[128];
    while(1)
    {
        printf("Input command: ls, get, exit\n");

        while(!kbhit())
        {
            // no user input, recv from server
            nbytes = SSL_read(clieSSL, &recvPacket, sizeof(Packet));
            if (nbytes > 0)
            {
                if (recvPacket.type == 0)
                {
                    if (strcmp(recvPacket.cmd, "Client existed")==0)
                    {
                        // client already existed, quit
                        printf("Client %s already registered with server, exiting...\n", argv[1]);
                        exit(1);
                    }
                }
                else
                {// recv file list
                    printf("Received master file list from server\n");
                    copyFileList(&(masterList), &(recvPacket.fileList));
                    printFileList(&(masterList));
                }
                printf("input command: ls, get, exit\n");
            }
            // try to accept on p2p listen socket
            peerSock = accept(p2pSock, NULL, sizeof(struct sockaddr_in));
            if(peerSock > 0)
            {
                // create p2p ssl
                p2pSSL = SSL_new(ctx);
                // Assign the socket into the SSL structure
                SSL_set_fd(p2pSSL, peerSock);
                // Perform SSL Handshake on the client recv cmd
                nbytes = SSL_accept(p2pSSL);
                if(nbytes == 1)
                {
                    printf("Accpeted connection from remote client via SSL\n");
                }
                sleep(1);
                // connection established

                // peer-2-peer connection handling                
                int rtn = 1, fsize, size_per_send;
                char fname[128];
                DataPacket recvDataPacket, sendDataPacket;
                FILE *file;
                
                // try to receive from remote peer
                nbytes = SSL_read(p2pSSL, &recvDataPacket, sizeof(DataPacket));
                if (nbytes > 0)
                {
                    // check cmd field
                    printf("Receive command '%s' from remote peer\n", recvDataPacket.cmd);
                    if (strstr(recvDataPacket.cmd, "get"))
                    {
                        // parse file name
                        char* sec_arg = strstr(recvDataPacket.cmd, " ");
                        strcpy(fname, sec_arg+1);
                        file = fopen(fname, "rb");
                        if (file == NULL)
                        {
                            printf("Failed open file %s.\n", fname);
                            strcpy(sendDataPacket.cmd, "File Not Found");
                            // nbytes = send(peerSock, &sendDataPacket, sizeof(DataPacket), 0);
                            nbytes = SSL_write(p2pSSL, &sendDataPacket, sizeof(DataPacket));
                            if (nbytes < 0)
                            {
                                perror("error send cmd File Not Found to remote peer");
                            }
                            rtn = 0;
                        }
                        strcpy(sendDataPacket.cmd, "Sending");
                        // nbytes = send(peerSock, &sendDataPacket, sizeof(DataPacket), 0);
                        nbytes = SSL_write(p2pSSL, &sendDataPacket, sizeof(DataPacket));
                        if (nbytes < 0)
                        {
                            perror("error send cmd Sending to remote peer");
                        }
                        struct stat st;
                        stat(fname, &st);
                        fsize = st.st_size;
                        int repeats = (int) (fsize/MAXBUFFSIZE) + 1;
                        for (i = 0; i < repeats; i++)
                        {
                            size_per_send = (MAXBUFFSIZE) < (fsize-i*MAXBUFFSIZE) ? (MAXBUFFSIZE):(fsize-i*MAXBUFFSIZE);
                            int readed = fread(sendDataPacket.payload, sizeof(char), size_per_send, file);
                            sendDataPacket.size = readed;
                            // nbytes = send(peerSock, &sendDataPacket, sizeof(DataPacket), 0);
                            nbytes = SSL_write(p2pSSL, &sendDataPacket, sizeof(DataPacket));
                            if (nbytes < 0)
                            {
                                perror("error send file to remote peer");
                            }
                        }
                        fclose(file);
                        printf("File sent\n");
                        // receive response from reomte peer
                        nbytes = SSL_read(p2pSSL, &recvDataPacket, sizeof(DataPacket));
                        if (nbytes > 0)
                        {
                            if (strcmp(recvDataPacket.cmd, "File received")==0)
                            {
                                printf("Remote peer received file %s\n", fname);
                            }
                        }
                        else
                        {
                            perror("error recv peer file received msg");
                        }
                    }
                    else
                    {
                        printf("Unexpected remote command: %s\n", recvDataPacket.cmd);
                        rtn = 0;
                    }
                }
                else
                {
                    perror("error recv in handleRemotePeerConnection");
                    rtn = 0;
                }
                sleep(1);
                close(peerSock);
                printf("Input command: ls, get, exit\n");
            }
        }
		gets(command);
		// ls command
		if(strcmp(command, "ls") == 0)
        {
            strcpy(sendCmdPacket.cmd, command);
            nbytes = SSL_write(clieSSL, &sendCmdPacket, sizeof(Packet));
			if(nbytes < 0)
            {
				perror("send ls command");
			}
        }
        if (strcmp(command, "exit") == 0)
        {
            // deregister with server
            strcpy(sendCmdPacket.cmd, command);
            nbytes = SSL_write(clieSSL, &sendCmdPacket, sizeof(Packet));
            if (nbytes < 0)
            {
                perror("send exit command");
            }
            else
            {
                printf("Client %s exiting...\n", argv[1]);
                exit(1);
            }
        }
        if (strstr(command, "get"))
        {
            connectRemotePeer(command, &masterList, argv[1], keyName, certName, CACert);
        }
    }
	return 0;
}