コード例 #1
0
ファイル: filelists.c プロジェクト: aylusltd/gretl
void delete_from_filelist (int filetype, const char *fname)
{
    char *tmp[MAXRECENT];
    char **filep;
    int i, match = -1;

    filep = get_file_list(filetype);
    if (filep == NULL) {
	return;
    }

    /* save pointers to current order */
    for (i=0; i<MAXRECENT; i++) {
	tmp[i] = filep[i];
	if (!fnamecmp(filep[i], fname)) {
	    match = i;
	}
    }

    if (match == -1) {
	return;
    }

    /* clear menu files list before rebuilding */
    clear_files_list(filetype, filep);

    for (i=match; i<MAXRECENT-1; i++) {
	filep[i] = tmp[i+1];
    }

    filep[MAXRECENT-1] = tmp[match];
    filep[MAXRECENT-1][0] = '\0';

    add_files_to_menu(filetype);
}
コード例 #2
0
void FileBrowser::pushDirectory(const char *in_path)
{
	const char *cur = this->cur_path_prefix ? xstrdup(this->cur_path_prefix) : NULL;
	size_t cur_len = this->cur_path_prefix ? strlen(this->cur_path_prefix) : 0;
	char *path_cpy = xstrdup(in_path);
	char *path = path_cpy;

	/* Weed out [ and ] from paths */
	if (*path_cpy == '[')
		path = path_cpy + 1;
	for (size_t i = 0; i < strlen(path); i++)
	{
		if (path[i] == ']')
			path[i] = '\0';
	}

	this->cur_path_prefix = (char *)xrealloc(this->cur_path_prefix,
			cur_len + 2 + strlen(path));

	if (cur != NULL)
		sprintf(this->cur_path_prefix, "%s/%s", cur, path);
	else
		strcpy(this->cur_path_prefix, path);

	free((void *)cur);
	free(path_cpy);

	this->freeFileList();
	this->file_list = get_file_list(this->cur_path_prefix, this->exts);
	if (!this->file_list)
		this->setDefaultFileList();
	this->setText(this->file_list);
}
コード例 #3
0
static void load_gpg_keys(void)
{
    map_string_t *settings = new_map_string();
    if (!load_abrt_conf_file(GPG_CONF, settings))
    {
        error_msg("Can't load '%s'", GPG_CONF);
        return;
    }

    const char *gpg_keys_dir = get_map_string_item_or_NULL(settings, "GPGKeysDir");
    if (strcmp(gpg_keys_dir, "") != 0)
    {
        log_debug("Reading gpg keys from '%s'", gpg_keys_dir);
        GHashTable *done_set = g_hash_table_new(g_str_hash, g_str_equal);
        GList *gpg_files = get_file_list(gpg_keys_dir, NULL /* we don't care about the file ext */);
        for (GList *iter = gpg_files; iter; iter = g_list_next(iter))
        {
            const char *key_path = fo_get_fullpath((file_obj_t *)iter->data);

            if (g_hash_table_contains(done_set, key_path))
                continue;

            g_hash_table_insert(done_set, (gpointer)key_path, NULL);
            log_debug("Loading gpg key '%s'", key_path);
            settings_setOpenGPGPublicKeys = g_list_append(settings_setOpenGPGPublicKeys, xstrdup(key_path));
        }

        g_list_free_full(gpg_files, (GDestroyNotify)free_file_obj);
        g_hash_table_destroy(done_set);
    }
}
コード例 #4
0
ファイル: fileutil.c プロジェクト: pkit/sphinx-port
int get_file_list (char *path, SingleList_t *pList, SingleList_t *pFileTypeList)
{
	static int a;
	DIR *dir;
	struct dirent *entry;
	dir = opendir(path);
	int len;
	if(dir == 0)
	{
		return -1;
	}
	while((entry = readdir(dir)))
	{

		if(entry->d_type == DT_DIR)
		{
			if (strcmp (entry->d_name, ".") != 0 && strcmp (entry->d_name, "..") != 0)
			{
				char *newpath = NULL;
				newpath = (char *)  malloc ( sizeof ( char ) * ( strlen (entry->d_name) + strlen (path) + 2 ) );
				if ( strcmp (path, "/") == 0 )
					sprintf ( newpath, "/%s", entry->d_name );
				else
					sprintf ( newpath, "%s/%s", path, entry->d_name );
				get_file_list (newpath, pList, pFileTypeList);
				free (newpath);
			}
		}
		if ( entry->d_type == DT_REG )
		{
			char *filePath = NULL;
			filePath = (char *) malloc ( sizeof ( char ) * ( strlen (entry->d_name) + strlen (path) + 2 ) );
			sprintf( filePath, "%s/%s", path,  entry->d_name);
			int i = 0;
			char *fileExt = NULL;
			//fileExt = getext_( filePath );
/*
			for ( i = 0; i < pFileTypeList->count; i++)
				if ( strcmp ( fileExt , pFileTypeList->list[i]) == 0 )
				{
					char *freeFilePath = filePath;
					if ( filePath[0] == '/' && filePath[1] == '/' )
						filePath++;
					addToList( filePath, pList );
					free ( freeFilePath );
				}
*/
			char *freeFilePath = filePath;
			if ( filePath[0] == '/' && filePath[1] == '/' )
				filePath++;
			addToList( filePath, pList );
			free ( freeFilePath );
		}
	}
	closedir(dir);
	return 0;
}
コード例 #5
0
ファイル: filename_handle.c プロジェクト: huairen/JArchive
struct filename_node * get_file_list( const char *path, int *count, struct filename_node *file_node /*= NULL*/ )
{
	struct _finddata_t file_info;

	intptr_t find_handle = _findfirst(path, &file_info);
	if (find_handle == -1)
		return file_node;

	do 
	{
		if (file_info.attrib &  _A_SUBDIR)
		{
			char sub_puth[256];
			size_t len;

			if (file_info.attrib & _A_SYSTEM)
				continue;

			// skip . and .. directories
			if (strcmp(file_info.name, ".") == 0 || strcmp(file_info.name, "..") == 0)
				continue;

			len = strlen(path) - 1;

			strncpy_s(sub_puth, 256, path, len);
			strcat_s(sub_puth, 256, file_info.name);
			strcat_s(sub_puth, 256, "\\*");
			file_node = get_file_list(sub_puth, count, file_node);
		}      
		else
		{
			struct filename_node *new_node;
			size_t len;

			// make sure it is the kind of file we're looking for
			if (file_info.attrib & _A_SYSTEM)
				continue;

			// add it to the list
			new_node = (struct filename_node*)malloc(sizeof(struct filename_node));
			len = strlen(path) - 1;

			strncpy_s(new_node->name, 256, path, len);
			strcat_s(new_node->name, 256, file_info.name);
			new_node->next = file_node;
			file_node = new_node;

			if(count != NULL)
				(*count) ++;
		}

	}while(_findnext(find_handle, &file_info) == 0);

	_findclose(find_handle);
	return file_node;
}
コード例 #6
0
ファイル: bid.c プロジェクト: huilang22/Projects
static int preprocess_batch(BATCH batch )

{
    int iStatus;
    int count;
    static char * this_func = "preprocess_batch";
    char szSet[256];
    
    (void)arb_put_state(dbproc,ARB_STATUS_PREPROC);
    
    /* Lock files */
    sprintf(szSet, "   SET dispatch_status = %d ", BID_IN_PROGRESS);
    count = set_bill_files(szSet, NULL, batch->batch_id,
			   bid_hold_flag, bid_error_flag,
			   RERUN ? BID_COMPLETE : BID_NOT_STARTED);

    if (count < 0)
	return(count);
	
    if (0 == count)
    {
	emit(BIDMOD,BID_NO_FILES,this_func);
	return(BID_NO_FILES);
    }

    /* Lock all available devices for BID that PRINTs */
    /* Don't need to lock devices for BID that FTPs  LLT */

    if (!BID_ftp)
    {
    	get_all_devices(bid_queueDevices);            /* depends on DISPATCH_TYPE */
    	if (0 >= QueueCount(bid_queueDevices))
    	{
   	    emit(BIDMOD,BID_NO_FIND_DEV_TYPE,this_func,DISPATCH_TYPE);
	    return(-1);
    	}
    
    	lock_all_devices();           /* result -->> bid_queueDevicesLocked */
    	if (0 >= QueueCount(bid_queueDevicesLocked))
    	{
	    emit(BIDMOD,BID_NO_LOCK_DEV_TYPE,this_func,DISPATCH_TYPE);
	    return(-1);
    	}
    }

    /* Get list of files in this batch. -->> bid_queueFiles */
    if (SUCCESS != (iStatus = get_file_list(bid_queueFiles, batch->batch_id,
					bid_hold_flag, bid_error_flag)))
   	return(iStatus);
    count = QueueCount(bid_queueFiles);
    emit(BIDMOD,BID_NUM_FILES_BATCH,this_func,count);
    if (count)
  	return(SUCCESS);
    else
  	return(NO_BILL_FILES);
}
コード例 #7
0
ファイル: picin_core.cpp プロジェクト: ChunKai-Wang/PicIn
/*
 * name : get_file_list
 * desc : Scan indicated path list and return file info list of images
 * in   :
 *   pathList, String list of source path
 *   filters, String list of file extension name
 * ret  : List of QFileInfo for all files under indicated path
 */
QFileInfoList
PicIn_Core::get_file_list(QStringList pathList, QStringList filters)
{
    QFileInfoList fileInfoList;
    for(int i = 0; i < pathList.size(); i++){
        fileInfoList.append(get_file_list(pathList.at(i), filters));
    }

    return fileInfoList;
}
コード例 #8
0
ファイル: picin_core.cpp プロジェクト: ChunKai-Wang/PicIn
/*
 * name : scan_files
 * desc : Get number of files as specific extension from source path
 * ret  : Number of files from source path
 */
