void end_read(const boost::system::error_code &ec, std::size_t bytes_transferred) { if (!ec) { pending_read_buffer_ += std::string(read_buffer_.data(), bytes_transferred); while (pending_read_buffer_.size() > sizeof(inotify_event)) { const inotify_event *iev = reinterpret_cast<const inotify_event*>(pending_read_buffer_.data()); dir_monitor_event::event_type type = dir_monitor_event::null; switch (iev->mask) { case IN_CREATE: type = dir_monitor_event::added; break; case IN_DELETE: type = dir_monitor_event::removed; break; case IN_MODIFY: type = dir_monitor_event::modified; break; case IN_MOVED_FROM: type = dir_monitor_event::renamed_old_name; break; case IN_MOVED_TO: type = dir_monitor_event::renamed_new_name; break; case IN_CREATE | IN_ISDIR: { type = dir_monitor_event::added; add_directory(get_dirname(iev->wd) + "/" + iev->name); break; } } pushback_event(dir_monitor_event(boost::filesystem::path(get_dirname(iev->wd)) / iev->name, type)); pending_read_buffer_.erase(0, sizeof(inotify_event) + iev->len); } begin_read(); } else if (ec != boost::asio::error::operation_aborted) { boost::system::system_error e(ec); boost::throw_exception(e); } }
const char *get_asf_share_dir_with_argv0(const char *argv0) { #ifdef win32 // "realpath" not available on Windows char *argv0_real_path = STRDUP(argv0); #else // handle use of "./mapready" etc char *argv0_real_path = realpath(argv0, NULL); if (!argv0_real_path) { // probably user did not specify a path when running MapReady // so, can use the normal method for finding the share dir return get_asf_share_dir(); } #endif // strip off the executable, leaving just the path info char *argv0_path = get_dirname(argv0_real_path); if (!s_argv0) s_argv0 = STRDUP(argv0_path); #ifndef win32 // If the user specified a path on the command line, we want to // try that directory first, when searching for the share dir. // If this doesn't work, in get_asf_share_dir(), called below, we will // use the normal path-searching method to find the share dir. If this // does work, then the call below will just return what we've already // found. if (!s_share_dir) { // obtain what needs to be pasted on to the location of the bin dir // to get to the share dir (i.e. "share/asf_tools") char *share = strstr(ASF_SHARE_DIR, "share"); if (share) { if (argv0_path && strlen(argv0_path) > 0) { // a copy for us to change "whatever/bin" to "whatever/share/asf_tools" char *buf = MALLOC(sizeof(char)*(strlen(argv0_path) + strlen(share) + strlen(TOOL_SUITE_SHARE_DIR) + 5)); strcpy(buf, argv0_path); // only try this if the binary location ends with 'bin' if (strcmp(buf + strlen(buf) - 4, "bin/") == 0) { // strip off "bin" - add "share/asf_tools" *(buf + strlen(buf) - 4) = '\0'; strcat(buf, share); strcat(buf, "/"); strcat(buf, TOOL_SUITE_SHARE_DIR); if (check_for_known_file_in_share_dir(buf)) { // this is the one! s_share_dir = STRDUP(buf); } } FREE(buf); } } } #endif FREE(argv0_path); FREE(argv0_real_path); return get_asf_share_dir(); }
char *get_terrasar_browse_file(const char *xml_file_name) { xmlDoc *doc = xmlReadFile(xml_file_name, NULL, 0); if (!doc) { asfPrintWarning("Could not parse file %s\n", xml_file_name); return NULL; } char preview_file[2048]; char *path = get_dirname(xml_file_name); if (strlen(path)>0) { strcpy(preview_file, path); if (preview_file[strlen(preview_file)-1] != '/') strcat(preview_file, "/"); } else strcpy(preview_file, ""); free(path); strcat(preview_file, xml_get_string_value(doc, "level1Product.productComponents.browseImage.file.location.path")); strcat(preview_file, "/"); strcat(preview_file, xml_get_string_value(doc, "level1Product.productComponents.browseImage.file.location.filename")); return STRDUP(preview_file); }
static void set_defaults(ImageInfo *ii) { // default filename char *basename = get_basename(ii->filename); char *def = appendStr(basename, "_aoi"); if (strncmp_case(def, "LED-", 4) == 0 || strncmp_case(def, "IMG-", 4) == 0 || strncmp_case(def, "TRL-", 4) == 0 || strncmp_case(def, "VOL-", 4) == 0) { char *tmp = STRDUP(def+4); free(def); def = tmp; } free(basename); put_string_to_entry("filename_entry", def); free(def); // default directory char *dir = get_dirname(ii->filename); if (dir && strlen(dir) > 0) put_string_to_entry("dir_entry", dir); else put_string_to_entry("dir_entry", ""); FREE(dir); // default data to save (Pixel Values) set_combo_box_item("data_combobox", 0); }
/** * <JA> * jconf 設定ファイルを読み込んで解析し,対応するオプションを設定する. * オプション内の相対パスは、その jconf 設定ファイルからの相対となる. * * @param conffile [in] jconf ファイルのパス名 * @param jconf [out] 値をセットする jconf 設定データ * </JA> * <EN> * Read and parse a jconf file, and set the specified option values. * Relative paths in the file will be treated as relative to the file, * not the application current. * * @param conffile [in] jconf file path name * @param jconf [out] global configuration data to be written. * </EN> * * @callgraph * @callergraph */ boolean config_file_parse(char *conffile, Jconf *jconf) { int c_argc; char **c_argv; FILE *fp; int maxnum; char buf[BUFLEN]; char *cdir; int i; boolean ret; jlog("STAT: include config: %s\n", conffile); /* set the content of jconf file into argument list c_argv[1..c_argc-1] */ /* c_argv[0] will be the original conffile name */ /* inside jconf file, quoting by ", ' and escape by '\' is supported */ if ((fp = fopen(conffile, "r")) == NULL) { jlog("ERROR: m_jconf: failed to open jconf file: %s\n", conffile); return FALSE; } maxnum = 20; c_argv = (char **)mymalloc(sizeof(char *) * maxnum); c_argv[0] = strcpy((char *)mymalloc(strlen(conffile)+1), conffile); c_argc = 1; while (fgets_jconf(buf, BUFLEN, fp) != NULL) { if (buf[0] == '\0') continue; add_to_arglist(buf, &c_argv, &c_argc, &maxnum); } if (fclose(fp) == -1) { jlog("ERROR: m_jconf: cannot close jconf file\n"); return FALSE; } /* env expansion */ for (i=1;i<c_argc;i++) { c_argv[i] = expand_env(c_argv[i]); } if (debug2_flag) { /* for debug */ jlog("DEBUG: args:"); for (i=1;i<c_argc;i++) jlog(" %s",c_argv[i]); jlog("\n"); } /* now that options are in c_argv[][], call opt_parse() to process them */ /* relative paths in jconf file are relative to the jconf file (not current) */ cdir = strcpy((char *)mymalloc(strlen(conffile)+1), conffile); get_dirname(cdir); ret = opt_parse(c_argc, c_argv, (cdir[0] == '\0') ? NULL : cdir, jconf); free(cdir); /* free arguments */ while (c_argc-- > 0) { free(c_argv[c_argc]); } free(c_argv); return(ret); }
int find_existing_directory_ancestor(char *ancestor, size_t ancestor_size, const char *path) { int error; char dir_path[PATH_MAX]; struct stat info; if (!ancestor || ancestor_size < 1) return ENOBUFS; *ancestor = 0; strncpy(dir_path, path, sizeof(dir_path)); if (dir_path[sizeof(dir_path)-1] != '\0') return ENOBUFS; while (strcmp(dir_path, "/") != 0) { if (lstat(dir_path, &info) < 0) { error = errno; if (error != ENOENT) return error; } else { if (S_ISDIR(info.st_mode)) break; } error = get_dirname(dir_path, sizeof(dir_path), dir_path); if (error != SUCCESS) { return error; } } strncpy(ancestor, dir_path, ancestor_size); if (ancestor[ancestor_size-1] != '\0') return ENOBUFS; return SUCCESS; }
int xmp_load_module(xmp_context opaque, char *path) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; HIO_HANDLE *h; struct stat st; struct list_head tmpfiles_list; D_(D_WARN "path = %s", path); if (stat(path, &st) < 0) return -XMP_ERROR_SYSTEM; #ifndef _MSC_VER if (S_ISDIR(st.st_mode)) { errno = EISDIR; return -XMP_ERROR_SYSTEM; } #endif if ((h = hio_open_file(path, "rb")) == NULL) return -XMP_ERROR_SYSTEM; INIT_LIST_HEAD(&tmpfiles_list); D_(D_INFO "decrunch"); if (decrunch(&tmpfiles_list, &h->f, &path, DECRUNCH_MAX) < 0) goto err_depack; if (hio_stat(h, &st) < 0) goto err_depack; if (st.st_size < 256) { /* get size after decrunch */ hio_close(h); unlink_tempfiles(&tmpfiles_list); return -XMP_ERROR_FORMAT; } if (ctx->state > XMP_STATE_UNLOADED) xmp_release_module(opaque); m->dirname = get_dirname(path); if (m->dirname == NULL) return -XMP_ERROR_SYSTEM; m->basename = get_basename(path); if (m->basename == NULL) return -XMP_ERROR_SYSTEM; m->filename = path; /* For ALM, SSMT, etc */ m->size = st.st_size; return load_module(opaque, h, &tmpfiles_list); err_depack: hio_close(h); unlink_tempfiles(&tmpfiles_list); return -XMP_ERROR_DEPACK; }
int handle_terrasar_file(const char *filename, char *meta_name, char *data_name, char **err) { // allocate error buffer, just in case we need it *err = (char *) MALLOC(sizeof(char)*1024); // check for metadata if (!fileExists(filename)) meta_name = appendExt(filename, ".xml"); else strcpy(meta_name, filename); if (!fileExists(meta_name)) { sprintf(*err, "Error opening TerraSAR-X file, metadata file (%s) does " "not exist!\n", meta_name); return FALSE; } xmlDoc *doc = xmlReadFile(meta_name, NULL, 0); if (!doc) { sprintf(*err, "Could not parse file %s\n", meta_name); return FALSE; } // path from the xml (metadata) file char *path = get_dirname(filename); if (strlen(path)>0) { strcpy(data_name, path); if (data_name[strlen(data_name)-1] != '/') strcat(data_name, "/"); } else strcpy(data_name, ""); free(path); // strcat() on the path & file from the XML entry strcat(data_name, xml_get_string_value(doc, "level1Product.productComponents.imageData[0].file.location.path")); strcat(data_name, "/"); strcat(data_name, xml_get_string_value(doc, "level1Product.productComponents.imageData[0].file.location.filename")); if (!fileExists(data_name)) { sprintf(*err, "Data file (%s) does not exist!\n", data_name); return FALSE; } // check data type terrasar_meta *terrasar = read_terrasar_meta(meta_name); if (!strcmp_case(terrasar->imageDataType, "COMPLEX") == 0 && !strcmp_case(terrasar->imageDataFormat, "COSAR") == 0) { sprintf(*err, "Data type (%s) and data format (%s) currently not " "supported!\n", terrasar->imageDataType, terrasar->imageDataFormat); return FALSE; } FREE(*err); err = NULL; return TRUE; }
void f_local_fwriter::open_file () { #ifdef _WIN32 if (f_handle_ != INVALID_HANDLE_VALUE) return; create_directory (get_dirname (f_name_)); int flag = OPEN_EXISTING; open_again: f_handle_ = ::CreateFileA (f_name_.c_str (), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, flag, FILE_ATTRIBUTE_NORMAL, 0); if(f_handle_ == INVALID_HANDLE_VALUE) { UINT lasterror = GetLastError (); if (lasterror == ERROR_FILE_NOT_FOUND || lasterror == ERROR_PATH_NOT_FOUND) { flag = CREATE_NEW; goto open_again; } else { std::string errmsg = fmt_string ("Can't not open file %s.", f_name_.c_str ()); THROW_XDELTA_EXCEPTION (errmsg); } } #else if (f_fd_ > 0) return; int flag = O_WRONLY | O_BINARY; int mode = 0; open_again: f_fd_ = open (f_name_.c_str (), flag, mode); if (f_fd_ < 0) { if (errno == ENOENT) { flag = O_CREAT | O_EXCL | O_RDWR | O_BINARY; mode = S_IREAD | S_IWRITE; goto open_again; } else { std::string errmsg = fmt_string ("Can't not open file %s.", f_name_.c_str ()); THROW_XDELTA_EXCEPTION (errmsg); } } #endif }
bool CTar32::extract(const char *fname_extract_to) { std::string fname; if(fname_extract_to){ fname = fname_extract_to; }else{ fname = m_currentfile_status.filename; } size64 filesize = m_currentfile_status.original_size; const int buf_size = 4096; char buf[buf_size]; CTar32InternalFile file; file.open(this); //string dirname = get_dirname(fname.c_str()); //mkdir_recursive(dirname.c_str()); mkdir_recursive(get_dirname(fname.c_str()).c_str()); //std::ofstream fs_w; fast_fstream fs_w; fs_w.open(fname.c_str(), std::ios::out|std::ios::binary); if(fs_w.fail()){return false;} //FILE *fp_w = fopen(fname.c_str(), "wb"); //if(fp_w == NULL){ // return false; //} size64 readsize = 0; while(filesize==-1 || readsize<filesize){ size64 nextreadsize = (filesize==-1) ? buf_size : min(filesize-readsize,buf_size); size64 n = file.read(buf,nextreadsize); fs_w.write(buf,nextreadsize); if(fs_w.fail()){ if(filesize==-1){ return true; }else{ return false; } } //fwrite(buf,1,ret,fp_w); readsize += n; if(n != nextreadsize){/*fclose(fp_w);*/return false;} } //fclose(fp_w); return true; }
/* walk through the directory of the loaded file and add every file matching the current file */ void fileset_add_dir(const char *fname) { WS_DIR *dir; /* scanned directory */ WS_DIRENT *file; /* current file */ const char *name; fileset_entry *entry; GString *dirname; gchar *fname_dup; /* get (convert) directory name, but don't touch the given string */ fname_dup = get_dirname(g_strdup(fname)); dirname = g_string_new(fname_dup); g_free(fname_dup); set.dirname = g_strdup(dirname->str); dirname = g_string_append_c(dirname, G_DIR_SEPARATOR); /* is the current file probably a part of any fileset? */ if(fileset_filename_match_pattern(fname)) { /* yes, go through the files in the directory and check if the file in question is part of the current file set */ if ((dir = ws_dir_open(dirname->str, 0, NULL)) != NULL) { while ((file = ws_dir_read_name(dir)) != NULL) { name = ws_dir_get_name(file); if(fileset_filename_match_pattern(name) && fileset_is_file_in_set(name, get_basename(fname))) { fileset_add_file(dirname->str, name, strcmp(name, get_basename(fname))== 0 /* current */); } } /* while */ ws_dir_close(dir); } /* if */ } else { /* no, this is a "standalone file", just add this one */ entry = fileset_add_file(dirname->str, get_basename(fname), TRUE /* current */); /* don't add the file to the dialog here, this will be done in fileset_update_dlg() below */ } g_string_free(dirname, TRUE /* free_segment */); /* sort entries by creation time */ set.entries = g_list_sort(set.entries, fileset_sort_compare); fileset_update_dlg(); }
static char *findInArcList(char *acquisition_time, char *arclist) { char line[1024]; char *odr = NULL; // ODR files will be in the same directory as arclist char *dir = get_dirname(arclist); FILE *fp = FOPEN(arclist, "r"); if (!fp) { asfPrintError("Failed to open: %s\n", arclist); } ymd_date ymd; hms_time hms; parse_DMYdate(acquisition_time, &ymd, &hms); // YYYYMMDD as an integer int scene_time = ymd.year * 10000 + ymd.month * 100 + ymd.day; while (fgets(line, 1024, fp) != NULL) { if (isdigit(line[0])) { int arc, start, end, junk, n; n = sscanf(line, "%d %d %d:%d - %d %d:%d", &arc, &start, &junk, &junk, &end, &junk, &junk); start = arclist_time_fudge(start); end = arclist_time_fudge(end); if (n == 7) { if (scene_time > start && scene_time < end) { odr = MALLOC(sizeof(char)*(strlen(dir)+64)); sprintf(odr, "%sODR.%03d", dir, arc); break; } } } } FCLOSE(fp); if (!odr) odr = STRDUP(""); FREE(dir); return odr; }
int test_get_dirname() { static const size_t sz = SCRATCH_SZ; int errors = 0; char scratch[SCRATCH_SZ]; #ifdef _UNIX_ scratch[0] = '\0'; if ( get_dirname( "/hi/there", scratch, sz ) || strcmp("/hi", scratch) ) { ++errors; LOG("get_dirname fail with absolute path '/hi/there' ['%s']\n", scratch); } #else //windows scratch[0] = '\0'; if ( get_dirname( "c:/hi/there", scratch, sz ) || strcmp("c:/hi", scratch) ) { ++errors; LOG("get_dirname fail with absolute path 'c:/hi/there ['%s']'\n", scratch); } scratch[0] = '\0'; if ( get_dirname( "c:\\hi\\there", scratch, sz ) || strcmp("c:\\hi", scratch) ) { ++errors; LOG("get_dirname fail with absolute path 'c:\\hi\\there ['%s']'\n", scratch); } #endif scratch[0] = '\0'; if ( get_dirname( "./hi/there", scratch, sz ) || strcmp("./hi", scratch) ) { ++errors; LOG("get_dirname fail with explicit relative path './hi/there' ['%s']\n", scratch); } scratch[0] = '\0'; if ( get_dirname( "../hi/there", scratch, sz ) || strcmp("../hi", scratch) ) { ++errors; LOG("get_dirname fail with explicit relative path '../hi/there' ['%s']\n", scratch); } scratch[0] = '\0'; if ( get_dirname( "hi/there", scratch, sz ) || strcmp("hi", scratch) ) { ++errors; LOG("get_dirname fail with relative path 'hi/there ['%s']'\n", scratch); } return errors; }
static void create_directory (const std::string & path) { if (!exist_file (path)) { int ret; create_directory (get_dirname (path)); #ifdef _WIN32 ret = _mkdir (path.c_str ()); #else ret = mkdir (path.c_str (), S_IREAD | S_IWRITE); #endif if (ret < 0 && errno != EEXIST) { std::string errmsg = xdelta::fmt_string ("Can't create directory %s(%s)." , path.c_str () , xdelta::error_msg ().c_str ()); THROW_XDELTA_EXCEPTION (errmsg); } } return; }
static int init_file_locking(struct lib_context *lc) { int ret = 0; char *dir; if (!(dir = get_dirname(lc, lock_file))) return 0; if (!mk_dir(lc, dir)) goto out; /* Fail on read-only file system. */ if (access(dir, R_OK | W_OK) && errno == EROFS) goto out; lc->lock = &file_locking; ret = 1; out: dbg_free(dir); return ret; }
int open_google_earth() { char *kml_filename = appendExt(curr->filename, ".kml"); char *basename = get_basename(curr->filename); char *dirname = get_dirname(curr->filename); char *arg; if (strlen(dirname)==0) { char *tmpdir = g_get_current_dir(); dirname = escapify(tmpdir); arg = MALLOC(sizeof(char)*(strlen(dirname)+strlen(kml_filename)+20)); sprintf(arg, "%s/%s", dirname, kml_filename); //free(tmpdir); } else { arg = STRDUP(kml_filename); } char *png_file = appendExt(arg, ".png"); printf("png file: %s\n", png_file); printf("Temporary kml file: %s\n", arg); FILE *kml_file = fopen(arg, "w"); if (!kml_file) { asfPrintWarning("Couldn't open kml file!\n"); return FALSE; } dbf_header_t *dbf; int nAttr, nCoords; double *lat, *lon, center_lat, center_lon; char configFile[255], *name; meta_parameters *meta; sprintf(configFile, "%s/convert2vector.config", get_asf_share_dir()); c2v_config *cfg = read_c2v_config(configFile); kml_header(kml_file); meta = meta2vector(curr->filename, &dbf, &nAttr, &lat, &lon, &nCoords); //meta_parameters *meta = curr->meta; if (meta && meta->general && meta_is_valid_double(meta->general->center_latitude) && meta_is_valid_double(meta->general->center_longitude)) { pixbuf2png(pixbuf_small, png_file); //kml_entry_with_overlay(kml_file, meta, basename, png_file, dirname); name = get_basename(kml_filename); center_lat = meta->general->center_latitude; center_lon = meta->general->center_longitude; write_kml_placemark(kml_file, name, center_lat, center_lon, png_file, dbf, nAttr, lat, lon, nCoords, cfg); FREE(lat); FREE(lon); FREE(dbf); } else { asfPrintWarning( "Failed, metadata doesn't contain valid lat/lon info.\n"); return FALSE; } kml_footer(kml_file); fclose(kml_file); gchar *ge; printf("kml: %s\n", kml_filename); printf("dir: %s\n", dirname); #ifdef win32 char path[1024]; FindExecutable((LPCTSTR)kml_filename, (LPCTSTR)dirname, (LPTSTR)path); ge = escapify(path); printf("Path to google earth: %s\n", ge); asfSystem("\"%s\" \"%s\"", ge, arg); #else ge = find_in_path("googleearth"); if (!ge) { message_box("Couldn't find googleearth! Is it installed?"); return FALSE; } int pid = fork(); if (pid == 0) { asfSystem("\"%s\" \"%s\"", ge, arg); //unlink(kml_filename); exit(EXIT_SUCCESS); } #endif free(kml_filename); free(basename); free(dirname); free(arg); return TRUE; }
int xmp_load_module(xmp_context opaque, char *path) { struct context_data *ctx = (struct context_data *)opaque; struct module_data *m = &ctx->m; HIO_HANDLE *h; struct stat st; struct list_head tmpfiles_list; int test_result, load_result; int i, ret; D_(D_WARN "path = %s", path); if (stat(path, &st) < 0) return -XMP_ERROR_SYSTEM; #ifndef _MSC_VER if (S_ISDIR(st.st_mode)) { errno = EISDIR; return -XMP_ERROR_SYSTEM; } #endif if ((h = hio_open_file(path, "rb")) == NULL) return -XMP_ERROR_SYSTEM; INIT_LIST_HEAD(&tmpfiles_list); D_(D_INFO "decrunch"); if (decrunch(&tmpfiles_list, &h->f, &path, DECRUNCH_MAX) < 0) goto err_depack; if (hio_stat(h, &st) < 0) goto err_depack; if (st.st_size < 256) { /* get size after decrunch */ hio_close(h); unlink_tempfiles(&tmpfiles_list); return -XMP_ERROR_FORMAT; } if (ctx->state > XMP_STATE_UNLOADED) xmp_release_module(opaque); m->dirname = get_dirname(path); if (m->dirname == NULL) return -XMP_ERROR_SYSTEM; m->basename = get_basename(path); if (m->basename == NULL) return -XMP_ERROR_SYSTEM; m->filename = path; /* For ALM, SSMT, etc */ m->size = st.st_size; load_prologue(ctx); D_(D_WARN "load"); test_result = load_result = -1; for (i = 0; format_loader[i] != NULL; i++) { hio_seek(h, 0, SEEK_SET); test_result = format_loader[i]->test(h, NULL, 0); if (test_result == 0) { hio_seek(h, 0, SEEK_SET); D_(D_WARN "load format: %s", format_loader[i]->name); load_result = format_loader[i]->loader(m, h, 0); break; } } set_md5sum(h, m->md5); hio_close(h); unlink_tempfiles(&tmpfiles_list); if (test_result < 0) { free(m->basename); free(m->dirname); return -XMP_ERROR_FORMAT; } if (load_result < 0) { xmp_release_module(opaque); return -XMP_ERROR_LOAD; } str_adj(m->mod.name); if (!*m->mod.name) { strncpy(m->mod.name, m->basename, XMP_NAME_SIZE); } load_epilogue(ctx); ret = prepare_scan(ctx); if (ret < 0) return ret; scan_sequences(ctx); ctx->state = XMP_STATE_LOADED; return 0; err_depack: hio_close(h); unlink_tempfiles(&tmpfiles_list); return -XMP_ERROR_DEPACK; }
int xmp_load_module(xmp_context opaque, char *path) { struct context_data *ctx = (struct context_data *)opaque; #ifndef LIBXMP_CORE_PLAYER struct module_data *m = &ctx->m; long size; char *temp_name; #endif HIO_HANDLE *h; struct stat st; int ret; D_(D_WARN "path = %s", path); /* if (stat(path, &st) < 0) return -XMP_ERROR_SYSTEM; */ #ifndef _MSC_VER if (S_ISDIR(st.st_mode)) { errno = EISDIR; return -XMP_ERROR_SYSTEM; } #endif if ((h = hio_open(path, "rb")) == NULL) return -XMP_ERROR_SYSTEM; #ifndef LIBXMP_CORE_PLAYER D_(D_INFO "decrunch"); if (decrunch(&h, path, &temp_name) < 0) goto err_depack; size = hio_size(h); if (size < 256) { /* get size after decrunch */ hio_close(h); unlink_temp_file(temp_name); return -XMP_ERROR_FORMAT; } #endif if (ctx->state > XMP_STATE_UNLOADED) xmp_release_module(opaque); #ifndef LIBXMP_CORE_PLAYER m->dirname = get_dirname(path); if (m->dirname == NULL) return -XMP_ERROR_SYSTEM; m->basename = get_basename(path); if (m->basename == NULL) return -XMP_ERROR_SYSTEM; m->filename = path; /* For ALM, SSMT, etc */ m->size = size; #endif ret = load_module(opaque, h); hio_close(h); #ifndef LIBXMP_CORE_PLAYER unlink_temp_file(temp_name); #endif return ret; #ifndef LIBXMP_CORE_PLAYER err_depack: hio_close(h); unlink_temp_file(temp_name); return -XMP_ERROR_DEPACK; #endif }
/* parse DNN config file */ boolean dnn_config_file_parse(char *filename, JCONF_AM *am, Jconf *jconf) { FILE *fp; char buf[BUFLEN]; char *p, *pp; char *v; int i, n; boolean error_flag; char *cdir; if (am->dnn.wfile != NULL) { jlog("ERROR: dnn_config_file_parse: duplicated loading: %s\n", filename); return FALSE; } if ((fp = fopen(filename, "r")) == NULL) { jlog("ERROR: dnn_config_file_parse: failed to open %s\n", filename); return FALSE; } cdir = strcpy((char *)mymalloc(strlen(filename)+1), filename); get_dirname(cdir); if (cdir[0] == '\0') { free(cdir); cdir = NULL; } while (fgets_jconf(buf, BUFLEN, fp) != NULL) { if ((p = strchr(buf, '#')) != NULL) { *p = '\0'; } pp = &(buf[0]); while (*pp == ' ' || *pp == '\t') pp++; if (*pp == '\0') continue; p = strchr(pp, ' '); if (p == NULL) { jlog("ERROR: dnn_config_file_parse: wrong file format: %s\n", buf); if (cdir) free(cdir); fclose(fp); return FALSE; } v = p; while (*v == ' ') v++; *p = '\0'; if (strmatch(pp, "feature_type")) { am->dnn.paramtype = param_str2code(v); } else if (strmatch(pp, "feature_options")) { am->dnn.optionstring = strdup(v); } else if (strmatch(pp, "feature_len")) am->dnn.veclen = atoi(v); else if (strmatch(pp, "context_len")) am->dnn.contextlen = atoi(v); else if (strmatch(pp, "input_nodes")) am->dnn.inputnodes = atoi(v); else if (strmatch(pp, "output_nodes")) am->dnn.outputnodes = atoi(v); else if (strmatch(pp, "hidden_nodes")) am->dnn.hiddennodes = atoi(v); else if (strmatch(pp, "hidden_layers")) { am->dnn.hiddenlayernum = atoi(v); am->dnn.wfile = (char **)mymalloc(sizeof(char *) * am->dnn.hiddenlayernum); am->dnn.bfile = (char **)mymalloc(sizeof(char *) * am->dnn.hiddenlayernum); for (i = 0; i < am->dnn.hiddenlayernum; i++) { am->dnn.wfile[i] = NULL; am->dnn.bfile[i] = NULL; } } else if (pp[0] == 'W') { n = atoi(&(pp[1])); if (n > am->dnn.hiddenlayernum) { jlog("ERROR: dnn_config_file_parse: W%d > # of hidden_layers (%d)\n", n, am->dnn.hiddenlayernum); if (cdir) free(cdir); fclose(fp); return FALSE; } else if (n <= 0) { jlog("ERROR: dnn_config_file_parse: layer id should begin with 1\n"); if (cdir) free(cdir); fclose(fp); return FALSE; } am->dnn.wfile[n-1] = filepath(v, cdir); } else if (pp[0] == 'B') { n = atoi(&(pp[1])); if (n > am->dnn.hiddenlayernum) { jlog("ERROR: dnn_config_file_parse: B%d > # of hidden_layers (%d)\n", n, am->dnn.hiddenlayernum); if (cdir) free(cdir); fclose(fp); return FALSE; } else if (n <= 0) { jlog("ERROR: dnn_config_file_parse: layer id should begin with 1\n"); if (cdir) free(cdir); fclose(fp); return FALSE; } am->dnn.bfile[n-1] = filepath(v, cdir); } else if (strmatch(pp, "output_W")) am->dnn.output_wfile = filepath(v, cdir); else if (strmatch(pp, "output_B")) am->dnn.output_bfile = filepath(v, cdir); else if (strmatch(pp, "state_prior")) am->dnn.priorfile = filepath(v, cdir); else if (strmatch(pp, "state_prior_factor")) am->dnn.prior_factor = atof(v); else if (strmatch(pp, "batch_size")) am->dnn.batchsize = atoi(v); else if (strmatch(pp, "num_threads")) am->dnn.num_threads = atoi(v); else { jlog("ERROR: dnn_config_file_parse: unknown spec: %s %s\n", pp, v); if (cdir) free(cdir); fclose(fp); return FALSE; } } if (fclose(fp) == -1) { jlog("ERROR: dnn_config_file_parse: failed to close file\n"); if (cdir) free(cdir); return FALSE; } /* check validity */ error_flag = FALSE; for (i = 0; i < am->dnn.hiddenlayernum; i++) { if (am->dnn.wfile[i] == NULL) { jlog("ERROR: dnn_config_file_parse: no W file specified for hidden layer #%d\n", i + 1); error_flag = TRUE; } if (am->dnn.bfile[i] == NULL) { jlog("ERROR: dnn_config_file_parse: no B file specified for hidden layer #%d\n", i + 1); error_flag = TRUE; } } if (error_flag == TRUE) { if (cdir) free(cdir); return FALSE; } am->dnn.enabled = TRUE; /* load options */ if (am->dnn.optionstring) { if (config_string_parse_basedir(jconf->amnow->dnn.optionstring, jconf, cdir) == FALSE) { if (cdir) free(cdir); return FALSE; } } if (cdir) free(cdir); return TRUE; }
int isRadarsat2_ext(char *dataFile, int check_data, char **error) { char dataType[25]; char *message = NULL; int found = FALSE; char *inFile = MALLOC(sizeof(char)*(strlen(dataFile)+16)); strcpy(inFile, dataFile); // Let's first check for an .xml extension char *ext = findExt(inFile); // Append extension in case we don't find it if (!fileExists(inFile) && ext == NULL) { strcat(inFile, ".xml"); ext = findExt(inFile); } // If it has the correct extension, investigate it further // Might sound a little harsh but avoids some XML parser warning otherwise. if (fileExists(inFile) && ext && strcmp_case(ext, ".xml") == 0) { int ii, band_count = 0; char tmp[256], *path = NULL, *inDataName = NULL; char polarizations[25], satellite[25]; FILE *fp; fp = fopen(inFile, "r"); xmlDoc *doc = xmlReadFile(inFile, NULL, 0); if (doc) { strncpy_safe(satellite, xml_get_string_value(doc, "product.sourceAttributes.satellite"), 20); // only care about Radarsat-2 data if (strcmp_case(satellite, "RADARSAT-2") == 0) { found = TRUE; strncpy_safe(dataType, xml_get_string_value(doc, "product.imageAttributes.rasterAttributes.dataType"), 20); if (strcmp_case(dataType, "COMPLEX") != 0) { if (!message) message = (char *) MALLOC(sizeof(char)*1024); sprintf(tmp, "Wrong data type!\n" "Polarimetric processing requires SLC data!\n"); strcat(message, tmp); if (check_data) found = FALSE; } // path from the xml (metadata) file path = get_dirname(inFile); inDataName = (char *) MALLOC(sizeof(char)*(strlen(path)+512)); strncpy_safe(polarizations, xml_get_string_value(doc, "product.sourceAttributes.radarParameters.polarizations"),20); for (ii=0; ii<strlen(polarizations)-1; ii++) if (polarizations[ii] == ' ') polarizations[ii] = ','; if (strstr(polarizations, "HH")) band_count++; if (strstr(polarizations, "VV")) band_count++; if (strstr(polarizations, "HV")) band_count++; if (strstr(polarizations, "VH")) band_count++; for (ii=0; ii<band_count; ii++) { if (strlen(path)>0) { strcpy(inDataName, path); if (inDataName[strlen(inDataName)-1] != '/') strcat(inDataName, "/"); } else strcpy(inDataName, ""); strcat(inDataName, xml_get_string_value(doc, "product.imageAttributes.fullResolutionImageData[%d]", ii)); if (!fileExists(inDataName)) { if (!message) message = (char *) MALLOC(sizeof(char)*1024); sprintf(tmp, "Data file (%s) does not exist!\n", inDataName); strcat(message, tmp); if (check_data) found = FALSE; } } } } if (fp) { fclose(fp); xmlFreeDoc(doc); xmlCleanupParser(); } } FREE(inFile); if (!found && message) *error = message; return found; }
SIGNAL_CALLBACK void on_add_file_with_ancillary_ok_button_clicked(GtkWidget * w) { const char *type = get_string_from_label("add_with_ancillary_format_label"); int sel = -1; if (strcmp_case(type, "GAMMA") == 0) sel = ADD_FILE_WITH_ANCILLARY_FORMAT_GAMMA; else if (strcmp_case(type, "PolSARPro") == 0) sel = ADD_FILE_WITH_ANCILLARY_FORMAT_POLSARPRO; else if (strcmp_case(type, "UAVSAR") == 0) sel = ADD_FILE_WITH_ANCILLARY_FORMAT_UAVSAR; GtkTreeIter iter; int ok = TRUE; char *dataFile = NULL, *data = NULL, *ceos = NULL; char *aux_info = ""; switch (sel) { case ADD_FILE_WITH_ANCILLARY_FORMAT_POLSARPRO: { GtkWidget *ok_button = get_widget_checked("add_file_with_ancillary_ok_button"); gtk_widget_set_sensitive(ok_button, FALSE); dataFile = get_string_from_entry("add_file_with_ancillary_polsarpro_image_entry"); char *matrixType=NULL, *error, *decompositionType, *derror; char *serror, *perror; int is_polsarpro_matrix = isPolsarproMatrix(dataFile, &matrixType, &error); int is_polsarpro_decomposition = isPolsarproDecomposition(dataFile, &decompositionType, &derror); int is_polsarpro_segmentation = isPolsarproSegmentation(dataFile, &serror); int is_polsarpro_parameter = isPolsarproParameter(dataFile, &perror); if (is_polsarpro_matrix && !is_polsarpro_decomposition && !is_polsarpro_segmentation && !is_polsarpro_parameter) { data = (char *) MALLOC(sizeof(char) * (strlen(dataFile) + 15)); if (!is_dir(dataFile)) { char *tmp = (char *) MALLOC(sizeof(char) * (strlen(dataFile) + 1)); tmp = get_dirname(dataFile); dataFile[strlen(tmp) - 1] = '\0'; FREE(tmp); } if (strcmp(matrixType, "T3") == 0 || strcmp(matrixType, "T4") == 0) sprintf(data, "%s/T11.bin", dataFile); else if (strcmp(matrixType, "C2") == 0 || strcmp(matrixType, "C3") == 0 || strcmp(matrixType, "C4") == 0) sprintf(data, "%s/C11.bin", dataFile); } else data = STRDUP(dataFile); FREE(matrixType); int is_geocoded = isGeocoded(data); if (!is_geocoded) ceos = get_string_from_entry ("add_file_with_ancillary_polsarpro_ceos_entry"); if (!is_geocoded && (strlen(ceos) == 0 || strlen(data) == 0)) { put_string_to_label("add_with_ancillary_error_label", "Please choose all required files!"); return; } else { GtkWidget *browse_option_menu = get_widget_checked("browse_select_colormap_optionmenu"); GtkWidget *menu = gtk_option_menu_get_menu(GTK_OPTION_MENU(browse_option_menu)); GtkWidget *selected_item = gtk_menu_get_active(GTK_MENU(menu)); GtkWidget *combo = get_widget_checked("browse_select_image_data_type_optionmenu"); int image_data_type = gtk_combo_box_get_active(GTK_COMBO_BOX(combo)); char *lut_basename = g_object_get_data(G_OBJECT(selected_item), "file"); aux_info = encode_polsarpro_aux_info(image_data_type, lut_basename); put_string_to_label("add_with_ancillary_error_label", ""); ok = add_to_files_list_iter(data, ceos, NULL, aux_info, NULL, NULL, NULL, NULL, NULL, &iter); free(aux_info); } break; } case ADD_FILE_WITH_ANCILLARY_FORMAT_GAMMA: { GtkWidget *ok_button = get_widget_checked("add_file_with_ancillary_ok_button"); gtk_widget_set_sensitive(ok_button, TRUE); data = get_string_from_entry("add_file_with_ancillary_gamma_data_entry"); char *meta = get_string_from_entry("add_file_with_ancillary_gamma_metadata_entry"); if (strlen(data) == 0 || strlen(meta) == 0) { put_string_to_label("add_with_ancillary_error_label", "Please choose all required files!"); return; } else { put_string_to_label("add_with_ancillary_error_label", ""); char *interferogram, *coherence, *slave_metadata, *baseline; interferogram = get_string_from_entry("add_file_with_ancillary_gamma_igram_entry"); coherence = get_string_from_entry("add_file_with_ancillary_gamma_coh_entry"); slave_metadata = get_string_from_entry("add_file_with_ancillary_gamma_slave_entry"); baseline = get_string_from_entry("add_file_with_ancillary_gamma_baseline_entry"); if (strlen(interferogram) == 0) { FREE(interferogram); interferogram = NULL; } if (strlen(coherence) == 0) { FREE(coherence); coherence = NULL; } if (strlen(slave_metadata) == 0) { FREE(slave_metadata); slave_metadata = NULL; } if (strlen(baseline) == 0) { FREE(baseline); baseline = NULL; } ok = add_to_files_list_iter(data, ceos, meta, aux_info, NULL, interferogram, coherence, slave_metadata, baseline, &iter); } break; } case ADD_FILE_WITH_ANCILLARY_FORMAT_UAVSAR: { GtkWidget *ok_button = get_widget_checked("add_file_with_ancillary_ok_button"); gtk_widget_set_sensitive(ok_button, TRUE); GtkWidget *ann_file_entry = get_widget_checked("add_file_with_ancillary_uavsar_annotation_file_entry"); const gchar *annotation_file = gtk_entry_get_text(GTK_ENTRY(ann_file_entry)); GList *l, *uavsar_proc_types = get_widgets_prefix_checked("uavsar_proc_type_"); for(l = uavsar_proc_types; l; l = l->next) { gpointer proc_type_check_button = l->data; if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(proc_type_check_button))) { const gchar *name = gtk_widget_get_name(GTK_WIDGET(proc_type_check_button)); ok = add_to_files_list_iter(annotation_file, NULL, NULL, NULL, name + strlen("uavsar_proc_types_") - 1, NULL, NULL, NULL, NULL, &iter); if(!ok) break; } } g_list_free(uavsar_proc_types); } break; } if (!ok) { if (data) { char *msg = MALLOC(sizeof(char) * (strlen(data) + 128)); sprintf(msg, "Unrecognized file:\n %s\n\n" "The file may be of a type not supported by MapReady.\n", data); message_box(msg); free(msg); } else { char *msg = MALLOC(sizeof(char) * 256); sprintf(msg, "Unrecognized file!\n\n" "The file may be of a type not supported by MapReady.\n"); message_box(msg); free(msg); } } else { show_widget("add_file_with_ancillary_dialog", FALSE); clear_entries(); } }
int isTerrasar_ext(char *dataFile, int checkPolarimetry, char **error) { int found = FALSE; char *inFile = STRDUP(dataFile); // Let's first check for an .xml extension char *ext = findExt(inFile); // If it has the correct extension, investigate it further // Might sound a little harsh but avoids some XML parser warning otherwise. if (ext && strcmp_case(ext, ".xml") == 0) { char *satellite = NULL; char tmp[256], *message = NULL, *path=NULL, *inDataName=NULL; char imageDataType[25]; int ii, numberOfLayers; satellite = (char *) MALLOC(sizeof(char)*25); FILE *fp; fp = fopen(inFile, "r"); xmlDoc *doc = xmlReadFile(inFile, NULL, 0); if (doc) { strcpy(satellite, xml_get_string_value(doc, "level1Product.productInfo.missionInfo.mission")); // only care about TerraSAR-X data if (satellite && (strncmp_case(satellite, "TSX", 3) == 0 || strncmp_case(satellite, "TDX", 3) == 0)) { found = TRUE; if (checkPolarimetry) { strcpy(imageDataType, xml_get_string_value(doc, "level1Product.productInfo.imageDataInfo.imageDataType")); if (strcmp_case(imageDataType, "COMPLEX") != 0) { if (!message) message = (char *) MALLOC(sizeof(char)*1024); sprintf(tmp, "Wrong data type!\n" "Polarimetric processing requires SLC data!\n"); strcat(message, tmp); found = FALSE; } } // path from the xml (metadata) file path = get_dirname(inFile); inDataName = (char *) MALLOC(sizeof(char)*(strlen(path)+100)); numberOfLayers = xml_get_int_value(doc, "level1Product.productInfo.imageDataInfo.numberOfLayers"); for (ii=0; ii<numberOfLayers; ii++) { if (strlen(path)>0) { strcpy(inDataName, path); if (inDataName[strlen(inDataName)-1] != '/') strcat(inDataName, "/"); } else strcpy(inDataName, ""); // check whether data file exists strcat(inDataName, xml_get_string_value(doc, "level1Product.productComponents.imageData[%d].file.location.path", ii)); strcat(inDataName, "/"); strcat(inDataName, xml_get_string_value(doc, "level1Product.productComponents.imageData[%d].file.location." "filename", ii)); if (!fileExists(inDataName)) { if (!message) message = (char *) MALLOC(sizeof(char)*1024); sprintf(tmp, "Data file (%s) does not exist!\n", inDataName); strcat(message, tmp); found = FALSE; } } } } fclose(fp); xmlFreeDoc(doc); xmlCleanupParser(); if (path) FREE(path); if (inDataName) FREE(inDataName); FREE(inFile); } return found; }
int isPolsarproMatrix(char *dataFile, char **matrixType, char **error) { int matrix = FALSE; char *path; if (!dataFile || strlen(dataFile)<=0) return FALSE; if (is_dir(dataFile)) path = STRDUP(dataFile); else path = get_dirname(dataFile); if (strlen(path)<=0) path = g_get_current_dir(); if (path[strlen(path)-1] == DIR_SEPARATOR) path[strlen(path)-1] = '\0'; char *p = path, *q = path; while (q) { if ((q = strchr(p, DIR_SEPARATOR)) != NULL) p = q+1; } int ii; char *directory = STRDUP(p); char *binError = (char *) MALLOC(sizeof(char)*255); char *hdrError = (char *) MALLOC(sizeof(char)*255); char *tifError = (char *) MALLOC(sizeof(char)*255); char headerFile[1024], metaFile[1024]; // check files for coherency matrix T3 if (strcmp_case(directory, "T3") == 0) { for (ii=0; ii<9; ii++) { checkMatrixFile("Data", path, dataFile, t3_tif_matrix[ii], directory, &tifError); checkMatrixFile("Data", path, dataFile, t3_matrix[ii], directory, &binError); sprintf(headerFile, "%s.hdr", t3_matrix[ii]); sprintf(metaFile, "%s.hdr", dataFile); checkMatrixFile("Header", path, metaFile, headerFile, directory, &hdrError); if (binError && tifError) { *error = binError; return FALSE; } else if (hdrError && tifError) { *error = hdrError; return FALSE; } } matrix = TRUE; } // check files for coherency matrix T4 else if (strcmp_case(directory, "T4") == 0) { for (ii=0; ii<16; ii++) { if (!checkMatrixFile("Data", path, dataFile, t4_matrix[ii], directory, error)) return FALSE; sprintf(headerFile, "%s.hdr", t4_matrix[ii]); sprintf(metaFile, "%s.hdr", dataFile); if (!checkMatrixFile("Header", path, metaFile, headerFile, directory, error)) return FALSE; } matrix = TRUE; } // check files for covariance matrix C2 else if (strcmp_case(directory, "C2") == 0) { for (ii=0; ii<4; ii++) { if (!checkMatrixFile("Data", path, dataFile, c2_matrix[ii], directory, error)) return FALSE; sprintf(headerFile, "%s.hdr", c2_matrix[ii]); sprintf(metaFile, "%s.hdr", dataFile); if (!checkMatrixFile("Header", path, metaFile, headerFile, directory, error)) return FALSE; } matrix = TRUE; } // check files for covariance matrix C3 else if (strcmp_case(directory, "C3") == 0) { for (ii=0; ii<9; ii++) { checkMatrixFile("Data", path, dataFile, c3_tif_matrix[ii], directory, &tifError); checkMatrixFile("Data", path, dataFile, c3_matrix[ii], directory, &binError); sprintf(headerFile, "%s.hdr", c3_matrix[ii]); sprintf(metaFile, "%s.hdr", dataFile); checkMatrixFile("Header", path, metaFile, headerFile, directory, &hdrError); if (binError && tifError) { *error = binError; return FALSE; } else if (hdrError && tifError) { *error = hdrError; return FALSE; } } matrix = TRUE; } // check files for covariance matrix C4 else if (strcmp_case(directory, "C4") == 0) { for (ii=0; ii<16; ii++) { if (!checkMatrixFile("Data", path, dataFile, c4_matrix[ii], directory, error)) return FALSE; sprintf(headerFile, "%s.hdr", c4_matrix[ii]); sprintf(metaFile, "%s.hdr", dataFile); if (!checkMatrixFile("Header", path, dataFile, headerFile, directory, error)) return FALSE; } matrix = TRUE; } else { *error = STRDUP("Matrix does not exist."); } *matrixType = directory; if (binError) *error = STRDUP(binError); else if (hdrError) *error = STRDUP(hdrError); else if (tifError) *error = STRDUP(tifError); FREE(binError); FREE(hdrError); FREE(tifError); return matrix; }
int ExportDissectionDialog::exec() { #if !defined(Q_OS_WIN) int retval; if (!cap_file_) return QDialog::Rejected; retval = QFileDialog::exec(); if (retval == QDialog::Accepted && selectedFiles().length() > 0) { cf_print_status_t status; QString file_name = selectedFiles()[0]; /* Fill in our print (and export) args */ print_args_.file = file_name.toUtf8().data(); print_args_.format = PR_FMT_TEXT; print_args_.to_file = TRUE; print_args_.cmd = NULL; print_args_.print_summary = TRUE; print_args_.print_dissections = print_dissections_as_displayed; print_args_.print_hex = FALSE; print_args_.print_formfeed = FALSE; switch (export_type_) { case export_type_text: /* Text */ print_args_.print_summary = packet_format_group_box_.summaryEnabled(); print_args_.print_dissections = print_dissections_none; if (packet_format_group_box_.detailsEnabled()) { if (packet_format_group_box_.allCollapsedEnabled()) print_args_.print_dissections = print_dissections_collapsed; else if (packet_format_group_box_.asDisplayedEnabled()) print_args_.print_dissections = print_dissections_as_displayed; else if (packet_format_group_box_.allExpandedEnabled()) print_args_.print_dissections = print_dissections_expanded; } print_args_.print_hex = packet_format_group_box_.bytesEnabled(); print_args_.stream = print_stream_text_new(TRUE, print_args_.file); if (print_args_.stream == NULL) { open_failure_alert_box(print_args_.file, errno, TRUE); return QDialog::Rejected; } status = cf_print_packets(cap_file_, &print_args_); break; case export_type_csv: /* CSV */ status = cf_write_csv_packets(cap_file_, &print_args_); break; case export_type_carrays: /* C Arrays */ status = cf_write_carrays_packets(cap_file_, &print_args_); break; case export_type_psml: /* PSML */ status = cf_write_psml_packets(cap_file_, &print_args_); break; case export_type_pdml: /* PDML */ status = cf_write_pdml_packets(cap_file_, &print_args_); break; default: return QDialog::Rejected; } switch (status) { case CF_PRINT_OK: break; case CF_PRINT_OPEN_ERROR: open_failure_alert_box(print_args_.file, errno, TRUE); break; case CF_PRINT_WRITE_ERROR: write_failure_alert_box(print_args_.file, errno); break; } if (selectedFiles().length() > 0) { gchar *dirname; /* Save the directory name for future file dialogs. */ dirname = get_dirname(print_args_.file); /* Overwrites file_name data */ set_last_open_dir(dirname); } } return retval; #else // Q_OS_WIN win32_export_file(parentWidget()->effectiveWinId(), cap_file_, export_type_); return QDialog::Accepted; #endif // Q_OS_WIN }
int open_google_earth() { char *kml_filename = appendExt(curr->filename, ".kml"); char *basename = get_basename(curr->filename); char *dirname = get_dirname(curr->filename); char *arg; if (strlen(dirname)==0) { char *tmpdir = g_get_current_dir(); dirname = escapify(tmpdir); arg = MALLOC(sizeof(char)*(strlen(dirname)+strlen(kml_filename)+20)); sprintf(arg, "%s/%s", dirname, kml_filename); //free(tmpdir); } else { arg = STRDUP(kml_filename); } char *png_file = appendExt(arg, ".png"); printf("png file: %s\n", png_file); printf("Temporary kml file: %s\n", arg); FILE *kml_file = fopen(arg, "w"); if (!kml_file) { asfPrintWarning("Couldn't open kml file!\n"); return FALSE; } kml_header(kml_file); meta_parameters *meta = curr->meta; if (meta && meta->general && meta_is_valid_double(meta->general->center_latitude) && meta_is_valid_double(meta->general->center_longitude)) { pixbuf2png(pixbuf_small, png_file); kml_entry_with_overlay(kml_file, meta, basename, png_file, dirname); } else { asfPrintWarning( "Failed, metadata doesn't contain valid lat/lon info.\n"); return FALSE; } kml_footer(kml_file); fclose(kml_file); gchar *ge; printf("kml: %s\n", kml_filename); printf("dir: %s\n", dirname); #ifdef win32 char path[1024]; FindExecutable((LPCTSTR)kml_filename, (LPCTSTR)dirname, (LPTSTR)path); ge = escapify(path); printf("Path to google earth: %s\n", ge); asfSystem("\"%s\" \"%s\"", ge, arg); #else ge = find_in_path("googleearth"); if (!ge) { message_box("Couldn't find googleearth! Is it installed?"); return FALSE; } int pid = fork(); if (pid == 0) { asfSystem("\"%s\" \"%s\"", ge, arg); //unlink(kml_filename); exit(EXIT_SUCCESS); } #endif free(kml_filename); free(basename); free(dirname); free(arg); return TRUE; }
/* // InitSourceFile // // Initializes all the fields in SOURCEFILE, and attempts to to open the // file. // // Returns 1 on success, 0 on error */ SOURCEFILE *InitSourceFile( SOURCEFILE *pParent, char *filename, int use_include_path ) { SOURCEFILE *ps; int i; char SourceName[SOURCE_NAME]; char SourceBaseDir[SOURCE_BASE_DIR]; /* Put a reasonable cap on #include depth */ if( OpenFiles==15 ) { Report(pParent,REP_FATAL,"Too many open files"); return(0); } if ( use_include_path ) if ( !is_definite(filename) ) { switch ( get_absolute( filename, SOURCE_BASE_DIR ) ) { case -1: Report(pParent,REP_FATAL, "Could not find '%s' in include paths",filename); goto FILEOP_ERROR; case 1: Report(pParent,REP_FATAL, "Absolute pathname too long in [include-dirs]/'%s'", filename); goto FILEOP_ERROR; } } /* I don't imagine these test should ever fail at this point, but... */ if ( get_dirname(filename, SourceBaseDir, SOURCE_BASE_DIR) ) { Report(pParent,REP_FATAL,"Dirname too long in '%s'",filename); goto FILEOP_ERROR; } if ( get_basename(filename, SourceName, SOURCE_NAME) ) { Report(pParent,REP_FATAL,"base filename too long in '%s'",filename); goto FILEOP_ERROR; } if( Options & OPTION_DEBUG ) printf("Base source directory: '%s'\n",SourceBaseDir); /* // See if this file was used before, or allocate a new record */ for( i=0; i<(int)sfIndex; i++ ) { if( !sfArray[i].InUse && !strcmp(SourceName, sfArray[i].SourceName) && !strcmp(SourceBaseDir, sfArray[i].SourceBaseDir) ) break; } if( i<(int)sfIndex ) ps = &sfArray[i]; else { /* Allocate a new file */ if( sfIndex==SOURCEFILE_MAX ) { Report(pParent,REP_FATAL,"Max source files exceeded"); return(0); } ps = &sfArray[sfIndex]; i = sfIndex++; } /* // Fill in file record */ memset( ps, 0, sizeof(SOURCEFILE) ); if( Options & OPTION_DEBUG ) printf("New source file: '%s'\n",filename); /* Init the base fields */ ps->pParent = 0; ps->LastChar = 0; ps->CurrentLine = 1; ps->CurrentColumn = 1; ps->ccDepthIn = ccDepth; ps->InUse = 1; ps->FileIndex = i; strcpy( ps->SourceName, SourceName ); strcpy( ps->SourceBaseDir, SourceBaseDir ); /* Open the file */ ps->FilePtr = fopen(filename,"rb"); if (!ps->FilePtr) { Report(pParent,REP_FATAL,"Can't open source file '%s'",filename); goto FILEOP_ERROR; } OpenFiles++; if( OpenFiles > 10 ) Report(pParent,REP_WARN1,"%d open files - possible #include recursion",OpenFiles); return(ps); FILEOP_ERROR: return(0); }
int main(int argc, char **argv) { char inFormat[25], outFormat[25], configFile[255]; int currArg = 1, NUM_ARGS = 1, configFlag = FALSE; c2v_config *cfg=NULL; if (argc < 3) { usage(argv[0]); exit(1); } // Check for configuration file option first while (currArg < (argc-NUM_ARGS)) { char *key = argv[currArg++]; if (strmatches(key, "-help", "--help", NULL)) { usage(argv[0]); char format[25], data_dictionary[512]; CHECK_ARG(1); strcpy(format, GET_ARG(1)); sprintf(data_dictionary, "%s%c%s_data_dictionary.csv", get_asf_share_dir(), DIR_SEPARATOR, format); if (fileExists(data_dictionary)) { asfPrintStatus("\nFormat defined in %s_data_dictionary.csv\n\n", format); catFile(data_dictionary); asfPrintStatus("\n\n"); } else asfPrintWarning("Could not find a data dictionary for format (%s)!\n\n", format); exit(1); } else if (strmatches(key, "-config", "--config", "-c", NULL)) { CHECK_ARG(1); strcpy(configFile, GET_ARG(1)); cfg = read_c2v_config(configFile); configFlag = TRUE; } } if (!configFlag) { sprintf(configFile, "%s%cconvert2vector.config", get_asf_share_dir(), DIR_SEPARATOR); asfPrintStatus("\nReading parameters from default configuration file:\n" "%s\n", configFile); cfg = read_c2v_config(configFile); } // Pick up the rest of the arguments currArg = 1; NUM_ARGS = 2; while (currArg < (argc-NUM_ARGS)) { char *key = argv[currArg++]; if (strmatches(key, "-config", "--config", "-c", NULL)) { ; } else if (strmatches(key, "-log", "--log", NULL)) { CHECK_ARG(1); strcpy(logFile,GET_ARG(1)); fLog = FOPEN(logFile, "a"); logflag = TRUE; } else if (strmatches(key, "-quiet", "--quiet", "-q", NULL)) quietflag = TRUE; else if (strmatches(key, "-list", "--list", NULL)) cfg->list = TRUE; else if (strmatches(key, "-nosplit", "--nosplit", "-ns", NULL)) cfg->nosplit = TRUE; else if (strmatches(key, "-input-format", "--input-format", "-i", NULL)) { CHECK_ARG(1); strcpy(cfg->input_format, GET_ARG(1)); } else if (strmatches(key, "-output-format", "--output-format", "-o", NULL)) { CHECK_ARG(1); strcpy(cfg->output_format, GET_ARG(1)); } else { --currArg; break; } } if ((argc-currArg) < NUM_ARGS) { printf("Insufficient arguments.\n"); usage(argv[0]); } if (!configFlag) { sprintf(cfg->input_file, "%s", argv[currArg++]); sprintf(cfg->output_file, "%s", argv[currArg]); } asfSplashScreen (argc, argv); sprintf(inFormat, "%s", uc(cfg->input_format)); sprintf(outFormat, "%s", uc(cfg->output_format)); // Check whether you can find information about the format in the header // list file in the share directory dbf_header_t *dbf; int nCols; char shape_type[25]; if (strcmp_case(inFormat, "CSV") == 0 || read_header_config(inFormat, &dbf, &nCols, shape_type)) asfPrintStatus(" Converting a %s format file to %s\n", inFormat, outFormat); else asfPrintError(" Unsupported input format (%s)\n", inFormat); // Set output directory as the temporary directory -- where all temp files // created during import should be put char *tmpdir = get_dirname(cfg->output_file); if (tmpdir && strlen(tmpdir) > 0) set_asf_tmp_dir(tmpdir); convert2vector(cfg); asfPrintStatus("Done.\n\n"); return(0); }
object *load_object(IDirect3DDevice9 *device, char *filename){ matrix position, rotation, scale; vector position_vector, scale_vector; quat rotation_quat; unsigned int submesh_counter; char test[4]; object *temp; file *fp; vertex *dest; if(!filename) return NULL; fp = file_open(filename); if(!fp) return NULL; file_read(test,1,4,fp); if(memcmp(test,"KRO0",4)!=0){ file_close(fp); return NULL; } temp = (object*)malloc(sizeof(object)); if(!temp) return NULL; file_read(&position_vector,sizeof(float),3,fp); file_read(&rotation_quat,sizeof(float),4,fp); file_read(&scale_vector,sizeof(float),3,fp); file_read(&temp->vertex_count,1,4,fp); if(temp->vertex_count==0){ /* dummy-object, skip loading */ file_close(fp); temp->update = FALSE; temp->vertexbuffer = NULL; temp->vertices = 0; temp->submesh_count = 0; temp->submeshes = NULL; /* save prs */ temp->prs.pos = position_vector; temp->prs.rot = rotation_quat; temp->prs.scale = scale_vector; /* build matrix */ matrix_identity(temp->mat); matrix_translate(position, position_vector); matrix_from_quat(rotation, rotation_quat); matrix_scale(scale, scale_vector); matrix_multiply(temp->mat, temp->mat, position); matrix_multiply(temp->mat, temp->mat, rotation); matrix_multiply(temp->mat, temp->mat, scale); return temp; } temp->vertices = (vertex*)malloc(sizeof(vertex)*temp->vertex_count); if(!temp->vertices) return FALSE; file_read(temp->vertices,sizeof(vertex),temp->vertex_count,fp); file_read(&temp->morphtarget_count,1,4,fp); temp->morphtarget_vertices = malloc(sizeof(vector)*temp->vertex_count*temp->morphtarget_count); if(!temp->morphtarget_vertices) return FALSE; file_read(temp->morphtarget_vertices,sizeof(vector),temp->vertex_count*temp->morphtarget_count,fp); file_read(&temp->submesh_count,1,4,fp); temp->submeshes = (submesh*)malloc(sizeof(submesh)*temp->submesh_count); if(!temp->submeshes) return FALSE; for(submesh_counter=0;submesh_counter<temp->submesh_count;submesh_counter++){ unsigned int* dest; char mat_name[256]; char *material_name = file_loadstring(fp); sprintf(mat_name,"%s%s",get_dirname(filename),material_name); temp->submeshes[submesh_counter].mat = material_load(device,mat_name); file_read(&temp->submeshes[submesh_counter].triangle_count,1,4,fp); temp->submeshes[submesh_counter].triangles = (unsigned short*)malloc(sizeof(unsigned short)*3*temp->submeshes[submesh_counter].triangle_count); if(!temp->submeshes[submesh_counter].triangles) return FALSE; file_read(temp->submeshes[submesh_counter].triangles,sizeof(unsigned short)*3,temp->submeshes[submesh_counter].triangle_count,fp); if(FAILED(IDirect3DDevice9_CreateIndexBuffer(device,sizeof(unsigned short)*3*temp->submeshes[submesh_counter].triangle_count,0,D3DFMT_INDEX16,D3DPOOL_MANAGED,&temp->submeshes[submesh_counter].indexbuffer,NULL))) return FALSE; if(IDirect3DIndexBuffer9_Lock(temp->submeshes[submesh_counter].indexbuffer,0,0,&dest,0)==D3D_OK){ memcpy(dest,temp->submeshes[submesh_counter].triangles,sizeof(unsigned short)*3*temp->submeshes[submesh_counter].triangle_count); IDirect3DIndexBuffer9_Unlock(temp->submeshes[submesh_counter].indexbuffer); }else return FALSE; } file_close(fp); if(temp->morphtarget_count > 0) { printf("something shall morph!"); if(FAILED(IDirect3DDevice9_CreateVertexBuffer(device,sizeof(vertex)*temp->vertex_count,D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY,OBJECT_VERTEX_TYPE,D3DPOOL_DEFAULT,&temp->vertexbuffer,NULL))) return FALSE; } else { if(FAILED(IDirect3DDevice9_CreateVertexBuffer(device,sizeof(vertex)*temp->vertex_count,0,OBJECT_VERTEX_TYPE,D3DPOOL_MANAGED,&temp->vertexbuffer,NULL))) return FALSE; } if(IDirect3DVertexBuffer9_Lock(temp->vertexbuffer, 0, 0, (BYTE**)&dest, 0)==D3D_OK){ memcpy(dest,temp->vertices,sizeof(vertex)*temp->vertex_count); IDirect3DVertexBuffer9_Unlock(temp->vertexbuffer); temp->update = FALSE; }else return FALSE; /* save prs */ temp->prs.pos = position_vector; temp->prs.rot = rotation_quat; temp->prs.scale = scale_vector; /* build matrix */ matrix_identity(temp->mat); matrix_translate(position, position_vector); matrix_from_quat(rotation, rotation_quat); matrix_scale(scale, scale_vector); matrix_multiply(temp->mat, temp->mat, position); matrix_multiply(temp->mat, temp->mat, rotation); matrix_multiply(temp->mat, temp->mat, scale); return temp; }
/* Generate the target .res file name from the input file name */ static char* make_res_filename(const char *filename, const char *outputDir, const char *packageName, UErrorCode *status) { char *basename; char *dirname; char *resName; int32_t pkgLen = 0; /* length of package prefix */ if (U_FAILURE(*status)) { return 0; } if(packageName != NULL) { pkgLen = (int32_t)(1 + uprv_strlen(packageName)); } /* setup */ basename = dirname = resName = 0; /* determine basename, and compiled file names */ basename = (char*) uprv_malloc(sizeof(char) * (uprv_strlen(filename) + 1)); if(basename == 0) { *status = U_MEMORY_ALLOCATION_ERROR; goto finish; } get_basename(basename, filename); dirname = (char*) uprv_malloc(sizeof(char) * (uprv_strlen(filename) + 1)); if(dirname == 0) { *status = U_MEMORY_ALLOCATION_ERROR; goto finish; } get_dirname(dirname, filename); if (outputDir == NULL) { /* output in same dir as .txt */ resName = (char*) uprv_malloc(sizeof(char) * (uprv_strlen(dirname) + pkgLen + uprv_strlen(basename) + uprv_strlen(RES_SUFFIX) + 8)); if(resName == 0) { *status = U_MEMORY_ALLOCATION_ERROR; goto finish; } uprv_strcpy(resName, dirname); if(packageName != NULL) { uprv_strcat(resName, packageName); uprv_strcat(resName, "_"); } uprv_strcat(resName, basename); } else { int32_t dirlen = (int32_t)uprv_strlen(outputDir); int32_t basenamelen = (int32_t)uprv_strlen(basename); resName = (char*) uprv_malloc(sizeof(char) * (dirlen + pkgLen + basenamelen + 8)); if (resName == NULL) { *status = U_MEMORY_ALLOCATION_ERROR; goto finish; } uprv_strcpy(resName, outputDir); if(outputDir[dirlen] != U_FILE_SEP_CHAR) { resName[dirlen] = U_FILE_SEP_CHAR; resName[dirlen + 1] = '\0'; } if(packageName != NULL) { uprv_strcat(resName, packageName); uprv_strcat(resName, "_"); } uprv_strcat(resName, basename); } finish: uprv_free(basename); uprv_free(dirname); return resName; }
bool extract_file(CTar32CmdInfo &cmdinfo, CTar32 *pTarfile, const char *fname,std::vector<char> &buffer) { CTar32FileStatus &stat = pTarfile->m_currentfile_status; std::string fname2 = fname; EXTRACTINGINFOEX extractinfo; EXTRACTINGINFOEX64 exinfo64; MakeExtractingInfo(pTarfile,fname2.c_str(),extractinfo,exinfo64); { int ret = SendArcMessage(cmdinfo, ARCEXTRACT_BEGIN, &extractinfo,&exinfo64); if(ret){throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);} fname2 = extractinfo.exinfo.szDestFileName; } //上書き確認 if(cmdinfo.b_confirm_overwrite){ switch(ConfirmOverwrite(cmdinfo, exinfo64)){ case -1://cancel(abort) throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL); break; case 1: //yes to all cmdinfo.b_confirm_overwrite=false; break; } } size64 filesize = pTarfile->m_currentfile_status.original_size; CTar32InternalFile file; file.open(pTarfile); //std::ofstream fs_w; fast_fstream fs_w; if(!cmdinfo.b_print){ mkdir_recursive(get_dirname(fname2.c_str()).c_str()); fs_w.open(fname2.c_str(), std::ios::out|std::ios::binary); if(fs_w.fail()){return false;} } size64 readsize = 0; //static std::vector<char> buf; //const int bufsize=512*1024; //buf.resize(bufsize); const size_t bufsize=buffer.size(); while(filesize ==-1 || readsize<filesize){ size64 nextreadsize; if(filesize == -1){ // case ".gz",".Z",".bz2" //nextreadsize = sizeof(buf); nextreadsize=bufsize; }else{ size64 nextreadsize64 = filesize-readsize; if(nextreadsize64 > bufsize){nextreadsize64 = bufsize;} nextreadsize = nextreadsize64; if(nextreadsize==0){ Sleep(0); } // nextreadsize = (int)min(filesize-readsize, sizeof(buf)); } if(nextreadsize==0){ Sleep(0); } size64 n = file.read(&buffer[0],nextreadsize); readsize += n; if(cmdinfo.b_print){ cmdinfo.output.write(&buffer[0],(size_t)n); //TODO:size lost }else{ fs_w.write(&buffer[0],n); if(fs_w.fail()){return false;} } if(n != nextreadsize){ if(filesize == -1){ // case .gz/.Z/.bz2" break; }else{ return false; } } // if(cmdinfo.hTar32StatusDialog){ extractinfo.exinfo.dwWriteSize = (DWORD)readsize; exinfo64.exinfo.dwWriteSize = (DWORD)readsize; exinfo64.llWriteSize = readsize; int ret = SendArcMessage(cmdinfo, ARCEXTRACT_INPROCESS, &extractinfo,&exinfo64); if(ret){throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);} // } } if(!cmdinfo.b_print){ fs_w.close(); struct _utimbuf ut; ut.actime = (stat.atime ? stat.atime : time(NULL)); ut.modtime = (stat.mtime ? stat.mtime : time(NULL)); int ret; ret = _utime(fname2.c_str(), &ut); ret = _chmod(fname2.c_str(), stat.mode); } // if(cmdinfo.hTar32StatusDialog){ extractinfo.exinfo.dwWriteSize = (DWORD)readsize; exinfo64.exinfo.dwWriteSize = (DWORD)readsize; exinfo64.llWriteSize = readsize; int ret = SendArcMessage(cmdinfo, 6, &extractinfo,&exinfo64); if(ret){throw CTar32Exception("Cancel button was pushed.",ERROR_USER_CANCEL);} // } return true; }