int PicIn_Core::scanSrcFiles(QStringList filters)
{
    m_fileInfoList_src.clear();
    m_fileInfoList_src = get_file_list(m_pathList_source, filters);

    get_copyTgt_List();

    m_numFiles = m_fileInfoList_src.size();

    return m_numFiles;
}
コード例 #9
0
ファイル: gproject-project.c プロジェクト: JJ77/geany-plugins
void gprj_project_rescan(void)
{
	GSList *pattern_list = NULL;
	GSList *ignored_dirs_list = NULL;
	GSList *lst;
	GSList *elem;

	if (!g_prj)
		return;

	if (g_prj->generate_tags)
		g_hash_table_foreach(g_prj->file_tag_table, (GHFunc)workspace_remove_tag, NULL);
	g_hash_table_destroy(g_prj->file_tag_table);
	g_prj->file_tag_table = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);

	deferred_op_queue_clean();

	pattern_list = get_precompiled_patterns(geany_data->app->project->file_patterns);

	ignored_dirs_list = get_precompiled_patterns(g_prj->ignored_dirs_patterns);

	lst = get_file_list(geany_data->app->project->base_path, pattern_list, ignored_dirs_list);

	for (elem = lst; elem != NULL; elem = g_slist_next(elem))
	{
		char *path;
		TagObject *obj;

		obj = g_new0(TagObject, 1);
		obj->tag = NULL;

		path = tm_get_real_path(elem->data);
		if (path)
		{
			setptr(path, utils_get_utf8_from_locale(path));
			g_hash_table_insert(g_prj->file_tag_table, path, obj);
		}
	}

	if (g_prj->generate_tags)
		g_hash_table_foreach(g_prj->file_tag_table, (GHFunc)workspace_add_tag, NULL);

	g_slist_foreach(lst, (GFunc) g_free, NULL);
	g_slist_free(lst);

	g_slist_foreach(pattern_list, (GFunc) g_pattern_spec_free, NULL);
	g_slist_free(pattern_list);

	g_slist_foreach(ignored_dirs_list, (GFunc) g_pattern_spec_free, NULL);
	g_slist_free(ignored_dirs_list);
}
コード例 #10
0
ファイル: gproject-project.c プロジェクト: JJ77/geany-plugins
/* path - absolute path in locale, returned list in locale */
static GSList *get_file_list(const gchar * path, GSList *patterns, GSList *ignored_dirs_patterns)
{
	GSList *list = NULL;
	GDir *dir;

	dir = g_dir_open(path, 0, NULL);
	if (!dir)
		return NULL;

	while (TRUE)
	{
		const gchar *name;
		gchar *filename;

		name = g_dir_read_name(dir);
		if (!name)
			break;

		filename = g_build_filename(path, name, NULL);

		if (g_file_test(filename, G_FILE_TEST_IS_DIR))
		{
			GSList *lst;

			if (patterns_match(ignored_dirs_patterns, name))
			{
				g_free(filename);
				continue;
			}

			lst = get_file_list(filename, patterns, ignored_dirs_patterns);
			if (lst)
				list = g_slist_concat(list, lst);
			g_free(filename);
		}
		else if (g_file_test(filename, G_FILE_TEST_IS_REGULAR))
		{
			if (patterns_match(patterns, name))
				list = g_slist_prepend(list, filename);
			else
				g_free(filename);
		}
	}

	g_dir_close(dir);

	return list;
}
コード例 #11
0
ファイル: filelists.c プロジェクト: aylusltd/gretl
static void rc_print_filelist (int filetype, FILE *fp)
{
    char **filep;
    int i;

    filep = get_file_list(filetype);
    if (filep == NULL) {
	return;
    }

    for (i=0; i<MAXRECENT; i++) {
	if (filep[i] != NULL && *filep[i] != 0) {
	    fprintf(fp, "%s%d %s\n", file_sections[filetype], i, filep[i]);
	}
    }
}
コード例 #12
0
ファイル: shell.c プロジェクト: abitduck/baidupcs
static void exec_list(Pcs pcs, struct params *params)
{
	PcsFileInfoList *list;
	printf("\n%sList %s\n", params->is_recursion ? "Recursive " : "", params->args[0]);
	list = get_file_list(pcs, params->args[0], params->sort, params->is_desc, params->is_recursion);
	if (list) {
		printf("Got %d Files\n", list->count);
		fflush(stdout);
		print_filelist(list);
		pcs_filist_destroy(list);
	}
	else {
		printf("Got 0 Files\n");
		fflush(stdout);
		print_filelist_head(4);
	}
}
コード例 #13
0
ファイル: picin_core.cpp プロジェクト: ChunKai-Wang/PicIn
/*
 * name : get_file_list
 * desc : Scan indicated path and return file info list of images
 * in   :
 *   path, String of source path
 *   filters, String list of file extension name
 * ret  : List of QFileInfo for all files under indicated path
 */
QFileInfoList
PicIn_Core::get_file_list(QString path, QStringList filters)
{
    QDir dir(path);
    QStringList nameFilters;

    //
    // Scan files
    //

    QFileInfoList fileInfoList;

    if(filters.size() > 0){
        nameFilters.append(filters);
    }
    dir.setFilter(QDir::NoSymLinks | QDir::Files);
    dir.setNameFilters(nameFilters);
    dir.setSorting(QDir::Name);

    fileInfoList = dir.entryInfoList();

    //
    // Scan sub directory
    //

    if(checkOption(optionSubDir)){
        QFileInfoList dirInfoList;

        dir.setFilter(QDir::NoSymLinks | QDir::Dirs | QDir::NoDotAndDotDot);
        nameFilters.clear();
        dir.setNameFilters(nameFilters);
        dir.setSorting(QDir::Name);

        dirInfoList = dir.entryInfoList();

        for(int i = 0; i < dirInfoList.size(); i++){
            fileInfoList.append(
                get_file_list(dirInfoList.at(i).absoluteFilePath(),
                filters));
        }
    }

    return fileInfoList;
}
コード例 #14
0
int docs_to_xml (char * path, Input_Obj_Type tMode )
{
	int i = 0;
	SingleList_t tFileList, *pFileList=&tFileList, tFileTypeFilter, *pFileTypeFilter = &tFileTypeFilter;
	int xml_fd;
	char *ext = NULL;
	initList( pFileList );
	setFileTypeFilter ( pFileTypeFilter );

#ifndef OLD_ZRT
	if ( strcmp ( getext_( path ), "zip") == 0 )
	{
		get_file_list_inzip ( path , pFileList );
	}
	else
#endif
	if ( tMode == zip_obj )
		get_file_list_inzip( OBJECT_DEVICE_NAME, pFileList );
	else if ( tMode == mail_obj )
		get_file_list( path, pFileList, pFileTypeFilter );
	else
		return 0;

/*
	printf ( "list of indexed docs\n" );
	for ( i = 0; i < pFileList->count; i++)
		printf ( "%s\n", pFileList->list[i] );
*/

///////////////////////

	xml_fd = open_xml_( XML_PATH, tMode ); //FIXME const
	for ( i = 0; i < pFileList->count; i++)
	{
		add_doc_to_xml ( xml_fd, pFileList->list[i], tMode );
	}
	close_xml_( xml_fd );
///////////////////////

	freeList( pFileList );
	freeList( pFileTypeFilter );
	return 0;
}
コード例 #15
0
ファイル: workflow.c プロジェクト: fengye0316/libreport
GHashTable *load_workflow_config_data_from_list(GList *wf_names,
                                                const char *path)
{
    GList *wfs = wf_names;
    GHashTable *wf_list = g_hash_table_new_full(
                         g_str_hash,
                         g_str_equal,
                         g_free,
                         (GDestroyNotify) free_workflow
        );
    GList *workflow_files = get_file_list(path, "xml");
    while(wfs)
    {
        load_workflow_config((const char *)wfs->data, workflow_files, wf_list);
        wfs = g_list_next(wfs);
    }

    return wf_list;
}
コード例 #16
0
ファイル: test.c プロジェクト: initlove/fuse-ocs
int main(int argc, char *argv[])
{
    g_type_init ();
    gchar *val;
    gchar *data = "{'status':'ok','type':'dir'}";
    val = get_value (data, "type");
    printf ("val is %s\n", val);

    GList *list, *l;
    simple_file *sf;

    gchar *file_data = "{'status':'ok','files':[{'name':'dl_gdm','type':'file'},{'name':'b','type':'dir'},{'name':'a_file','type':'file'}]}";
    list = get_file_list (file_data);

    for (l = list; l; l = l->next) {
        sf = l->data;
        printf ("sf %s %s\n", sf->name, sf->type);
    }
    g_free (val);
	return 0;
}
コード例 #17
0
ファイル: workflow.c プロジェクト: credmon/libreport
GHashTable *load_workflow_config_data(const char *path)
{
    if (g_workflow_list)
        return g_workflow_list;

    if (g_workflow_list == NULL)
    {
        g_workflow_list = g_hash_table_new_full(
                                        g_str_hash,
                                        g_str_equal,
                                        g_free,
                                        (GDestroyNotify) free_workflow
        );
    }

    if (path == NULL)
        path = WORKFLOWS_DIR;

    GList *workflow_files = get_file_list(path, "xml");
    while (workflow_files)
    {
        file_obj_t *file = (file_obj_t *)workflow_files->data;

        workflow_t *workflow = get_workflow(file->filename);
        bool nw_workflow = (!workflow);
        if (nw_workflow)
            workflow = new_workflow(file->filename);

        load_workflow_description_from_file(workflow, file->fullpath);

        if (nw_workflow)
            g_hash_table_replace(g_workflow_list, xstrdup(wf_get_name(workflow)), workflow);

        free_file_obj(file);
        workflow_files = g_list_delete_link(workflow_files, workflow_files);
    }

    return g_workflow_list;
}
コード例 #18
0
ファイル: print.c プロジェクト: linus-young/Homework
void display_file_recursively(struct FileList *file_list, int count, int mode)
/*
 * display for -R option.
 * NOTE: for multiple directories, please use absolute path.
 */
{
        char path[MAX_PATH_LEN] = { 0 };
        char temp[MAX_PATH_LEN] = { 0 };
        char filename[MAX_FILENAME_LEN] = { 0 };
        struct FileList list[MAX_FILE_COUNT];
        int i = 0, size = 0;

        puts(get_current_dir_name()); /* absolute path */
        strcpy(path, get_current_dir_name());

        if(mode & DETAIL)
                display_file_detail(file_list, count);
        else
                display_file_simply(file_list, count);
        printf("\n");

        for(i = 0; i < count; ++i) {
                strcpy(filename, file_list[i].name);

                /* NOTE: "." and ".." is directory, skip them! */
                if((strcmp(filename, ".") == 0) || (strcmp(filename, "..") == 0))
                        continue;
                if(S_ISDIR(file_list[i].info.st_mode)) { /*if a directory*/
                        strcpy(temp, path);
                        strcat(path, "/");
                        strcat(path, filename); /*store absolute path*/
                        size = get_file_list(path, list, mode);
                        display_file_recursively(list, size, mode);
                        strcpy(path, temp);
                }
        }
}
コード例 #19
0
int docs_to_xml (char * path, int doc_type)
{
	int i = 0;
	SingleList_t tFileList, *pFileList=&tFileList, tFileTypeFilter, *pFileTypeFilter = &tFileTypeFilter;
	int xml_fd;
	char *ext = NULL;
	initList( pFileList );
	setFileTypeFilter ( pFileTypeFilter );

#ifndef OLD_ZRT
	if ( strcmp ( getext_( path ), "zip") == 0 )
	{
		get_file_list_inzip ( path , pFileList );
	}
	else
#endif
	print_dir_tree (path);
	get_file_list ( path, pFileList, pFileTypeFilter );

	printf ( "list of indexed docs\n" );
	for ( i = 0; i < pFileList->count; i++)
		printf ( "%s\n", pFileList->list[i] );

///////////////////////

	xml_fd = open_xml_( XML_PATH ); //FIXME const
	for ( i = 0; i < pFileList->count; i++)
	{
		add_doc_to_xml ( xml_fd, pFileList->list[i], doc_type );
	}
	close_xml_( xml_fd );
///////////////////////

	freeList( pFileList );
	freeList( pFileTypeFilter );
	return 0;
}
コード例 #20
0
ファイル: main.c プロジェクト: ExAcler/Prizm
void browse_main()
{
    /*
	    文件浏览器主函数
	*/

    char ncat[64], workdir[64] = "\\\\fls0";    //  当前目录
    f_name *a=get_file_list("\\\\fls0\\*.*");    //  存储文件列表的二维数组
	int pos=0,firstn=0;    //  列表光标位置、列表下移的行数
	unsigned int key;
	char subdir_fn[32];    //  供接收子目录文件名输入的缓冲区
	FONTCHARACTER fname[64];
	int handle = 0;
	
	DefineStatusAreaFlags(3, 0x01 | 0x02 | 0x100, 0, 0);
	
	beg:
	if (a) qsort(a, getn(a), sizeof(char *), cmp);
	
	font16 = open_font("\\\\fls0\\24PX.hzk");
	select_font(font16);
	
	draw_browser(workdir,firstn,pos,a);    //  绘制浏览器界面
	
	close_font(font16);
	
	//  显示当前工作目录于状态栏
	if (strcmp(workdir, "\\\\fls0") == 0)
		DefineStatusMessage("", 0, 0, 0);
	else
	{
		memset(ncat, 0, sizeof(ncat));
		GetDisplayDirName(workdir, ncat);
		DefineStatusMessage(ncat, 0, 0, 0);
	}
	
	while (1)
	{
	    GetKey(&key);
		switch (key)
		{
		    case KEY_CTRL_UP:    //  光标上移
			    if (a)
				{
				    aa(&pos,&firstn,getn(a));
					goto beg;
				}
				break;
				
			case KEY_CTRL_DOWN:    //  光标下移
			    if (a)
				{
				    bb(&pos,&firstn,getn(a));
					goto beg;
				}
				break;
			
			case KEY_CTRL_F6:    //  显示关于信息
			    Disp_About();
				goto beg;
				break;
			
			case KEY_CTRL_F1:    //  打开光标位置的文件
			case KEY_CTRL_EXE:
			    if (a)    //  如果文件列表不为空
			    {
			        if (strchr(a[pos+firstn].name,'['))    //  如果打开的是文件夹
				    {
				        memset(ncat,0,sizeof(ncat));
					    //strcat(ncat,"\\\\fls0\\");
						strcat(ncat, workdir); strcat(ncat, "\\");
				        strcat(ncat, ++a[pos+firstn].name);
					    memset(workdir, 0, sizeof(workdir));
					    strcpy(workdir, ncat);
					    strcat(ncat, "\\*.*");    //  解析出文件夹名称
					    a=get_file_list(ncat);    //  浏览该文件夹
						pos=0; firstn=0;    //  列表初始化
					    goto beg;
				    }
				    else    //  如果打开的是文本文件
				    {	
						memset(ncat,0,sizeof(ncat));
				        strcpy(ncat,workdir);
						strcat(ncat,"\\");
				        strcat(ncat,a[pos+firstn].name);    //  解析出文件名称
						
						iRead_main(ncat);    //  启动阅读器
						goto beg;
				    }
				}
				break;
				
			case KEY_CTRL_F2:	//  根据输入的文件名打开文件
				memset(subdir_fn, 0, sizeof(subdir_fn));
				if (Subdir_Open(subdir_fn))
				{
					memset(ncat, 0, sizeof(ncat));
				    strcpy(ncat, workdir);
					strcat(ncat, "\\");
				    strcat(ncat, subdir_fn);    //  连接上输入的文件名字
					strcat(ncat, ".txt");
						
					char_to_font(ncat, fname);
					handle = Bfile_OpenFile_OS(fname,0);
					if (handle <= 0)    //  如果文件未找到
					{
						Disp_FileNotFound();
						MsgBoxPop();
						goto beg; break;
					}
						
					MsgBoxPop();
					Bfile_CloseFile_OS(handle);
					
					//  重新绘制浏览器界面
					font16 = open_font("\\\\fls0\\24PX.hzk");
					select_font(font16);
	
					draw_browser(workdir, firstn, pos, a);
					close_font(font16);
					
					//  启动阅读器
					iRead_main(ncat);
				}
				
				goto beg; break;
			
			case KEY_CTRL_EXIT:    //  从文件夹返回根目录
			    if (strcmp(workdir,"\\\\fls0")!=0)    //  如果当前在文件夹内
			    {
			        memset(ncat,0,sizeof(ncat));
			        strncpy(ncat,workdir,strlen(workdir)-strlen(strrchr(workdir,'\\')));
				    memset(workdir,0,sizeof(workdir));
				    strcpy(workdir,ncat);
				    strcat(ncat,"\\*.*");    //  解析出上一级目录的名称
			        a=get_file_list(ncat);    //  浏览该文件夹
					pos=0;firstn=0;    //  初始化列表
				    goto beg;
				
				}
				break;
			
		}
	}
}
コード例 #21
0
ファイル: obmenu.c プロジェクト: aharotias2/t-obmenu
int print_dir_entries(char *dir_name) {
	int dir_name_length = strlen(dir_name), item_length = 0;
	char *path = NULL;
	char *escaped_path = NULL;
	str_list *list = get_file_list(dir_name);
	struct DESKTOP_ENTRY data = { APPLICATION, NULL, NULL, NULL, NULL, NULL, true };

	if (dir_name == NULL || list == NULL) return 1;

	str_list *item = list;
	while (item != NULL) {
		item_length = strlen(item->str);
		path = realloc(path, dir_name_length + 1 + item_length + 1);
		sprintf(path, "%s/%s", dir_name, item->str);
		switch (is_reg_file(path)) {
		case 1:
			if (get_data(&data, path)) { 
				if (data.type == LINK) {
					printf(
						"<item\n"
						"  label=\"%s\"\n"
						"  icon=\"" PAGE_ICON "\">\n"
						"  <action name=\"Execute\">\n"
						"    <execute>%s &quot;%s&quot;</execute>\n"
						"  </action>\n"
						"</item>\n",
						data.name,
						g_browser_name,
						data.url
					);
				} else if (data.type == APPLICATION) {
					printf(
						"<item\n"
					);
					if (data.comment != NULL) {
						printf(
						"  label=\"%s (%s)\"\n", data.name, data.comment
						);
					} else {
						printf(
						"  label=\"%s\"\n", data.name
						);
					}
					printf(
						"  icon=\"%s/%s.png\">\n"
						"  <action name=\"Execute\">\n",
						g_icon_dir,
						data.icon
					);
					if (data.has_gui) {
						printf(
						"    <execute>%s</execute>\n", data.command
						);
					} else {
						printf(
						"    <execute>urxvt -icon &quot;%s/%s.png&quot; -title &quot;%s&quot; -e &quot;%s&quot;</execute>\n",
						g_icon_dir,
						data.command,
					   	data.command,
						data.command
						);
					}
					printf(
						"  </action>\n"
						"</item>\n"
					);
				}
			}
			reset_data(&data);
			break;

		case 0: /* if the path represents a directory */
			escaped_path = escape_space(path);
			printf(
				"<menu\n"
				"  icon=\"" CATEGORY_ICON "\"\n"
				"  id=\"%s\"\n"
				"  label=\"%s\"\n"
				"  execute=\"%s -d%s -b%s -f%s -i%s\" />\n",
				item->str,
				item->str,
				g_cmd_name,
				escaped_path,
				g_browser_name,
				g_filer_name,
				g_icon_dir
			);
			free(escaped_path);
			break;
		}
		item = item->next;
	}
	strlist_free(list);
	free(path);
	return 0;
}
コード例 #22
0
ファイル: skdiff_main.cpp プロジェクト: webbjiang/skia
/// Creates difference images, returns the number that have a 0 metric.
/// If outputDir.isEmpty(), don't write out diff files.
static void create_diff_images (DiffMetricProc dmp,
                                const int colorThreshold,
                                RecordArray* differences,
                                const SkString& baseDir,
                                const SkString& comparisonDir,
                                const SkString& outputDir,
                                const StringArray& matchSubstrings,
                                const StringArray& nomatchSubstrings,
                                bool recurseIntoSubdirs,
                                bool getBounds,
                                bool verbose,
                                DiffSummary* summary) {
    SkASSERT(!baseDir.isEmpty());
    SkASSERT(!comparisonDir.isEmpty());

    FileArray baseFiles;
    FileArray comparisonFiles;

    get_file_list(baseDir, matchSubstrings, nomatchSubstrings, recurseIntoSubdirs, &baseFiles);
    get_file_list(comparisonDir, matchSubstrings, nomatchSubstrings, recurseIntoSubdirs,
                  &comparisonFiles);

    if (!baseFiles.isEmpty()) {
        qsort(baseFiles.begin(), baseFiles.count(), sizeof(SkString*),
              SkCastForQSort(compare_file_name_metrics));
    }
    if (!comparisonFiles.isEmpty()) {
        qsort(comparisonFiles.begin(), comparisonFiles.count(),
              sizeof(SkString*), SkCastForQSort(compare_file_name_metrics));
    }

    int i = 0;
    int j = 0;

    while (i < baseFiles.count() &&
           j < comparisonFiles.count()) {

        SkString basePath(baseDir);
        SkString comparisonPath(comparisonDir);

        DiffRecord *drp = new DiffRecord;
        int v = strcmp(baseFiles[i]->c_str(), comparisonFiles[j]->c_str());

        if (v < 0) {
            // in baseDir, but not in comparisonDir
            drp->fResult = DiffRecord::kCouldNotCompare_Result;

            basePath.append(*baseFiles[i]);
            comparisonPath.append(*baseFiles[i]);

            drp->fBase.fFilename = *baseFiles[i];
            drp->fBase.fFullPath = basePath;
            drp->fBase.fStatus = DiffResource::kExists_Status;

            drp->fComparison.fFilename = *baseFiles[i];
            drp->fComparison.fFullPath = comparisonPath;
            drp->fComparison.fStatus = DiffResource::kDoesNotExist_Status;

            VERBOSE_STATUS("MISSING", ANSI_COLOR_YELLOW, baseFiles[i]);

            ++i;
        } else if (v > 0) {
            // in comparisonDir, but not in baseDir
            drp->fResult = DiffRecord::kCouldNotCompare_Result;

            basePath.append(*comparisonFiles[j]);
            comparisonPath.append(*comparisonFiles[j]);

            drp->fBase.fFilename = *comparisonFiles[j];
            drp->fBase.fFullPath = basePath;
            drp->fBase.fStatus = DiffResource::kDoesNotExist_Status;

            drp->fComparison.fFilename = *comparisonFiles[j];
            drp->fComparison.fFullPath = comparisonPath;
            drp->fComparison.fStatus = DiffResource::kExists_Status;

            VERBOSE_STATUS("MISSING", ANSI_COLOR_YELLOW, comparisonFiles[j]);

            ++j;
        } else {
            // Found the same filename in both baseDir and comparisonDir.
            SkASSERT(DiffRecord::kUnknown_Result == drp->fResult);

            basePath.append(*baseFiles[i]);
            comparisonPath.append(*comparisonFiles[j]);

            drp->fBase.fFilename = *baseFiles[i];
            drp->fBase.fFullPath = basePath;
            drp->fBase.fStatus = DiffResource::kExists_Status;

            drp->fComparison.fFilename = *comparisonFiles[j];
            drp->fComparison.fFullPath = comparisonPath;
            drp->fComparison.fStatus = DiffResource::kExists_Status;

            SkAutoDataUnref baseFileBits(read_file(drp->fBase.fFullPath.c_str()));
            if (baseFileBits) {
                drp->fBase.fStatus = DiffResource::kRead_Status;
            }
            SkAutoDataUnref comparisonFileBits(read_file(drp->fComparison.fFullPath.c_str()));
            if (comparisonFileBits) {
                drp->fComparison.fStatus = DiffResource::kRead_Status;
            }
            if (NULL == baseFileBits || NULL == comparisonFileBits) {
                if (NULL == baseFileBits) {
                    drp->fBase.fStatus = DiffResource::kCouldNotRead_Status;
                    VERBOSE_STATUS("READ FAIL", ANSI_COLOR_RED, baseFiles[i]);
                }
                if (NULL == comparisonFileBits) {
                    drp->fComparison.fStatus = DiffResource::kCouldNotRead_Status;
                    VERBOSE_STATUS("READ FAIL", ANSI_COLOR_RED, comparisonFiles[j]);
                }
                drp->fResult = DiffRecord::kCouldNotCompare_Result;

            } else if (are_buffers_equal(baseFileBits, comparisonFileBits)) {
                drp->fResult = DiffRecord::kEqualBits_Result;
                VERBOSE_STATUS("MATCH", ANSI_COLOR_GREEN, baseFiles[i]);
            } else {
                AutoReleasePixels arp(drp);
                get_bitmap(baseFileBits, drp->fBase, SkImageDecoder::kDecodePixels_Mode);
                get_bitmap(comparisonFileBits, drp->fComparison,
                           SkImageDecoder::kDecodePixels_Mode);
                VERBOSE_STATUS("DIFFERENT", ANSI_COLOR_RED, baseFiles[i]);
                if (DiffResource::kDecoded_Status == drp->fBase.fStatus &&
                    DiffResource::kDecoded_Status == drp->fComparison.fStatus) {
                    create_and_write_diff_image(drp, dmp, colorThreshold,
                                                outputDir, drp->fBase.fFilename);
                } else {
                    drp->fResult = DiffRecord::kCouldNotCompare_Result;
                }
            }

            ++i;
            ++j;
        }

        if (getBounds) {
            get_bounds(*drp);
        }
        SkASSERT(DiffRecord::kUnknown_Result != drp->fResult);
        differences->push(drp);
        summary->add(drp);
    }

    for (; i < baseFiles.count(); ++i) {
        // files only in baseDir
        DiffRecord *drp = new DiffRecord();
        drp->fBase.fFilename = *baseFiles[i];
        drp->fBase.fFullPath = baseDir;
        drp->fBase.fFullPath.append(drp->fBase.fFilename);
        drp->fBase.fStatus = DiffResource::kExists_Status;

        drp->fComparison.fFilename = *baseFiles[i];
        drp->fComparison.fFullPath = comparisonDir;
        drp->fComparison.fFullPath.append(drp->fComparison.fFilename);
        drp->fComparison.fStatus = DiffResource::kDoesNotExist_Status;

        drp->fResult = DiffRecord::kCouldNotCompare_Result;
        if (getBounds) {
            get_bounds(*drp);
        }
        differences->push(drp);
        summary->add(drp);
    }

    for (; j < comparisonFiles.count(); ++j) {
        // files only in comparisonDir
        DiffRecord *drp = new DiffRecord();
        drp->fBase.fFilename = *comparisonFiles[j];
        drp->fBase.fFullPath = baseDir;
        drp->fBase.fFullPath.append(drp->fBase.fFilename);
        drp->fBase.fStatus = DiffResource::kDoesNotExist_Status;

        drp->fComparison.fFilename = *comparisonFiles[j];
        drp->fComparison.fFullPath = comparisonDir;
        drp->fComparison.fFullPath.append(drp->fComparison.fFilename);
        drp->fComparison.fStatus = DiffResource::kExists_Status;

        drp->fResult = DiffRecord::kCouldNotCompare_Result;
        if (getBounds) {
            get_bounds(*drp);
        }
        differences->push(drp);
        summary->add(drp);
    }

    release_file_list(&baseFiles);
    release_file_list(&comparisonFiles);
}
コード例 #23
0
ファイル: cchannelsession.cpp プロジェクト: darkjavi/corepad
void cChannelSession::dataRX(const QVector<QByteArray> &data)
{
    if (data.count() < 2)
    {
        qDebug() << "[ERROR]cChannelSession::dataRX-> Pocos campos... :" << data.count();
        return;
    }
    int cmd = data[1].toInt();
    //qDebug() << "[INFO]cChannelSession::dataRX-> Comando:" << cmd;
    if(cmd == CMD_JOIN_SESSION)
    {
        QString id = data[2];
        emit join_session(id);
    }
    else if (cmd == CMD_SESSION_STATUS)
    {
        QString id      = data[2];
        bool status     = data[3].toInt();
        QString reason  = data[4];
        emit session_status(id,status,reason);
    }
    else if (cmd == CMD_GET_SESSION_USERLIST)
    {
        QString id = data[2];
        emit get_session_userlist(id);
    }
    else if (cmd == CMD_SESSION_USERLIST)
    {
        QString id = data[2];
        QByteArray array = data[3];
        cUsersInfoList userslist(array);
        emit session_userlist(id,userslist);
    }
    else if (cmd == CMD_GET_CHATROOM_LIST)
    {
        QString id = data[2];
        emit get_chatroom_list(id);
    }
    else if (cmd == CMD_CHATROOM_LIST)
    {
        QString id = data[2];
        QVector<cChatInfo> chats;
        for ( int i = 3 ; i < data.count() ; i+=3 )
        {
            cChatInfo chatroom(data[i],data[i+1],data[i+2].toInt());
            chats.append(chatroom);
        }
        emit chatroom_list(id,chats);
    }
    else if(cmd == CMD_JOIN_CHATROOM)
    {
        QString id = data[2];
        emit join_chatroom(id);
    }
    else if(cmd == CMD_CHATROOM_STATUS)
    {
        QString id      = data[2];
        bool status     = data[3].toInt();
        QString reason  = data[4];
        emit chatroom_status(id,status,reason);
    }
    else if(cmd == CMD_GET_CHATROOM_USERLIST)
    {
        QString chatroom_id = data[2];
        emit get_chatroom_userlist(chatroom_id);
    }
    else if(cmd == CMD_CHATROOM_USERLIST)
    {
        QString id = data[2];
        QByteArray array = data[3];
        cUsersInfoList userslist(array);
        emit chatroom_userlist(id,userslist);
    }
    else if(cmd == CMD_CREATE_CHATROOM)
    {
        QString name    = data[2];
        bool persistent = data[3].toInt();
        emit create_chatroom(name,persistent);
    }
    else if(cmd == CMD_CHATROOM_MSG)
    {
        QVector<cChatMsg> msgs;
        QString id = data[2];
        for ( int i = 3 ; i < data.count() ; i+=3 )
        {
            QDateTime timestamp;
            timestamp.fromMSecsSinceEpoch(data[i+2].toInt());
            cChatMsg msg(data[i],data[i+1],timestamp);
            msgs.append(msg);
        }
        emit chatroom_msg(id,msgs);
    }
    else if(cmd == CMD_GET_FILELIST)
    {
        QString id = data[2];
        emit get_file_list(id);
    }
    else if(cmd == CMD_FILELIST)
    {
        QString id = data[2];

    }
    else if(cmd == CMD_GET_PAD_LIST)
    {
        QString id = data[2];
        emit get_pad_list(id);
    }
    else if(cmd == CMD_PAD_LIST)
    {
        QString id = data[2];
        QByteArray array(data[3]);
        cPadsInfoList padslist(array);
        emit pad_list(id,padslist);

    }
    else if(cmd == CMD_JOIN_PAD)
    {
        QString id = data[2];
        emit join_pad(id);
    }
    else if(cmd == CMD_PAD_STATUS)
    {
        QString id      = data[2];
        bool status     = data[3].toInt();
        QString reason  = data[4];
        emit pad_status(id,status,reason);
    }
    else if(cmd == CMD_GET_PAD_USERLIST)
    {
        QString id = data[2];
        emit get_pad_userlist(id);
    }
    else if(cmd == CMD_PAD_USERLIST)
    {
        QString id = data[2];
        QByteArray array = data[3];
        cUsersInfoList userslist(array);
        emit pad_userlist(id,userslist);
    }
    else if(cmd == CMD_GET_PAD_DOCUMENT)
    {
        QString id(data[2]);
        emit get_pad_document(id);
    }
    else if(cmd == CMD_PAD_DOCUMENT)
    {
        QString id(data[2]);
        QString padText(data[3]);
        emit pad_document(id,padText);
    }
    else if(cmd == CMD_PAD_CHANGES)
    {
        QString id(data[2]);
        QString sender = data[3];
        int pos(data[4].toInt());
        int del(data[5].toInt());
        int add(data[6].toInt());
        QString text(data[7]);
        emit pad_changes(id,sender,pos,del,add,text);
    }
    else
    {
        qDebug() << "[ERROR]cChannelSession::dataRX-> Comando desconocido:" << cmd;
    }
}
コード例 #24
0
ファイル: shell.c プロジェクト: abitduck/baidupcs
static int exec_download_dir(Pcs pcs, const char *remote_path, const char *local_path,
							 int force, int recursion, int synch)
{
	int ft;
	hashtable *ht;
	my_dirent *ents, *ent, *local_file;
	PcsFileInfoList *remote_files;
	PcsFileInfoListIterater iterater;
	PcsFileInfo *file;
	PcsRes dres;
	char *dest_path;
	struct download_state ddstat;
	FILE *pf;

	printf("\nDownload %s to %s\n", remote_path, local_path);
	ft = is_dir_or_file(local_path);
	if (ft == 1) {
		printf("Invalidate target: %s is not the directory.\n", local_path);
		return -1;
	}
	else if (ft == 2) {
		//if (!force) {
		//	printf("execute upload command failed: The target %s exist.\n", remote_path);
		//	return -1;
		//}
	}
	else {
		if (mkdir(local_path)) {
			printf("Cannot create the directory %s.\n", local_path);
			return -1;
		}
	}

	ents = list_dir(local_path, 0);

	ht = hashtable_create(100, 1, NULL);
	if (!ht) {
		printf("Cannot create hashtable.\n");
		my_dirent_destroy(ents);
		return -1;
	}
	ent = ents;
	while(ent) {
		if (hashtable_add(ht, ent->path, ent)) {
			printf("Cannot add item into hashtable.\n");
			hashtable_destroy(ht);
			my_dirent_destroy(ents);
			return -1;
		}
		ent = ent->next;
	}

	remote_files = get_file_list(pcs, remote_path, NULL, PcsFalse, PcsFalse);
	if (!remote_files) {
		hashtable_destroy(ht);
		my_dirent_destroy(ents);
		if (pcs_strerror(pcs)) {
			printf("Cannot list the remote files.\n");
			return -1;
		}
		return 0;
	}

	pcs_filist_iterater_init(remote_files, &iterater, PcsFalse);
	while(pcs_filist_iterater_next(&iterater)) {
		file = iterater.current;
		dest_path = combin_local_path(local_path, file->server_filename);
		if (!dest_path) {
			printf("Cannot alloca memory. 0%s, %s\n", local_path, file->server_filename);
			pcs_filist_destroy(remote_files);
			hashtable_destroy(ht);
			my_dirent_destroy(ents);
			return -1;
		}
		if (file->isdir) {
			if (force || recursion) {
				local_file = (my_dirent *)hashtable_get(ht, dest_path);
				if (local_file) {
					local_file->user_flag = 1;
					printf("[SKIP] d %s\n", file->path);
				}
				else if (recursion) {
					if (mkdir(dest_path)) {
						printf("[FAIL] d %s Cannot create the folder %s\n", file->path, dest_path);
						pcs_free(dest_path);
						pcs_filist_destroy(remote_files);
						hashtable_destroy(ht);
						my_dirent_destroy(ents);
						return -1;
					}
					else {
						printf("[SUCC] d %s => %s\n", file->path, dest_path);
					}
				}
			}
		}
		else {
			local_file = (my_dirent *)hashtable_get(ht, dest_path);
			if (local_file) local_file->user_flag = 1;
			if (force || !local_file || my_dirent_get_mtime(local_file) < ((time_t)file->server_mtime)) {
				ddstat.msg = (char *) pcs_malloc(strlen(dest_path) + 12);
				if (!ddstat.msg) {
					printf("Cannot alloca memory. 1%s, %s\n", local_path, file->server_filename);
					pcs_free(dest_path);
					pcs_filist_destroy(remote_files);
					hashtable_destroy(ht);
					my_dirent_destroy(ents);
					return -1;
				}
				sprintf(ddstat.msg, "Download %s ", dest_path);
				pf = fopen(dest_path, "wb");
				if (!pf) {
					printf("Cannot create the local file: %s\n", dest_path);
					pcs_free(dest_path);
					pcs_free(ddstat.msg);
					pcs_filist_destroy(remote_files);
					hashtable_destroy(ht);
					my_dirent_destroy(ents);
					return -1;
				}
				ddstat.pf = pf;
				ddstat.size = 0;
				pcs_setopt(pcs, PCS_OPTION_DOWNLOAD_WRITE_FUNCTION_DATA, &ddstat);
				dres = pcs_download(pcs, file->path);
				pcs_free(ddstat.msg);
				fclose(ddstat.pf);
				if (dres != PCS_OK) {
					printf("[FAIL] - %s => %s\n", file->path, dest_path);
					pcs_free(dest_path);
					pcs_filist_destroy(remote_files);
					hashtable_destroy(ht);
					my_dirent_destroy(ents);
					return -1;
				}
				my_dirent_utime(dest_path, file->server_mtime);
				printf("[SUCC] - %s => %s\n", file->path, dest_path);
			}
			else {
				printf("[SKIP] - %s\n", file->path);
			}
		}
		pcs_free(dest_path);
	}
	if (recursion) {
		pcs_filist_iterater_init(remote_files, &iterater, PcsFalse);
		while(pcs_filist_iterater_next(&iterater)) {
			file = iterater.current;
			dest_path = combin_local_path(local_path, file->server_filename);
			if (!dest_path) {
				printf("Cannot alloca memory. 2%s, %s\n", local_path, file->server_filename);
				pcs_filist_destroy(remote_files);
				hashtable_destroy(ht);
				my_dirent_destroy(ents);
				return -1;
			}
			if (file->isdir) {
				if (exec_download_dir(pcs, file->path, dest_path, force, recursion, synch)) {
					pcs_free(dest_path);
					pcs_filist_destroy(remote_files);
					hashtable_destroy(ht);
					my_dirent_destroy(ents);
					return -1;
				}
			}
			pcs_free(dest_path);
		}
	}
	if (synch) {
		hashtable_iterater *iterater;

		iterater = hashtable_iterater_create(ht);
		hashtable_iterater_reset(iterater);
		while(hashtable_iterater_next(iterater)) {
			local_file = (my_dirent *)hashtable_iterater_current(iterater);
			if (!local_file->user_flag) {
				if (my_dirent_remove(local_file->path)) {
					printf("[DELETE] [FAIL] %s %s \n", local_file->is_dir ? "d" : "-", local_file->path);
				}
				else {
					printf("[DELETE] [SUCC] %s %s \n", local_file->is_dir ? "d" : "-", local_file->path);
				}
			}
		}
		hashtable_iterater_destroy(iterater);
	}

	pcs_filist_destroy(remote_files);
	hashtable_destroy(ht);
	my_dirent_destroy(ents);
	return 0;
}
コード例 #25
0
ファイル: shell.c プロジェクト: abitduck/baidupcs
static PcsFileInfoList *get_file_list(Pcs pcs, const char *dir, const char *sort, PcsBool desc, PcsBool recursion)
{
	PcsFileInfoList *reslist = NULL,
		*list = NULL,
		*sublist = NULL,
		*item = NULL;
	PcsFileInfo *info = NULL;
	int page_index = 1,
		page_size = 100;
	int cnt = 0, cnt_total = 0;
	while(1) {
		printf("List %s, Got %d Files           \r", dir, cnt_total);
		fflush(stdout);
		list = pcs_list(pcs, dir, 
			page_index, page_size,
			sort ? sort : "name", 
			sort ? desc : PcsFalse);
		if (!list) {
			if (pcs_strerror(pcs))
				printf("Cannot list %s: %s\n", dir, pcs_strerror(pcs));
			return NULL;
		}
		cnt = list->count;
		cnt_total += cnt;
		if (recursion) {
			PcsFileInfoListItem *listitem;
			PcsFileInfoListIterater iterater;
			reslist = pcs_filist_create();
			if (!reslist) {
				printf("Cannot create the PcsFileInfoList object for %s.\n", dir);
				pcs_filist_destroy(list);
				return NULL;
			}
			pcs_filist_iterater_init(list, &iterater, PcsFalse);
			while(pcs_filist_iterater_next(&iterater)) {
				info = iterater.current;
				listitem = iterater.cursor;
				pcs_filist_remove(list, listitem, &iterater);
				pcs_filist_add(reslist, listitem);
				if (info->isdir) {
					sublist = get_file_list(pcs, info->path, sort, desc, recursion);
					if (sublist) {
						pcs_filist_combin(reslist, sublist);
						pcs_filist_destroy(sublist);
					}
				}
				else {
					/*
					 * 因为百度网盘返回的都是文件夹在前,文件在后,
					 * 因此遇到第一个文件,则后边的都是文件。
					 * 所以可以跳过检查,直接合并
					*/
					pcs_filist_combin(reslist, list);
					break;
				}
			}
			pcs_filist_destroy(list);
		}
		else {
			reslist = list;
		}
		if (cnt > 0) {
			printf("List %s, Got %d Files           \r", dir, cnt_total);
			fflush(stdout);
		}
		if (cnt < page_size) {
			break;
		}
		page_index++;
	}
	return reslist;
}
コード例 #26
0
ファイル: shell.c プロジェクト: abitduck/baidupcs
static int exec_upload_dir(Pcs pcs, const char *local_path, const char *remote_path,
							 int force, int recursion, int synch)
{
	int ft = 0, res = 0, ric = 0;
	char *dest_path = NULL;
	PcsFileInfo *meta = NULL,
		*remote_file = NULL;
	PcsFileInfoList *remote_filelist = NULL;
	PcsFileInfoListIterater iterater = {0};
	PcsRes pcsres = PCS_NONE;
	PcsPanApiRes *pcsapires = NULL;
	hashtable *ht = NULL;
	my_dirent *ents = NULL,
		*ent = NULL;

	printf("\nUpload %s to %s\n", local_path, remote_path);
exec_upload_dir_label_1:
	meta = pcs_meta(pcs, remote_path);
	if (meta) {
		if (meta->isdir)
			ft = 2;
		else
			ft = 1;
		pcs_fileinfo_destroy(meta);
		meta = NULL;
	}
	else if (pcs_strerror(pcs)) {
		printf("Cannot get the meta for %s: %s\n", remote_path, pcs_strerror(pcs));
		ric = retry_cancel();
		if (ric == 'r')
			goto exec_upload_dir_label_1;
		else
			return -1;
	}
	if (ft == 1) {
		if (force) {
			PcsSList slist = { 
				(char *)remote_path,
				0
			};
			printf("Delete the %s, since the target is not the directory and you specify -f.\n", remote_path);
exec_upload_dir_label_2:
			pcsapires = pcs_delete(pcs, &slist);
			if (!pcsapires) {
				printf("[DELETE] [FAIL] - %s: %s\n", remote_path, pcs_strerror(pcs));
				ric = retry_cancel();
				if (ric == 'r')
					goto exec_upload_dir_label_2;
				else
					return -1;
			}
			else {
				printf("[DELETE] [SUCC] - %s \n", remote_path);
				pcs_pan_api_res_destroy(pcsapires);
			}
exec_upload_dir_label_3:
			pcsres = pcs_mkdir(pcs, remote_path);
			if (pcsres != PCS_OK) {
				printf("[FAIL] Cannot create the directory %s: %s\n", remote_path, pcs_strerror(pcs));
				ric = retry_cancel();
				if (ric == 'r')
					goto exec_upload_dir_label_3;
				else
					return -1;
			}
			else {
				printf("[SUCC] Create directory %s\n", remote_path);
				goto exec_upload_dir_label_5;
			}
		}
		else {
			printf("The target %s is not the directory. You can use -f to force recreate the directory.\n", remote_path);
		}
		return -1;
	}
	else if (ft == 2) {
	}
	else {
exec_upload_dir_label_4:
		pcsres = pcs_mkdir(pcs, remote_path);
		if (pcsres != PCS_OK) {
			printf("[FAIL] Cannot create the directory %s: %s\n", remote_path, pcs_strerror(pcs));
			ric = retry_cancel();
			if (ric == 'r')
				goto exec_upload_dir_label_4;
			else
				return -1;
		}
		else {
			printf("[SUCC] Create directory %s\n", remote_path);
			goto exec_upload_dir_label_5;
		}
	}

exec_upload_dir_label_5:
	printf("Get remote file list %s.\n", remote_path);
	remote_filelist = get_file_list(pcs, remote_path, NULL, PcsFalse, PcsFalse);
	if (!remote_filelist && pcs_strerror(pcs)) {
		printf("[FAIL] Cannot list the directory %s: %s\n", remote_path, pcs_strerror(pcs));
		ric = retry_cancel();
		if (ric == 'r')
			goto exec_upload_dir_label_5;
		else
			return -1;
	}
	if (remote_filelist) {
		ht = hashtable_create(remote_filelist->count, 1, NULL);
		if (!ht) {
			printf("Cannot create hashtable.\n");
			goto exec_upload_dir_label_00;
		}
		pcs_filist_iterater_init(remote_filelist, &iterater, PcsFalse);
		while(pcs_filist_iterater_next(&iterater)) {
			remote_file = iterater.current;
			if (hashtable_add(ht, remote_file->path, remote_file)) {
				printf("Cannot add object to hashtable.\n");
				goto exec_upload_dir_label_00;
			}
		}
	}

	ents = list_dir(local_path, 0);
	if (!ents) {
		printf("[SKIP] d %s empty directory.\n", local_path);
		goto exec_upload_dir_label_0;
	}
	ent = ents;
	while(ent) {
		dest_path = combin_remote_path(remote_path, ent->filename);
		if (!dest_path) {
			printf("Cannot combin the path.\n");
			goto exec_upload_dir_label_00;
		}
		if (ent->is_dir) {
			if (force || recursion) {
				remote_file = ht ? (PcsFileInfo *)hashtable_get(ht, dest_path) : NULL;
				if (remote_file) {
					remote_file->user_flag = 1;
					printf("[SKIP] d %s\n", ent->path);
				}
				else if (recursion) {
exec_upload_dir_label_6:
					pcsres = pcs_mkdir(pcs, dest_path);
					if (pcsres != PCS_OK) {
						printf("[FAIL] d %s Cannot create the directory %s: %s\n", ent->path, dest_path, pcs_strerror(pcs));
						ric = retry_cancel();
						if (ric == 'r') {
							goto exec_upload_dir_label_6;
						}
						else {
							goto exec_upload_dir_label_00;
						}
					}
					else {
						printf("[SUCC] d %s => %s\n", ent->path, dest_path);
					}
				}
			}
		}
		else {
			remote_file = ht ? (PcsFileInfo *)hashtable_get(ht, dest_path) : NULL;
			if (remote_file) remote_file->user_flag = 1;
			if (force || !remote_file || ((time_t)remote_file->server_mtime) < my_dirent_get_mtime(ent)) {
exec_upload_dir_label_7:
				pcs_setopt(pcs, PCS_OPTION_PROGRESS_FUNCTION_DATE, ent->path);
				pcs_setopt(pcs, PCS_OPTION_PROGRESS, (void *)PcsTrue);
				meta = pcs_upload(pcs, dest_path, PcsTrue, ent->path);
				pcs_setopt(pcs, PCS_OPTION_PROGRESS, (void *)PcsFalse);
				pcs_setopt(pcs, PCS_OPTION_PROGRESS_FUNCTION_DATE, NULL);
				if (!meta) {
					printf("[FAIL] - %s Cannot upload the file: %s\n", ent->path, pcs_strerror(pcs));
					ric = retry_cancel();
					if (ric == 'r') {
						goto exec_upload_dir_label_7;
					}
					else {
						goto exec_upload_dir_label_00;
					}
				}
				printf("[SUCC] - %s => %s\n", ent->path, meta->path);
				pcs_fileinfo_destroy(meta); meta = NULL;
			}
			else {
				printf("[SKIP] - %s\n", ent->path);
			}
		}
		ent = ent->next;
		pcs_free(dest_path); dest_path = NULL;
	}
	if (recursion) {
		ent = ents;
		while(ent) {
			dest_path = combin_remote_path(remote_path, ent->filename);
			if (!dest_path) {
				printf("Cannot combin the path.\n");
				goto exec_upload_dir_label_00;
			}
			if (ent->is_dir) {
				if (exec_upload_dir(pcs, ent->path, dest_path, force, recursion, synch)) {
					goto exec_upload_dir_label_00;
				}
			}
			ent = ent->next;
			pcs_free(dest_path); dest_path = NULL;
		}
	}
	if (synch && ht) {
		hashtable_iterater *iterater;
		PcsSList slist = {0,0};

		iterater = hashtable_iterater_create(ht);
		hashtable_iterater_reset(iterater);
		while(hashtable_iterater_next(iterater)) {
			remote_file = (PcsFileInfo *)hashtable_iterater_current(iterater);
			if (!remote_file->user_flag) {
				slist.string = remote_file->path;
exec_upload_dir_label_8:
				pcsapires = pcs_delete(pcs, &slist);
				if (!pcsapires) {
					printf("[DELETE] [FAIL] %s %s Cannot delete the %s: %s\n",
						remote_file->isdir ? "d" : "-",
						remote_file->path, 
						remote_file->isdir ? "directory" : "fire", pcs_strerror(pcs));
					ric = retry_cancel();
					if (ric == 'r') {
						goto exec_upload_dir_label_8;
					}
					else {
						goto exec_upload_dir_label_00;
					}
				}
				else {
					printf("[DELETE] [SUCC] %s %s \n", remote_file->isdir ? "d" : "-", remote_file->path);
					pcs_pan_api_res_destroy(pcsapires);
				}
			}
		}
		hashtable_iterater_destroy(iterater);
	}
	goto exec_upload_dir_label_0;
exec_upload_dir_label_00:
	res = -1;
exec_upload_dir_label_0:
	if (dest_path) pcs_free(dest_path);
	if (meta) pcs_fileinfo_destroy(meta);
	if (ht) hashtable_destroy(ht);
	if (remote_filelist) pcs_filist_destroy(remote_filelist);
	if (ents) my_dirent_destroy(ents);
	return res;
}
コード例 #27
0
ファイル: FitFibersToImage.cpp プロジェクト: m4271n/MITK
/*!
\brief Fits the tractogram to the input peak image by assigning a weight to each fiber (similar to https://doi.org/10.1016/j.neuroimage.2015.06.092).
*/
int main(int argc, char* argv[])
{
  mitkCommandLineParser parser;

  parser.setTitle("Fit Fibers To Image");
  parser.setCategory("Fiber Tracking and Processing Methods");
  parser.setDescription("Assigns a weight to each fiber in order to optimally explain the input peak image");
  parser.setContributor("MIC");

  parser.setArgumentPrefix("--", "-");
  parser.addArgument("", "i1", mitkCommandLineParser::StringList, "Input tractograms:", "input tractograms (.fib, vtk ascii file format)", us::Any(), false);
  parser.addArgument("", "i2", mitkCommandLineParser::InputFile, "Input image:", "input image", us::Any(), false);
  parser.addArgument("", "o", mitkCommandLineParser::OutputDirectory, "Output:", "output root", us::Any(), false);

  parser.addArgument("max_iter", "", mitkCommandLineParser::Int, "Max. iterations:", "maximum number of optimizer iterations", 20);
  parser.addArgument("bundle_based", "", mitkCommandLineParser::Bool, "Bundle based fit:", "fit one weight per input tractogram/bundle, not for each fiber", false);
  parser.addArgument("min_g", "", mitkCommandLineParser::Float, "Min. g:", "lower termination threshold for gradient magnitude", 1e-5);
  parser.addArgument("lambda", "", mitkCommandLineParser::Float, "Lambda:", "modifier for regularization", 0.1);
  parser.addArgument("save_res", "", mitkCommandLineParser::Bool, "Save Residuals:", "save residual images", false);
  parser.addArgument("save_weights", "", mitkCommandLineParser::Bool, "Save Weights:", "save fiber weights in a separate text file", false);
  parser.addArgument("filter_outliers", "", mitkCommandLineParser::Bool, "Filter outliers:", "perform second optimization run with an upper weight bound based on the first weight estimation (99% quantile)", false);
  parser.addArgument("join_tracts", "", mitkCommandLineParser::Bool, "Join output tracts:", "outout tracts are merged into a single tractogram", false);
  parser.addArgument("regu", "", mitkCommandLineParser::String, "Regularization:", "MSM, Variance, VoxelVariance (default), Lasso, GroupLasso, GroupVariance, NONE");

  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
  if (parsedArgs.size()==0)
    return EXIT_FAILURE;

  mitkCommandLineParser::StringContainerType fib_files = us::any_cast<mitkCommandLineParser::StringContainerType>(parsedArgs["i1"]);
  std::string input_image_name = us::any_cast<std::string>(parsedArgs["i2"]);
  std::string outRoot = us::any_cast<std::string>(parsedArgs["o"]);

  bool single_fib = true;
  if (parsedArgs.count("bundle_based"))
    single_fib = !us::any_cast<bool>(parsedArgs["bundle_based"]);

  bool save_residuals = false;
  if (parsedArgs.count("save_res"))
    save_residuals = us::any_cast<bool>(parsedArgs["save_res"]);

  bool save_weights = false;
  if (parsedArgs.count("save_weights"))
    save_weights = us::any_cast<bool>(parsedArgs["save_weights"]);

  std::string regu = "VoxelVariance";
  if (parsedArgs.count("regu"))
    regu = us::any_cast<std::string>(parsedArgs["regu"]);

  bool join_tracts = false;
  if (parsedArgs.count("join_tracts"))
    join_tracts = us::any_cast<bool>(parsedArgs["join_tracts"]);

  int max_iter = 20;
  if (parsedArgs.count("max_iter"))
    max_iter = us::any_cast<int>(parsedArgs["max_iter"]);

  float g_tol = 1e-5;
  if (parsedArgs.count("min_g"))
    g_tol = us::any_cast<float>(parsedArgs["min_g"]);

  float lambda = 0.1;
  if (parsedArgs.count("lambda"))
    lambda = us::any_cast<float>(parsedArgs["lambda"]);

  bool filter_outliers = false;
  if (parsedArgs.count("filter_outliers"))
    filter_outliers = us::any_cast<bool>(parsedArgs["filter_outliers"]);

  try
  {
    MITK_INFO << "Loading data";
    std::streambuf *old = cout.rdbuf(); // <-- save
    std::stringstream ss;
    std::cout.rdbuf (ss.rdbuf());       // <-- redirect
    std::vector< mitk::FiberBundle::Pointer > input_tracts;

    mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor({"Peak Image", "Fiberbundles"}, {});

    std::vector< std::string > fib_names;
    for (auto item : fib_files)
    {
      if ( ist::FileIsDirectory(item) )
      {
        for ( auto fibFile : get_file_list(item) )
        {
          mitk::FiberBundle::Pointer inputTractogram = mitk::IOUtil::Load<mitk::FiberBundle>(fibFile);
          if (inputTractogram.IsNull())
            continue;
          input_tracts.push_back(inputTractogram);
          fib_names.push_back(fibFile);
        }
      }
      else
      {
        mitk::FiberBundle::Pointer inputTractogram = mitk::IOUtil::Load<mitk::FiberBundle>(item);
        if (inputTractogram.IsNull())
          continue;
        input_tracts.push_back(inputTractogram);
        fib_names.push_back(item);
      }
    }
    std::cout.rdbuf (old);              // <-- restore

    itk::FitFibersToImageFilter::Pointer fitter = itk::FitFibersToImageFilter::New();

    mitk::BaseData::Pointer inputData = mitk::IOUtil::Load(input_image_name, &functor)[0].GetPointer();
    mitk::Image::Pointer mitk_image = dynamic_cast<mitk::Image*>(inputData.GetPointer());
    mitk::PeakImage::Pointer mitk_peak_image = dynamic_cast<mitk::PeakImage*>(inputData.GetPointer());
    if (mitk_peak_image.IsNotNull())
    {
      typedef mitk::ImageToItk< mitk::PeakImage::ItkPeakImageType > CasterType;
      CasterType::Pointer caster = CasterType::New();
      caster->SetInput(mitk_peak_image);
      caster->Update();
      mitk::PeakImage::ItkPeakImageType::Pointer peak_image = caster->GetOutput();
      fitter->SetPeakImage(peak_image);
    }
    else if (mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage(mitk_image))
    {
      fitter->SetDiffImage(mitk::DiffusionPropertyHelper::GetItkVectorImage(mitk_image));
      mitk::TensorModel<>* model = new mitk::TensorModel<>();
      model->SetBvalue(1000);
      model->SetDiffusivity1(0.0010);
      model->SetDiffusivity2(0.00015);
      model->SetDiffusivity3(0.00015);
      model->SetGradientList(mitk::DiffusionPropertyHelper::GetGradientContainer(mitk_image));
      fitter->SetSignalModel(model);
    }
    else if (mitk_image->GetDimension()==3)
    {
      itk::FitFibersToImageFilter::DoubleImgType::Pointer scalar_image = itk::FitFibersToImageFilter::DoubleImgType::New();
      mitk::CastToItkImage(mitk_image, scalar_image);
      fitter->SetScalarImage(scalar_image);
    }
    else
    {
      MITK_INFO << "Input image invalid. Valid options are peak image, 3D scalar image or raw diffusion-weighted image.";
      return EXIT_FAILURE;
    }

    fitter->SetTractograms(input_tracts);
    fitter->SetFitIndividualFibers(single_fib);
    fitter->SetMaxIterations(max_iter);
    fitter->SetGradientTolerance(g_tol);
    fitter->SetLambda(lambda);
    fitter->SetFilterOutliers(filter_outliers);

    if (regu=="MSM")
      fitter->SetRegularization(VnlCostFunction::REGU::MSM);
    else if (regu=="Variance")
      fitter->SetRegularization(VnlCostFunction::REGU::VARIANCE);
    else if (regu=="Lasso")
      fitter->SetRegularization(VnlCostFunction::REGU::LASSO);
    else if (regu=="VoxelVariance")
      fitter->SetRegularization(VnlCostFunction::REGU::VOXEL_VARIANCE);
    else if (regu=="GroupLasso")
      fitter->SetRegularization(VnlCostFunction::REGU::GROUP_LASSO);
    else if (regu=="GroupVariance")
      fitter->SetRegularization(VnlCostFunction::REGU::GROUP_VARIANCE);
    else if (regu=="NONE")
      fitter->SetRegularization(VnlCostFunction::REGU::NONE);

    fitter->Update();

    if (save_residuals && mitk_peak_image.IsNotNull())
    {
      itk::ImageFileWriter< PeakImgType >::Pointer writer = itk::ImageFileWriter< PeakImgType >::New();
      writer->SetInput(fitter->GetFittedImage());
      writer->SetFileName(outRoot + "_fitted.nii.gz");
      writer->Update();

      writer->SetInput(fitter->GetResidualImage());
      writer->SetFileName(outRoot + "_residual.nii.gz");
      writer->Update();

      writer->SetInput(fitter->GetOverexplainedImage());
      writer->SetFileName(outRoot + "_overexplained.nii.gz");
      writer->Update();

      writer->SetInput(fitter->GetUnderexplainedImage());
      writer->SetFileName(outRoot + "_underexplained.nii.gz");
      writer->Update();
    }
    else if (save_residuals && mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage(mitk_image))
    {
      {
        mitk::Image::Pointer outImage = mitk::GrabItkImageMemory( fitter->GetFittedImageDiff().GetPointer() );
        mitk::DiffusionPropertyHelper::CopyProperties(mitk_image, outImage, true);
        mitk::DiffusionPropertyHelper propertyHelper( outImage );
        propertyHelper.InitializeImage();
        mitk::IOUtil::Save(outImage, "application/vnd.mitk.nii.gz", outRoot + "_fitted_image.nii.gz");
      }

      {
        mitk::Image::Pointer outImage = mitk::GrabItkImageMemory( fitter->GetResidualImageDiff().GetPointer() );
        mitk::DiffusionPropertyHelper::CopyProperties(mitk_image, outImage, true);
        mitk::DiffusionPropertyHelper propertyHelper( outImage );
        propertyHelper.InitializeImage();
        mitk::IOUtil::Save(outImage, "application/vnd.mitk.nii.gz", outRoot + "_residual_image.nii.gz");
      }

      {
        mitk::Image::Pointer outImage = mitk::GrabItkImageMemory( fitter->GetOverexplainedImageDiff().GetPointer() );
        mitk::DiffusionPropertyHelper::CopyProperties(mitk_image, outImage, true);
        mitk::DiffusionPropertyHelper propertyHelper( outImage );
        propertyHelper.InitializeImage();
        mitk::IOUtil::Save(outImage, "application/vnd.mitk.nii.gz", outRoot + "_overexplained_image.nii.gz");
      }

      {
        mitk::Image::Pointer outImage = mitk::GrabItkImageMemory( fitter->GetUnderexplainedImageDiff().GetPointer() );
        mitk::DiffusionPropertyHelper::CopyProperties(mitk_image, outImage, true);
        mitk::DiffusionPropertyHelper propertyHelper( outImage );
        propertyHelper.InitializeImage();
        mitk::IOUtil::Save(outImage, "application/vnd.mitk.nii.gz", outRoot + "_underexplained_image.nii.gz");
      }
    }
    else if (save_residuals)
    {
      itk::ImageFileWriter< itk::FitFibersToImageFilter::DoubleImgType >::Pointer writer = itk::ImageFileWriter< itk::FitFibersToImageFilter::DoubleImgType >::New();
      writer->SetInput(fitter->GetFittedImageScalar());
      writer->SetFileName(outRoot + "_fitted_image.nii.gz");
      writer->Update();

      writer->SetInput(fitter->GetResidualImageScalar());
      writer->SetFileName(outRoot + "_residual_image.nii.gz");
      writer->Update();

      writer->SetInput(fitter->GetOverexplainedImageScalar());
      writer->SetFileName(outRoot + "_overexplained_image.nii.gz");
      writer->Update();

      writer->SetInput(fitter->GetUnderexplainedImageScalar());
      writer->SetFileName(outRoot + "_underexplained_image.nii.gz");
      writer->Update();
    }

    std::vector< mitk::FiberBundle::Pointer > output_tracts = fitter->GetTractograms();

    if (!join_tracts)
    {
      for (unsigned int bundle=0; bundle<output_tracts.size(); bundle++)
      {
        std::string name = fib_names.at(bundle);
        name = ist::GetFilenameWithoutExtension(name);
        mitk::IOUtil::Save(output_tracts.at(bundle), outRoot + name + "_fitted.fib");

        if (save_weights)
        {
          ofstream logfile;
          logfile.open (outRoot + name + "_weights.txt");
          for (int f=0; f<output_tracts.at(bundle)->GetNumFibers(); ++f)
            logfile << output_tracts.at(bundle)->GetFiberWeight(f) << "\n";
          logfile.close();
        }
      }
    }
    else
    {
      mitk::FiberBundle::Pointer out = mitk::FiberBundle::New();
      out = out->AddBundles(output_tracts);
      out->ColorFibersByFiberWeights(false, true);
      mitk::IOUtil::Save(out, outRoot + "_fitted.fib");

      if (save_weights)
      {
        ofstream logfile;
        logfile.open (outRoot + "_weights.txt");
        for (int f=0; f<out->GetNumFibers(); ++f)
          logfile << out->GetFiberWeight(f) << "\n";
        logfile.close();
      }
    }
  }
  catch (itk::ExceptionObject e)
  {
    std::cout << e;
    return EXIT_FAILURE;
  }
  catch (std::exception e)
  {
    std::cout << e.what();
    return EXIT_FAILURE;
  }
  catch (...)
  {
    std::cout << "ERROR!?!";
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
コード例 #28
0
/*!
\brief
*/
int main(int argc, char* argv[])
{
  mitkCommandLineParser parser;

  parser.setTitle("Extract Overlapping Tracts");
  parser.setCategory("Fiber Tracking Evaluation");
  parser.setDescription("");
  parser.setContributor("MIC");

  parser.setArgumentPrefix("--", "-");
  parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input:", "input tractogram (.fib, vtk ascii file format)", us::Any(), false);
  parser.addArgument("out", "o", mitkCommandLineParser::OutputDirectory, "Output:", "output folder", us::Any(), false);
  parser.addArgument("reference_mask_folder", "m", mitkCommandLineParser::String, "Reference Mask Folder:", "reference masks of known bundles", us::Any(), false);
  parser.addArgument("gray_matter_mask", "gm", mitkCommandLineParser::String, "GM mask:", "remove fibers not ending in the gray matter");
  parser.addArgument("anchor_fraction", "", mitkCommandLineParser::Float, "Anchor fraction:", "Fraction of tracts used as anchors", 0.5);
  parser.addArgument("overlap", "", mitkCommandLineParser::Float, "Overlap threshold:", "Overlap threshold used to identify the anchor tracts", 0.8);
  parser.addArgument("subsample", "", mitkCommandLineParser::Float, "Subsampling factor:", "Only use specified fraction of input fibers for the analysis", 1.0);
  parser.addArgument("random_seed", "", mitkCommandLineParser::Int, ":", "", -1);

  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
  if (parsedArgs.size()==0)
    return EXIT_FAILURE;

  std::string fibFile = us::any_cast<std::string>(parsedArgs["input"]);
  std::string reference_mask_folder = us::any_cast<std::string>(parsedArgs["reference_mask_folder"]);
  std::string out_folder = us::any_cast<std::string>(parsedArgs["out"]);

  std::string gray_matter_mask = "";
  if (parsedArgs.count("gray_matter_mask"))
    gray_matter_mask = us::any_cast<std::string>(parsedArgs["gray_matter_mask"]);

  float anchor_fraction = 0.5;
  if (parsedArgs.count("anchor_fraction"))
    anchor_fraction = us::any_cast<float>(parsedArgs["anchor_fraction"]);

  int random_seed = -1;
  if (parsedArgs.count("random_seed"))
    random_seed = us::any_cast<int>(parsedArgs["random_seed"]);

  float overlap = 0.8;
  if (parsedArgs.count("overlap"))
    overlap = us::any_cast<float>(parsedArgs["overlap"]);

  float subsample = 1.0;
  if (parsedArgs.count("subsample"))
    subsample = us::any_cast<float>(parsedArgs["subsample"]);

  try
  {
    CreateFolderStructure(out_folder);
    std::vector< MaskType > known_tract_masks = get_file_list(reference_mask_folder, anchor_fraction, out_folder + "/skipped_masks/", random_seed);
    mitk::FiberBundle::Pointer inputTractogram = dynamic_cast<mitk::FiberBundle*>(mitk::IOUtil::Load(fibFile)[0].GetPointer());

    if (gray_matter_mask.compare("")!=0)
    {
      MITK_INFO << "Removing fibers not ending inside of GM";
      std::streambuf *old = cout.rdbuf(); // <-- save
      std::stringstream ss;
      std::cout.rdbuf (ss.rdbuf());       // <-- redirect
      ItkFloatImgType::Pointer gm_image = LoadItkImage(gray_matter_mask);
      std::cout.rdbuf (old);              // <-- restore

      itk::FiberExtractionFilter<unsigned char>::Pointer extractor = itk::FiberExtractionFilter<unsigned char>::New();
      extractor->SetInputFiberBundle(inputTractogram);
      extractor->SetRoiImages({gm_image});
      extractor->SetBothEnds(true);
      extractor->SetNoNegatives(true);
      extractor->SetMode(itk::FiberExtractionFilter<unsigned char>::MODE::ENDPOINTS);
      extractor->Update();
      inputTractogram = extractor->GetPositives().at(0);
    }

    std::srand(0);
    if (subsample<1.0)
      inputTractogram = inputTractogram->SubsampleFibers(subsample);

    mitk::FiberBundle::Pointer anchor_tractogram = mitk::FiberBundle::New(nullptr);
    mitk::FiberBundle::Pointer candidate_tractogram = mitk::FiberBundle::New(nullptr);
    if (!known_tract_masks.empty())
    {
      MITK_INFO << "Find known tracts via overlap match";
      std::vector< ItkFloatImgType::Pointer > mask_images;
      for (auto mask : known_tract_masks)
        mask_images.push_back(std::get<0>(mask));

      std::vector< ItkFloatImgType* > roi_images2;
      for (auto roi : mask_images)
        roi_images2.push_back(roi);

      itk::FiberExtractionFilter<unsigned char>::Pointer extractor = itk::FiberExtractionFilter<unsigned char>::New();
      extractor->SetInputFiberBundle(inputTractogram);
      extractor->SetRoiImages(roi_images2);
      extractor->SetOverlapFraction(overlap);
      extractor->SetMode(itk::FiberExtractionFilter<unsigned char>::MODE::OVERLAP);
      extractor->Update();
      std::vector< mitk::FiberBundle::Pointer > positives = extractor->GetPositives();
      candidate_tractogram = extractor->GetNegatives().at(0);

      for ( unsigned int i=0; i<known_tract_masks.size(); ++i )
      {
        std::streambuf *old = cout.rdbuf(); // <-- save
        std::stringstream ss;
        std::cout.rdbuf (ss.rdbuf());       // <-- redirect

        std::string mask_name = std::get<1>(known_tract_masks.at(i));
        mitk::IOUtil::Save(positives.at(i), out_folder + "/anchor_tracts/" + mask_name + ".trk");

        std::cout.rdbuf (old);              // <-- restore
      }
      anchor_tractogram = anchor_tractogram->AddBundles(positives);
    }

    mitk::IOUtil::Save(anchor_tractogram, out_folder + "/anchor_tracts/anchor_tractogram.trk");
    mitk::IOUtil::Save(candidate_tractogram, out_folder + "/candidate_tracts/candidate_tractogram.trk");
    mitk::IOUtil::Save(inputTractogram, out_folder + "/filtered_tractogram.trk");
  }
  catch (itk::ExceptionObject e)
  {
    std::cout << e;
    return EXIT_FAILURE;
  }
  catch (std::exception e)
  {
    std::cout << e.what();
    return EXIT_FAILURE;
  }
  catch (...)
  {
    std::cout << "ERROR!?!";
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
コード例 #29
0
/* 
 * recurence function for building file list
 * 
 * in:
 *    list - current filename list
 *    base - indicate if filename path is relative or absolute
 *           '$ROOT$' - path is absolute, no need to concatenate both
 *           other => absolute filename path = $base/$path
 *    path - filename path (file or directory)
 * out:
 *    list->key - full pathname to backup file
 *    list->value - relative filename
 */
keylist * get_file_list ( keylist * list, const char * base, const char * path ){

   int err;
   struct stat st;
   DIR * dirp;
   DIR * dirp_tab;
   char * npath = NULL;
   char * bpath = NULL;
   char * link = NULL;
   keylist * nlist = list;
   struct dirent * filedir;
   struct dirent * filedir_tab;
   int dl;
   int plen = strlen ( path );


   bpath = MALLOC ( PATH_MAX );
   if ( ! bpath )
      return list;

   if ( strncmp ( base, "$ROOT$", PATH_MAX ) == 0 ){
      /* indicate a path variable include absolute filename path */
      strncpy ( bpath, path, PATH_MAX );
   } else {
      /* bpath has a real and absolute path into a filename as $base/$path,
       * path has a relative filename path
       * first concatenate a path for normalise */
      snprintf ( bpath, PATH_MAX, "%s/%s",
            base, path );
   }
   /* bpath has a full path for analized filename/directory */
   err = lstat ( bpath, &st );

   if ( err ){
      printf ( "stat error on %s.\n", path );
      FREE ( bpath );
      return list;
   }

   if ( S_ISDIR (st.st_mode) ){
//      printf ( "found: %s\n", bpath );
//      printf ( "add dir to the list\n" );

      if ( strncmp ( base, "$ROOT$", PATH_MAX ) == 0 ){
         nlist = add_keylist_attr ( nlist, base, bpath, PG_DIR );
      } else {
         //nlist = add_keylist ( nlist, bpath, plen ? path : "$BASE$" );
         nlist = add_keylist_attr ( nlist, bpath, path, PG_DIR );
      }

      dirp = opendir ( bpath );
      if ( !dirp ){
         FREE ( bpath );
         return nlist;
      }

      while ( ( filedir = readdir ( dirp ) ) ){
         /* check for tablespaces when path is empty and base has a absolute path */
         if ( strcmp ( filedir->d_name, "pg_tblspc" ) == 0 && plen == 0 ){

            /* add all tablespaces into a list */
            nlist = get_file_list ( nlist, base, "pg_tblspc" );

            /* building an absolute path for base variable */
            snprintf ( bpath, PATH_MAX, "%s/pg_tblspc", base );

            dirp_tab = opendir ( bpath );

            if ( !dirp_tab ){
               FREE ( bpath );
               return nlist;
            }

            /* all tablespaces are symbolic links into a destination location */
            while ( (filedir_tab = readdir ( dirp_tab )) ){
               if ( strcmp ( filedir_tab->d_name, "." ) != 0 &&
                    strcmp ( filedir_tab->d_name, ".." ) != 0 ){

//                  printf ("tablespace found: %s\n", filedir_tab->d_name );

                  link = MALLOC ( PATH_MAX );
                  if ( ! link ){
                     FREE ( bpath );
                     return nlist;
                  }

                  /* building an absolute path for a link */
                  snprintf ( bpath, PATH_MAX, "%s/pg_tblspc/%s",
                        base, filedir_tab->d_name );

                  dl = readlink ( bpath, link, PATH_MAX - 1 );
                  if ( dl < 0 ){
                     printf ("ERR: %s\n", strerror ( errno ) );
                     FREE ( bpath );
                     FREE ( link );
                     closedir ( dirp_tab );
                     return nlist;
                  }
                  link [ dl ] = 0;
//                  printf ( "dl %i, %s\n", dl, link );

                  /* check if link is absolute or not */
                  if ( link [ 0 ] == '/' ){
                     strncpy ( bpath, link, PATH_MAX );
                  } else {
                     /* according to PostgreSQL a tablespace location has to be an absolute,
                      * if not we have an error, raise it. */
                     printf ( "Relative link Error!\n" );
                     FREE ( bpath );
                     FREE ( link );
                     closedir ( dirp_tab );
                     return nlist;
                     //snprintf ( bpath, PATH_MAX, "%s/pg_tblspc/%s",
                     //      base, link );
                  }

                  /* all tablespaces are backuped with absolute path */
                  link = realpath ( bpath, link );

//                  printf ( "filelink %s\n", link );

                  nlist = get_file_list ( nlist, "$ROOT$", link );

                  FREE ( link );
               }
            }
            closedir ( dirp_tab );
         } else {
//            printf ("found: %s\n", filedir->d_name );
            if ( strcmp ( filedir->d_name, "." ) != 0 &&
                 strcmp ( filedir->d_name, ".." ) != 0 &&
                 strcmp ( filedir->d_name, "pg_xlog" ) != 0
                 ){

               npath = MALLOC ( PATH_MAX );
               snprintf ( npath, PATH_MAX, plen ? "%s/%s" : "%s%s",
                     path, filedir->d_name );
               nlist = get_file_list ( nlist, base, npath );
               FREE ( npath );
            } else {
//               printf ("ignored\n");
            }
         }
      }
      closedir ( dirp );
   } else
   if ( S_ISLNK ( st.st_mode ) ){
      /* indicate filetype of link */
      if ( strncmp ( base, "$ROOT$", PATH_MAX ) == 0 ){
         nlist = add_keylist_attr ( nlist, base, path, PG_LINK );
      } else {
         nlist = add_keylist_attr ( nlist, bpath, path, PG_LINK );
      }
   } else
   if ( S_ISREG ( st.st_mode ) ){
      /* indicate filetype of regular file */
      if ( strncmp ( base, "$ROOT$", PATH_MAX ) == 0 ){
         nlist = add_keylist_attr ( nlist, base, path, PG_FILE );
      } else {
         nlist = add_keylist_attr ( nlist, bpath, path, PG_FILE );
      }
   }
   FREE ( bpath );
   return nlist;
}
コード例 #30
0
ファイル: guifilelist.c プロジェクト: hiro2233/libspmp8k-1
int file_selector(char *result) {
	SDL_Event ev;
	int picked = 0;
//	int max_width = tiawidth/FONT_WIDTH;
	int max_height = MaxLines/FONT_HEIGHT; //-1;
	int k = 0;

	if (PaletteNumber != UserPaletteNumber)
	{
		PaletteNumber = UserPaletteNumber;
		gui_SetVideoMode();
	}
	clrscr();

	/* filesread is a global that gets updated by get_list */
	if (first_filelist) 
	{
		get_file_list();
		first_filelist = 0;
	}

	while(!picked) {
		int action;

		window_line = draw_file_list(curfile, window_line, max_height-2);
		SDL_WaitEvent(&ev);

		action = gui_navigation( &ev );

//		if(action == GUI_NO_ACTION)
//			continue;

		switch(action) 
		{
		char type;

		case GUI_EXIT_GUI:
			clrscr();
			return 0; /* abort */

		case GUI_ACTIVATE_SEC:
			match = 0;
			curfile++;
			if(curfile == filesread) curfile = 0;
			clrscr();
			type = file_list[curfile][strlen(file_list[curfile])-1];
			if(type == '/')	/* if it's a dir, cd to it and get new file list. */
			{
				if (chdir(file_list[curfile]) == 0)
				{
					curfile = 0;
					get_file_list();
				}
			} 
			else		/* if it's a file, return it */
			{
				strcpy(result, file_list[curfile]);
				picked = 1;
			}
			break;
		
		
		case GUI_ACTIVATE_PRI:
			match = 0;
			clrscr();
			type = file_list[curfile][strlen(file_list[curfile])-1];
			if(type == '/')	/* if it's a dir, cd to it and get new file list. */
			{
				if (chdir(file_list[curfile]) == 0)
				{
					curfile = 0;
					get_file_list();
				}
			} 
			else		/* if it's a file, return it */
			{
				strcpy(result, file_list[curfile]);
				picked = 1;
			}
			break;

		case GUI_UP:
			match = 0;
			curfile--;
			if(curfile < 0) curfile = filesread - 1;
			break;

		case GUI_DOWN:
			match = 0;
			curfile++;
			if(curfile == filesread) curfile = 0;
			break;

		case GUI_PAGEDOWN:
			match = 0;
			if(filesread > max_height-1) {
				curfile += max_height-1;
				if(curfile >= filesread)
					curfile = 0;
				window_line = curfile;
				clrscr();
			}
			break;

		case GUI_PAGEUP:
			match = 0;
			if(filesread > max_height-1) {
				curfile -= max_height-1;
				if(curfile < 0)
					curfile = filesread-1;
				window_line = curfile;
				clrscr();
				break;
			}

		case GUI_HOME:
			match = 0;
			curfile = 0;
			window_line = 0;
			clrscr();
			break;

		case GUI_END:
			match = 0;
			curfile = filesread-1;
			window_line = curfile;
			clrscr();
			break;
			
		case GUI_RANDOM:
			match = 0;
			curfile = rand() % filesread;
			window_line = curfile;
			type = file_list[curfile][strlen(file_list[curfile])-1];
			
			while (type == '/')	/* if it's a dir, find another file */
			{
				curfile = rand() % filesread;
				window_line = curfile;
				type = file_list[curfile][strlen(file_list[curfile])-1];
			} 
			
			
			
			clrscr();
			break;


		default:
			if(ev.type == SDL_KEYDOWN)
			{
				k = ev.key.keysym.sym;
				curfile = window_line = find_next_rom(curfile, k);
			}
			break;
		}

		SDL_WM_SetCaption(file_list[curfile], file_list[curfile]);

	}
	
	return picked;
}