int main(int argc, char **argv) { int i; gboolean no_filenames = TRUE; const char *path; /* set up l18n - the search directory needs to change * so that it uses the correct system directory when * subsurface isn't run from the local directory */ path = subsurface_gettext_domainpath(argv[0]); setlocale(LC_ALL, ""); bindtextdomain("subsurface", path); bind_textdomain_codeset("subsurface", "utf-8"); textdomain("subsurface"); setup_system_prefs(); prefs = default_prefs; #if DEBUGFILE > 1 debugfile = stderr; #elif defined(DEBUGFILE) debugfilename = strdup(prefs.default_filename); strncpy(debugfilename + strlen(debugfilename) - 3, "log", 3); if (g_mkdir_with_parents(g_path_get_dirname(debugfilename), 0664) != 0 || (debugfile = g_fopen(debugfilename, "w")) == NULL) printf("oh boy, can't create debugfile"); #endif subsurface_command_line_init(&argc, &argv); parse_xml_init(); init_ui(&argc, &argv); for (i = 1; i < argc; i++) { const char *a = argv[i]; if (a[0] == '-') { parse_argument(a); continue; } GError *error = NULL; /* if we have exactly one filename, parse_file will set * that to be the default. Otherwise there will be no default filename */ set_filename(NULL, TRUE); parse_file(a, &error, no_filenames); no_filenames = FALSE; if (error != NULL) { report_error(error); g_error_free(error); error = NULL; } } if (no_filenames) { GError *error = NULL; const char *filename = prefs.default_filename; parse_file(filename, &error, TRUE); /* don't report errors - this file may not exist, but make sure we remember this as the filename in use */ set_filename(filename, FALSE); } report_dives(imported, FALSE); if (dive_table.nr == 0) show_dive_info(NULL); run_ui(); exit_ui(); parse_xml_exit(); subsurface_command_line_exit(&argc, &argv); #ifdef DEBUGFILE if (debugfile) fclose(debugfile); #endif return 0; }
/** * ti9x_file_read_backup: * @filename: name of backup file to open. * @content: where to store the file content. * * Load the backup file into a Ti9xBackup structure. * * Structure content must be freed with #tifiles_content_delete_backup when * no longer used. If error occurs, the structure content is released for you. * * Return value: an error code, 0 otherwise. **/ int ti9x_file_read_backup(const char *filename, Ti9xBackup *content) { FILE *f; uint32_t file_size; char signature[9]; uint16_t sum; if (!tifiles_file_is_backup(filename)) { return ERR_INVALID_FILE; } f = g_fopen(filename, "rb"); if (f == NULL) { tifiles_info( "Unable to open this file: %s", filename); return ERR_FILE_OPEN; } if (content == NULL) { tifiles_critical("%s: an argument is NULL", __FUNCTION__); return ERR_INVALID_FILE; } if(fread_8_chars(f, signature) < 0) goto tfrb; content->model = tifiles_signature2calctype(signature); if (content->model == CALC_NONE) { return ERR_INVALID_FILE; } if(fread_word(f, NULL) < 0) goto tfrb; if(fread_8_chars(f, NULL) < 0) goto tfrb; if(fread_n_chars(f, 40, content->comment) < 0) goto tfrb; if(fread_word(f, NULL) < 0) goto tfrb; if(fread_long(f, NULL) < 0) goto tfrb; if(fread_8_chars(f, content->rom_version) < 0) goto tfrb; if(fread_byte(f, &(content->type)) < 0) goto tfrb; if(fread_byte(f, NULL) < 0) goto tfrb; if(fread_word(f, NULL) < 0) goto tfrb; if(fread_long(f, &file_size) < 0) goto tfrb; content->data_length = file_size - 0x52 - 2; if(fread_word(f, NULL) < 0) goto tfrb; content->data_part = (uint8_t *)g_malloc0(content->data_length); if (content->data_part == NULL) { fclose(f); tifiles_content_delete_backup(content); return ERR_MALLOC; } if(fread(content->data_part, 1, content->data_length, f) < content->data_length) goto tfrb; if(fread_word(f, &(content->checksum)) < 0) goto tfrb; sum = tifiles_checksum(content->data_part, content->data_length); #if defined(CHECKSUM_ENABLED) if(sum != content->checksum) { fclose(f); tifiles_content_delete_backup(content); return ERR_FILE_CHECKSUM; } #endif fclose(f); return 0; tfrb: // release on exit tifiles_critical("%s: error reading / understanding file %s", __FUNCTION__, filename); fclose(f); tifiles_content_delete_backup(content); return ERR_FILE_IO; }
/** * ti9x_file_write_regular: * @filename: name of single/group file where to write or NULL. * @content: the file content to write. * @real_filename: pointer address or NULL. Must be freed if needed when no longer needed. * * Write one (or several) variable(s) into a single (group) file. If filename is set to NULL, * the function build a filename from varname and allocates resulting filename in %real_fname. * %filename and %real_filename can be NULL but not both ! * * %real_filename must be freed when no longer used. * * Return value: an error code, 0 otherwise. **/ int ti9x_file_write_regular(const char *fname, Ti9xRegular *content, char **real_fname) { FILE *f; int i; char *filename = NULL; uint32_t offset = 0x52; int **table; int num_folders; char default_folder[FLDNAME_MAX]; char fldname[FLDNAME_MAX], varname[VARNAME_MAX]; if (content->entries == NULL) { tifiles_warning("%s: skipping content with NULL content->entries", __FUNCTION__); return 0; } if (fname != NULL) { filename = g_strdup(fname); if (filename == NULL) { return ERR_MALLOC; } } else { if (content->entries[0]) { filename = tifiles_build_filename(content->model_dst, content->entries[0]); } else { tifiles_warning("%s: asked to build a filename from null content->entries[0], bailing out", __FUNCTION__); if (real_fname != NULL) { *real_fname = NULL; } return 0; } if (real_fname != NULL) { *real_fname = g_strdup(filename); } } f = g_fopen(filename, "wb"); if (f == NULL) { tifiles_info( "Unable to open this file: %s", filename); g_free(filename); return ERR_FILE_OPEN; } g_free(filename); // build the table of folder & variable entries table = tifiles_create_table_of_entries((FileContent *)content, &num_folders); if (table == NULL) { return ERR_MALLOC; } // write header if(fwrite_8_chars(f, tifiles_calctype2signature(content->model)) < 0) goto tfwr; if(fwrite(fsignature, 1, 2, f) < 2) goto tfwr; if (content->num_entries == 1) // folder entry for single var is placed here { strcpy(content->default_folder, content->entries[0]->folder); } ticonv_varname_to_tifile_s(content->model, content->default_folder, default_folder, -1); if(fwrite_8_chars(f, default_folder) < 0) goto tfwr; if(fwrite_n_bytes(f, 40, (uint8_t *)content->comment) < 0) goto tfwr; if (content->num_entries > 1) { if(fwrite_word(f, (uint16_t) (content->num_entries + num_folders)) < 0) goto tfwr; offset += 16 * (content->num_entries + num_folders - 1); } else { if(fwrite_word(f, 1) < 0) goto tfwr; } // write table of entries for (i = 0; table[i] != NULL; i++) { VarEntry *fentry; int j, idx = table[i][0]; fentry = content->entries[idx]; if (fentry == NULL) { tifiles_warning("%s: skipping null content entry %d", __FUNCTION__, i); continue; } if (content->num_entries > 1) // single var does not have folder entry { if(fwrite_long(f, offset) < 0) goto tfwr; ticonv_varname_to_tifile_s(content->model, fentry->folder, fldname, -1); if(fwrite_8_chars(f, fldname) < 0) goto tfwr; if(fwrite_byte(f, (uint8_t)tifiles_folder_type(content->model)) < 0) goto tfwr; if(fwrite_byte(f, 0x00) < 0) goto tfwr; for (j = 0; table[i][j] != -1; j++); if(fwrite_word(f, (uint16_t) j) < 0) goto tfwr; } for (j = 0; table[i][j] != -1; j++) { int idx2 = table[i][j]; VarEntry *entry = content->entries[idx2]; uint8_t attr = ATTRB_NONE; if(fwrite_long(f, offset) < 0) goto tfwr; ticonv_varname_to_tifile_s(content->model, entry->name, varname, entry->type); if(fwrite_8_chars(f, varname) < 0) goto tfwr; if(fwrite_byte(f, entry->type) < 0) goto tfwr; attr = (entry->attr == ATTRB_ARCHIVED) ? 3 : entry->attr; if(fwrite_byte(f, attr) < 0) goto tfwr; if(fwrite_word(f, 0) < 0) goto tfwr; offset += entry->size + 4 + 2; } } if(fwrite_long(f, offset) < 0) goto tfwr; if(fwrite_word(f, 0x5aa5) < 0) goto tfwr; // write data for (i = 0; table[i] != NULL; i++) { int j; for (j = 0; table[i][j] != -1; j++) { int idx = table[i][j]; VarEntry *entry = content->entries[idx]; uint16_t sum; if(fwrite_long(f, 0) < 0) goto tfwr; if(fwrite(entry->data, 1, entry->size, f) < entry->size) goto tfwr; sum = tifiles_checksum(entry->data, entry->size); if(fwrite_word(f, sum) < 0) goto tfwr; } } // g_free( memory for (i = 0; i < num_folders; i++) g_free(table[i]); g_free(table); fclose(f); return 0; tfwr: // release on exit tifiles_critical("%s: error writing file %s", __FUNCTION__, filename); fclose(f); return ERR_FILE_IO; }
static void convert2tabfile(const gchar *ifofilename, print_info_t print_info) { std::string idxfilename=ifofilename; idxfilename.replace(idxfilename.length()-sizeof("ifo")+1, sizeof("ifo")-1, "idx"); struct stat idx_stats; if (g_stat (idxfilename.c_str(), &idx_stats) == -1) { gchar *str = g_strdup_printf("File not exist: %s\n", idxfilename.c_str()); print_info(str); g_free(str); return; } std::string dictfilename=ifofilename; dictfilename.replace(dictfilename.length()-sizeof("ifo")+1, sizeof("ifo")-1, "dict"); struct stat dict_stats; if (g_stat (dictfilename.c_str(), &dict_stats) == -1) { #ifdef _WIN32 gchar *str = g_strdup_printf("File not exist: %s\nPlease rename somedict.dict.dz to somedict.dict.gz and use SevenZip to uncompress the somedict.dict.gz file, then you can get the somedict.dict file.\n", dictfilename.c_str()); #else gchar *str = g_strdup_printf("File not exist: %s\nPlease do \"mv somedict.dict.dz somedict.dict.gz;gunzip somedict.dict.gz\"\n", dictfilename.c_str()); #endif print_info(str); g_free(str); return; } gchar *idxbuffer = (gchar *)g_malloc (idx_stats.st_size); gchar *idxbuffer_end = idxbuffer+idx_stats.st_size; FILE *idxfile; idxfile = g_fopen(idxfilename.c_str(),"rb"); fread (idxbuffer, 1, idx_stats.st_size, idxfile); fclose (idxfile); gchar *dictbuffer = (gchar *)g_malloc (dict_stats.st_size); FILE *dictfile; dictfile = g_fopen(dictfilename.c_str(),"rb"); fread (dictbuffer, 1, dict_stats.st_size, dictfile); fclose (dictfile); gchar *basefilename = g_path_get_basename(ifofilename); std::string txtfilename=basefilename; g_free(basefilename); txtfilename.replace(txtfilename.length()-sizeof("ifo")+1, sizeof("ifo")-1, "txt"); gchar *str = g_strdup_printf("Write to file: %s\n", txtfilename.c_str()); print_info(str); g_free(str); FILE *txtfile; txtfile = g_fopen(txtfilename.c_str(),"w"); gchar *p=idxbuffer; int wordlen; guint32 offset, size; gchar *data; while (1) { if (p == idxbuffer_end) { break; } wordlen=strlen(p); fwrite(p, wordlen, 1, txtfile); fwrite("\t", 1, 1, txtfile); p+=wordlen +1; offset=*reinterpret_cast<guint32 *>(p); offset=g_ntohl(offset); p+=sizeof(guint32); size=*reinterpret_cast<guint32 *>(p); size=g_ntohl(size); p+=sizeof(guint32); data=dictbuffer+offset; while ((guint32)(data-(dictbuffer+offset))<size) { switch (*data) { case '\n': fwrite("\\n", 2, 1, txtfile); break; case '\\': fwrite("\\\\", 2, 1, txtfile); break; default: fwrite(data, 1, 1, txtfile); break; } data++; } fwrite("\n", 1, 1, txtfile); } fclose(txtfile); g_free(idxbuffer); g_free(dictbuffer); }
GimpPlugInProcedure * file_procedure_find (GSList *procs, const gchar *uri, GError **error) { GimpPlugInProcedure *file_proc; GSList *all_procs = procs; gchar *filename; g_return_val_if_fail (procs != NULL, NULL); g_return_val_if_fail (uri != NULL, NULL); g_return_val_if_fail (error == NULL || *error == NULL, NULL); /* First, check magicless prefixes/suffixes */ file_proc = file_proc_find_by_name (all_procs, uri, TRUE); if (file_proc) return file_proc; filename = file_utils_filename_from_uri (uri); /* Then look for magics */ if (filename) { GimpPlugInProcedure *size_matched_proc = NULL; FILE *ifp = NULL; gboolean opened = FALSE; gint head_size = 0; gint size_match_count = 0; guchar head[256]; while (procs) { file_proc = procs->data; procs = procs->next; if (file_proc->magics_list) { if (G_UNLIKELY (!opened)) { ifp = g_fopen (filename, "rb"); if (ifp != NULL) head_size = fread ((gchar *) head, 1, sizeof (head), ifp); else g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (errno), g_strerror (errno)); opened = TRUE; } if (head_size >= 4) { FileMatchType match_val; match_val = file_check_magic_list (file_proc->magics_list, head, head_size, ifp); if (match_val == FILE_MATCH_SIZE) { /* Use it only if no other magic matches */ size_match_count++; size_matched_proc = file_proc; } else if (match_val != FILE_MATCH_NONE) { fclose (ifp); g_free (filename); return file_proc; } } } } if (ifp) { if (ferror (ifp)) g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (errno), g_strerror (errno)); fclose (ifp); } g_free (filename); if (size_match_count == 1) return size_matched_proc; } /* As a last resort, try matching by name */ file_proc = file_proc_find_by_name (all_procs, uri, FALSE); if (file_proc) { /* we found a procedure, clear error that might have been set */ g_clear_error (error); } else { /* set an error message unless one was already set */ if (error && *error == NULL) g_set_error_literal (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Unknown file type")); } return file_proc; }
static gint pop3_write_msg_to_file(const gchar *file, const gchar *data, guint len, const gchar *prefix) { FILE *fp; const gchar *prev, *cur; cm_return_val_if_fail(file != NULL, -1); if ((fp = g_fopen(file, "wb")) == NULL) { FILE_OP_ERROR(file, "fopen"); return -1; } if (change_file_mode_rw(fp, file) < 0) FILE_OP_ERROR(file, "chmod"); if (prefix != NULL) { if (fprintf(fp, "%s\n", prefix) < 0) { FILE_OP_ERROR(file, "fprintf"); fclose(fp); claws_unlink(file); return -1; } } /* +------------------+----------------+--------------------------+ * * ^data ^prev ^cur data+len-1^ */ prev = data; while ((cur = (gchar *)my_memmem(prev, len - (prev - data), "\r\n", 2)) != NULL) { if ((cur > prev && fwrite(prev, 1, cur - prev, fp) < 1) || fputc('\n', fp) == EOF) { FILE_OP_ERROR(file, "fwrite"); g_warning("can't write to file: %s", file); fclose(fp); claws_unlink(file); return -1; } if (cur == data + len - 1) { prev = cur + 1; break; } if (*(cur + 1) == '\n') prev = cur + 2; else prev = cur + 1; if (prev - data < len - 1 && *prev == '.' && *(prev + 1) == '.') prev++; if (prev - data >= len) break; } if (prev - data < len && fwrite(prev, 1, len - (prev - data), fp) < 1) { FILE_OP_ERROR(file, "fwrite"); g_warning("can't write to file: %s", file); fclose(fp); claws_unlink(file); return -1; } if (data[len - 1] != '\r' && data[len - 1] != '\n') { if (fputc('\n', fp) == EOF) { FILE_OP_ERROR(file, "fputc"); g_warning("can't write to file: %s", file); fclose(fp); claws_unlink(file); return -1; } } if (fclose(fp) == EOF) { FILE_OP_ERROR(file, "fclose"); claws_unlink(file); return -1; } return 0; }
static void cm_load_file_response_callback (GtkWidget *dialog, gint response_id, CmParamsType *mix) { FILE *fp; if (response_id == GTK_RESPONSE_OK) { gchar *filename; filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)); fp = g_fopen (filename, "rb"); if (fp) { gchar buf[3][CM_LINE_SIZE]; buf[0][0] = '\0'; buf[1][0] = '\0'; buf[2][0] = '\0'; fgets (buf[0], CM_LINE_SIZE - 1, fp); fscanf (fp, "%*s %1023s", buf[0]); if (strcmp (buf[0], "RED") == 0) mix->output_channel = CM_RED_CHANNEL; else if (strcmp (buf[0], "GREEN") == 0) mix->output_channel = CM_GREEN_CHANNEL; else if (strcmp (buf[0], "BLUE") == 0) mix->output_channel = CM_BLUE_CHANNEL; fscanf (fp, "%*s %1023s", buf[0]); /* preview flag, preserved for compatibility */ fscanf (fp, "%*s %1023s", buf[0]); if (strcmp (buf[0], "TRUE") == 0) mix->monochrome = TRUE; else mix->monochrome = FALSE; fscanf (fp, "%*s %1023s", buf[0]); if (strcmp (buf[0], "TRUE") == 0) mix->preserve_luminosity = TRUE; else mix->preserve_luminosity = FALSE; fscanf (fp, "%*s %1023s %1023s %1023s", buf[0], buf[1], buf[2]); mix->red.red_gain = g_ascii_strtod (buf[0], NULL); mix->red.green_gain = g_ascii_strtod (buf[1], NULL); mix->red.blue_gain = g_ascii_strtod (buf[2], NULL); fscanf (fp, "%*s %1023s %1023s %1023s", buf[0], buf[1], buf[2]); mix->green.red_gain = g_ascii_strtod (buf[0], NULL); mix->green.green_gain = g_ascii_strtod (buf[1], NULL); mix->green.blue_gain = g_ascii_strtod (buf[2], NULL); fscanf (fp, "%*s %1023s %1023s %1023s", buf[0], buf[1], buf[2]); mix->blue.red_gain = g_ascii_strtod (buf[0], NULL); mix->blue.green_gain = g_ascii_strtod (buf[1], NULL); mix->blue.blue_gain = g_ascii_strtod (buf[2], NULL); fscanf (fp, "%*s %1023s %1023s %1023s", buf[0], buf[1], buf[2]); mix->black.red_gain = g_ascii_strtod (buf[0], NULL); mix->black.green_gain = g_ascii_strtod (buf[1], NULL); mix->black.blue_gain = g_ascii_strtod (buf[2], NULL); fclose (fp); cm_update_ui (mix); } else { g_message (_("Could not open '%s' for reading: %s"), gimp_filename_to_utf8 (filename), g_strerror (errno)); } g_free (filename); } gtk_widget_hide (dialog); }
static GstFlowReturn gst_multi_file_sink_render (GstBaseSink * sink, GstBuffer * buffer) { GstMultiFileSink *multifilesink; guint size; guint8 *data; gchar *filename; gboolean ret; GError *error = NULL; size = GST_BUFFER_SIZE (buffer); data = GST_BUFFER_DATA (buffer); multifilesink = GST_MULTI_FILE_SINK (sink); switch (multifilesink->next_file) { case GST_MULTI_FILE_SINK_NEXT_BUFFER: filename = g_strdup_printf (multifilesink->filename, multifilesink->index); ret = g_file_set_contents (filename, (char *) data, size, &error); if (!ret) goto write_error; gst_multi_file_sink_post_message (multifilesink, buffer, filename); multifilesink->index++; g_free (filename); break; case GST_MULTI_FILE_SINK_NEXT_DISCONT: if (GST_BUFFER_IS_DISCONT (buffer)) { if (multifilesink->file) { fclose (multifilesink->file); multifilesink->file = NULL; filename = g_strdup_printf (multifilesink->filename, multifilesink->index); gst_multi_file_sink_post_message (multifilesink, buffer, filename); g_free (filename); multifilesink->index++; } } if (multifilesink->file == NULL) { filename = g_strdup_printf (multifilesink->filename, multifilesink->index); multifilesink->file = g_fopen (filename, "wb"); g_free (filename); if (multifilesink->file == NULL) goto stdio_write_error; } ret = fwrite (GST_BUFFER_DATA (buffer), GST_BUFFER_SIZE (buffer), 1, multifilesink->file); if (ret != 1) goto stdio_write_error; break; case GST_MULTI_FILE_SINK_NEXT_KEY_FRAME: if (multifilesink->next_segment == GST_CLOCK_TIME_NONE) { if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) { multifilesink->next_segment = GST_BUFFER_TIMESTAMP (buffer) + 10 * GST_SECOND; } } if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) && GST_BUFFER_TIMESTAMP (buffer) >= multifilesink->next_segment && !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) { if (multifilesink->file) { fclose (multifilesink->file); multifilesink->file = NULL; filename = g_strdup_printf (multifilesink->filename, multifilesink->index); gst_multi_file_sink_post_message (multifilesink, buffer, filename); g_free (filename); multifilesink->index++; } multifilesink->next_segment += 10 * GST_SECOND; } if (multifilesink->file == NULL) { filename = g_strdup_printf (multifilesink->filename, multifilesink->index); multifilesink->file = g_fopen (filename, "wb"); g_free (filename); if (multifilesink->file == NULL) goto stdio_write_error; } ret = fwrite (GST_BUFFER_DATA (buffer), GST_BUFFER_SIZE (buffer), 1, multifilesink->file); if (ret != 1) goto stdio_write_error; break; default: g_assert_not_reached (); } return GST_FLOW_OK; /* ERRORS */ write_error: { switch (error->code) { case G_FILE_ERROR_NOSPC:{ GST_ELEMENT_ERROR (multifilesink, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL)); break; } default:{ GST_ELEMENT_ERROR (multifilesink, RESOURCE, WRITE, ("Error while writing to file \"%s\".", filename), ("%s", g_strerror (errno))); } } g_error_free (error); g_free (filename); return GST_FLOW_ERROR; } stdio_write_error: GST_ELEMENT_ERROR (multifilesink, RESOURCE, WRITE, ("Error while writing to file."), (NULL)); return GST_FLOW_ERROR; }
GList * gimp_gradient_load (const gchar *filename, GError **error) { GimpGradient *gradient; GimpGradientSegment *prev; gint num_segments; gint i; FILE *file; gchar line[1024]; gint linenum; g_return_val_if_fail (filename != NULL, NULL); g_return_val_if_fail (g_path_is_absolute (filename), NULL); g_return_val_if_fail (error == NULL || *error == NULL, NULL); file = g_fopen (filename, "rb"); if (!file) { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_OPEN, _("Could not open '%s' for reading: %s"), gimp_filename_to_utf8 (filename), g_strerror (errno)); return NULL; } linenum = 1; if (! fgets (line, sizeof (line), file)) { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Fatal parse error in gradient file '%s': " "Read error in line %d."), gimp_filename_to_utf8 (filename), linenum); fclose (file); return NULL; } if (! g_str_has_prefix (line, "GIMP Gradient")) { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Fatal parse error in gradient file '%s': " "Not a GIMP gradient file."), gimp_filename_to_utf8 (filename)); fclose (file); return NULL; } gradient = g_object_new (GIMP_TYPE_GRADIENT, "mime-type", "application/x-gimp-gradient", NULL); linenum++; if (! fgets (line, sizeof (line), file)) { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Fatal parse error in gradient file '%s': " "Read error in line %d."), gimp_filename_to_utf8 (filename), linenum); fclose (file); g_object_unref (gradient); return NULL; } if (g_str_has_prefix (line, "Name: ")) { gchar *utf8; utf8 = gimp_any_to_utf8 (g_strstrip (line + strlen ("Name: ")), -1, _("Invalid UTF-8 string in gradient file '%s'."), gimp_filename_to_utf8 (filename)); gimp_object_take_name (GIMP_OBJECT (gradient), utf8); linenum++; if (! fgets (line, sizeof (line), file)) { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Fatal parse error in gradient file '%s': " "Read error in line %d."), gimp_filename_to_utf8 (filename), linenum); fclose (file); g_object_unref (gradient); return NULL; } } else /* old gradient format */ { gimp_object_take_name (GIMP_OBJECT (gradient), g_filename_display_basename (filename)); } num_segments = atoi (line); if (num_segments < 1) { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Fatal parse error in gradient file '%s': " "File is corrupt in line %d."), gimp_filename_to_utf8 (filename), linenum); g_object_unref (gradient); fclose (file); return NULL; } prev = NULL; for (i = 0; i < num_segments; i++) { GimpGradientSegment *seg; gchar *end; gint color; gint type; gint left_color_type; gint right_color_type; seg = gimp_gradient_segment_new (); seg->prev = prev; if (prev) prev->next = seg; else gradient->segments = seg; linenum++; if (! fgets (line, sizeof (line), file)) { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Fatal parse error in gradient file '%s': " "Read error in line %d."), gimp_filename_to_utf8 (filename), linenum); fclose (file); g_object_unref (gradient); return NULL; } seg->left = g_ascii_strtod (line, &end); if (end && errno != ERANGE) seg->middle = g_ascii_strtod (end, &end); if (end && errno != ERANGE) seg->right = g_ascii_strtod (end, &end); if (end && errno != ERANGE) seg->left_color.r = g_ascii_strtod (end, &end); if (end && errno != ERANGE) seg->left_color.g = g_ascii_strtod (end, &end); if (end && errno != ERANGE) seg->left_color.b = g_ascii_strtod (end, &end); if (end && errno != ERANGE) seg->left_color.a = g_ascii_strtod (end, &end); if (end && errno != ERANGE) seg->right_color.r = g_ascii_strtod (end, &end); if (end && errno != ERANGE) seg->right_color.g = g_ascii_strtod (end, &end); if (end && errno != ERANGE) seg->right_color.b = g_ascii_strtod (end, &end); if (end && errno != ERANGE) seg->right_color.a = g_ascii_strtod (end, &end); if (errno != ERANGE) { switch (sscanf (end, "%d %d %d %d", &type, &color, &left_color_type, &right_color_type)) { case 4: seg->left_color_type = (GimpGradientColor) left_color_type; seg->right_color_type = (GimpGradientColor) right_color_type; /* fall thru */ case 2: seg->type = (GimpGradientSegmentType) type; seg->color = (GimpGradientSegmentColor) color; break; default: g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Fatal parse error in gradient file '%s': " "Corrupt segment %d in line %d."), gimp_filename_to_utf8 (filename), i, linenum); g_object_unref (gradient); fclose (file); return NULL; } } else { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Fatal parse error in gradient file '%s': " "Corrupt segment %d in line %d."), gimp_filename_to_utf8 (filename), i, linenum); g_object_unref (gradient); fclose (file); return NULL; } if ( (prev && (prev->right < seg->left)) || (!prev && (0. < seg->left) )) { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Gradient file '%s' is corrupt: " "Segments do not span the range 0-1."), gimp_filename_to_utf8 (filename)); g_object_unref (gradient); fclose (file); return NULL; } prev = seg; } if (prev->right < 1.0) { g_set_error (error, GIMP_DATA_ERROR, GIMP_DATA_ERROR_READ, _("Gradient file '%s' is corrupt: " "Segments do not span the range 0-1."), gimp_filename_to_utf8 (filename)); g_object_unref (gradient); fclose (file); return NULL; } fclose (file); return g_list_prepend (NULL, gradient); }
gint xjpg_save_drawable (const char *filename, gint32 image_ID, gint32 drawable_ID, gint save_mode, t_JpegSaveVals *jsvals) { GimpPixelRgn pixel_rgn; GimpDrawable *drawable; GimpImageType drawable_type; struct jpeg_compress_struct cinfo; struct my_error_mgr jerr; FILE * volatile outfile; guchar *temp, *t; guchar *data; guchar *src, *s; int has_alpha; int rowstride, yend; int i, j; int alpha_offset; guchar alpha_byte; guchar volatile l_alpha_sum; alpha_offset = 0; has_alpha = 0; src = NULL; temp = NULL; data = NULL; l_alpha_sum = 0xff; drawable = gimp_drawable_get (drawable_ID); drawable_type = gimp_drawable_type (drawable_ID); switch (drawable_type) { case GIMP_RGB_IMAGE: case GIMP_GRAY_IMAGE: if(save_mode == JSVM_ALPHA) return FALSE; /* there is no alpha to save */ break; case GIMP_RGBA_IMAGE: case GIMP_GRAYA_IMAGE: break; case GIMP_INDEXED_IMAGE: /*g_message ("jpeg: cannot operate on indexed color images");*/ return FALSE; break; default: /*g_message ("jpeg: cannot operate on unknown image types");*/ return FALSE; break; } gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, drawable->width, drawable->height, FALSE, FALSE); /* Step 1: allocate and initialize JPEG compression object */ /* We have to set up the error handler first, in case the initialization * step fails. (Unlikely, but it could happen if you are out of memory.) * This routine fills in the contents of struct jerr, and returns jerr's * address which we place into the link field in cinfo. */ cinfo.err = jpeg_std_error (&jerr.pub); jerr.pub.error_exit = my_error_exit; outfile = NULL; /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp (jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. * We need to clean up the JPEG object, close the input file, and return. */ jpeg_destroy_compress (&cinfo); if (outfile) fclose (outfile); if (drawable) gimp_drawable_detach (drawable); return FALSE; } /* Now we can initialize the JPEG compression object. */ jpeg_create_compress (&cinfo); /* Step 2: specify data destination (eg, a file) */ /* Note: steps 2 and 3 can be done in either order. */ /* Here we use the library-supplied code to send compressed data to a * stdio stream. You can also write your own code to do something else. * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that * requires it in order to write binary files. */ if ((outfile = g_fopen (filename, "wb")) == NULL) { g_message ("can't open %s\n", filename); return FALSE; } jpeg_stdio_dest (&cinfo, outfile); /* Get the input image and a pointer to its data. */ switch (drawable_type) { case GIMP_RGB_IMAGE: case GIMP_GRAY_IMAGE: /* # of color components per pixel */ cinfo.input_components = drawable->bpp; has_alpha = 0; alpha_offset = 0; break; case GIMP_RGBA_IMAGE: case GIMP_GRAYA_IMAGE: if(save_mode == JSVM_ALPHA) { cinfo.input_components = 1; } else { /* # of color components per pixel (minus the GIMP alpha channel) */ cinfo.input_components = drawable->bpp - 1; } alpha_offset = drawable->bpp -1; has_alpha = 1; break; default: return FALSE; break; } /* Step 3: set parameters for compression */ /* First we supply a description of the input image. * Four fields of the cinfo struct must be filled in: */ /* image width and height, in pixels */ cinfo.image_width = drawable->width; cinfo.image_height = drawable->height; /* colorspace of input image */ cinfo.in_color_space = ( (save_mode != JSVM_ALPHA) && (drawable_type == GIMP_RGB_IMAGE || drawable_type == GIMP_RGBA_IMAGE)) ? JCS_RGB : JCS_GRAYSCALE; /* Now use the library's routine to set default compression parameters. * (You must set at least cinfo.in_color_space before calling this, * since the defaults depend on the source color space.) */ jpeg_set_defaults (&cinfo); /* Now you can set any non-default parameters you wish to. * Here we just illustrate the use of quality (quantization table) scaling: */ jpeg_set_quality (&cinfo, (int) (jsvals->quality * 100), TRUE /* limit to baseline-JPEG values */); cinfo.smoothing_factor = (int) (jsvals->smoothing * 100); cinfo.optimize_coding = jsvals->optimize; /* Step 4: Start compressor */ /* TRUE ensures that we will write a complete interchange-JPEG file. * Pass TRUE unless you are very sure of what you're doing. */ jpeg_start_compress (&cinfo, TRUE); /* Step 5: while (scan lines remain to be written) */ /* jpeg_write_scanlines(...); */ /* Here we use the library's state variable cinfo.next_scanline as the * loop counter, so that we don't have to keep track ourselves. * To keep things simple, we pass one scanline per call; you can pass * more if you wish, though. */ /* JSAMPLEs per row in image_buffer */ rowstride = drawable->bpp * drawable->width; temp = (guchar *) g_malloc (cinfo.image_width * cinfo.input_components); data = (guchar *) g_malloc (rowstride * gimp_tile_height ()); src = data; while (cinfo.next_scanline < cinfo.image_height) { if ((cinfo.next_scanline % gimp_tile_height ()) == 0) { yend = cinfo.next_scanline + gimp_tile_height (); yend = MIN (yend, cinfo.image_height); gimp_pixel_rgn_get_rect (&pixel_rgn, data, 0, cinfo.next_scanline, cinfo.image_width, (yend - cinfo.next_scanline)); src = data; } t = temp; s = src; i = cinfo.image_width; switch(save_mode) { case JSVM_DRAWABLE: if(jsvals->clr_transparent) { /* save drawable (clear pixels where alpha is full transparent) */ while (i--) { alpha_byte = s[cinfo.input_components]; for (j = 0; j < cinfo.input_components; j++) { if(alpha_byte != 0) { *t++ = *s++; } else { *t++ = 0; s++; } } if (has_alpha) /* ignore alpha channel */ { s++; } } } else { /* save the drawable as it is (ignore alpha channel) */ while (i--) { for (j = 0; j < cinfo.input_components; j++) { *t++ = *s++; } if (has_alpha) /* ignore alpha channel */ { s++; } } } break; case JSVM_ALPHA: /* save the drawable's alpha cahnnel */ while (i--) { s += alpha_offset; l_alpha_sum &= (*s); /* check all alpha bytes for full opacity */ *t++ = *s++; } break; } src += rowstride; jpeg_write_scanlines (&cinfo, (JSAMPARRAY) &temp, 1); if ((cinfo.next_scanline % 5) == 0) gimp_progress_update ((double) cinfo.next_scanline / (double) cinfo.image_height); } /* Step 6: Finish compression */ jpeg_finish_compress (&cinfo); /* After finish_compress, we can close the output file. */ fclose (outfile); if((save_mode == JSVM_ALPHA) && (l_alpha_sum == 0xff)) { /* all bytes in the alpha channel are set to 0xff * == full opaque image. We can remove the file * to save diskspace */ g_remove(filename); } /* Step 7: release JPEG compression object */ /* This is an important step since it will release a good deal of memory. */ jpeg_destroy_compress (&cinfo); /* free the temporary buffer */ g_free (temp); g_free (data); gimp_drawable_detach (drawable); return TRUE; } /* end xjpg_save_drawable */
gint32 xjpg_load_layer (const char *filename, gint32 image_id, int image_type, char *layer_name, gdouble layer_opacity, GimpLayerModeEffects layer_mode ) { GimpPixelRgn l_pixel_rgn; GimpDrawable *l_drawable; gint32 l_layer_id; GimpImageType l_layer_type; struct jpeg_decompress_struct cinfo; struct my_error_mgr jerr; FILE *infile; guchar *l_buf; guchar **l_rowbuf; int l_tile_height; int l_scanlines; int l_idx, l_start, l_end; /* We set up the normal JPEG error routines. */ cinfo.err = jpeg_std_error (&jerr.pub); jerr.pub.error_exit = my_error_exit; l_layer_type = GIMP_GRAY_IMAGE; if ((infile = g_fopen (filename, "rb")) == NULL) { g_warning ("can't open \"%s\"\n", filename); return -1; } /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp (jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. * We need to clean up the JPEG object, close the input file, and return. */ jpeg_destroy_decompress (&cinfo); if (infile) fclose (infile); g_printerr ("XJT: JPEG load error\n"); return -1; } /* Now we can initialize the JPEG decompression object. */ jpeg_create_decompress (&cinfo); /* Step 2: specify data source (eg, a file) */ jpeg_stdio_src (&cinfo, infile); /* Step 3: read file parameters with jpeg_read_header() */ (void) jpeg_read_header (&cinfo, TRUE); /* We can ignore the return value from jpeg_read_header since * (a) suspension is not possible with the stdio data source, and * (b) we passed TRUE to reject a tables-only JPEG file as an error. * See libjpeg.doc for more info. */ /* Step 4: set parameters for decompression */ /* In this example, we don't need to change any of the defaults set by * jpeg_read_header(), so we do nothing here. */ /* Step 5: Start decompressor */ jpeg_start_decompress (&cinfo); /* We may need to do some setup of our own at this point before reading * the data. After jpeg_start_decompress() we have the correct scaled * output image dimensions available, as well as the output colormap * if we asked for color quantization. * In this example, we need to make an output work buffer of the right size. */ /* temporary buffer */ l_tile_height = gimp_tile_height (); l_buf = g_new (guchar, l_tile_height * cinfo.output_width * cinfo.output_components); l_rowbuf = g_new (guchar*, l_tile_height); for (l_idx = 0; l_idx < l_tile_height; l_idx++) { l_rowbuf[l_idx] = l_buf + cinfo.output_width * cinfo.output_components * l_idx; } /* Check jpeg file for layer type */ switch (cinfo.output_components) { case 1: l_layer_type = GIMP_GRAY_IMAGE; break; case 3: l_layer_type = GIMP_RGB_IMAGE; break; default: g_printerr ("XJT: cant load layer %s (type is not GRAY and not RGB)\n", filename); fclose (infile); return -1; } l_layer_id = gimp_layer_new (image_id, layer_name, cinfo.output_width, cinfo.output_height, l_layer_type, layer_opacity, layer_mode); if(l_layer_id < 0) { g_printerr ("XJT: cant create new layer\n"); fclose (infile); return -1; } l_drawable = gimp_drawable_get (l_layer_id); gimp_pixel_rgn_init (&l_pixel_rgn, l_drawable, 0, 0, l_drawable->width, l_drawable->height, TRUE, FALSE); /* Step 6: while (scan lines remain to be read) */ /* jpeg_read_scanlines(...); */ /* Here we use the library's state variable cinfo.output_scanline as the * loop counter, so that we don't have to keep track ourselves. */ while (cinfo.output_scanline < cinfo.output_height) { l_start = cinfo.output_scanline; l_end = cinfo.output_scanline + l_tile_height; l_end = MIN (l_end, cinfo.output_height); l_scanlines = l_end - l_start; for (l_idx = 0; l_idx < l_scanlines; l_idx++) { jpeg_read_scanlines (&cinfo, (JSAMPARRAY) &l_rowbuf[l_idx], 1); } gimp_pixel_rgn_set_rect (&l_pixel_rgn, l_buf, 0, l_start, l_drawable->width, l_scanlines); gimp_progress_update ((double) cinfo.output_scanline / (double) cinfo.output_height); } /* Step 7: Finish decompression */ jpeg_finish_decompress (&cinfo); /* We can ignore the return value since suspension is not possible * with the stdio data source. */ /* Step 8: Release JPEG decompression object */ /* This is an important step since it will release a good deal of memory. */ jpeg_destroy_decompress (&cinfo); /* free up the temporary buffers */ g_free (l_rowbuf); g_free (l_buf); /* After finish_decompress, we can close the input file. * Here we postpone it until after no more JPEG errors are possible, * so as to simplify the setjmp error logic above. (Actually, I don't * think that jpeg_destroy can do an error exit, but why assume anything...) */ fclose (infile); /* At this point you may want to check to see whether any corrupt-data * warnings occurred (test whether jerr.num_warnings is nonzero). */ return (l_layer_id); } /* end xjpg_load_layer */
gint xjpg_load_layer_alpha (const char *filename, gint32 image_id, gint32 layer_id) { GimpPixelRgn l_pixel_rgn; GimpDrawable *l_drawable; GimpImageType l_layer_type; struct jpeg_decompress_struct cinfo; struct my_error_mgr jerr; FILE *infile; guchar *l_buf; guchar *l_dstbuf; guchar **l_rowbuf; int l_tile_height; int l_scanlines; int l_idx, l_start, l_end; int l_alpha_offset; guchar *l_buf_ptr; guchar *l_dstbuf_ptr; /* We set up the normal JPEG error routines. */ cinfo.err = jpeg_std_error (&jerr.pub); jerr.pub.error_exit = my_error_exit; l_layer_type = GIMP_GRAY_IMAGE; /* add alpha channel */ gimp_layer_add_alpha (layer_id); if ((infile = g_fopen (filename, "rb")) == NULL) { /* No alpha found, thats OK, use full opaque alpha channel * (there is no need not store alpha channels on full opaque channels) * (fixme: if filename exists but is not readable * we should return -1 to indicate an error */ return 0; /* OK */ } /* Establish the setjmp return context for my_error_exit to use. */ if (setjmp (jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. * We need to clean up the JPEG object, close the input file, and return. */ jpeg_destroy_decompress (&cinfo); if (infile) fclose (infile); g_printerr ("XJT: JPEG alpha load error\n"); return -1; } /* Now we can initialize the JPEG decompression object. */ jpeg_create_decompress (&cinfo); /* Step 2: specify data source (eg, a file) */ jpeg_stdio_src (&cinfo, infile); /* Step 3: read file parameters with jpeg_read_header() */ (void) jpeg_read_header (&cinfo, TRUE); /* We can ignore the return value from jpeg_read_header since * (a) suspension is not possible with the stdio data source, and * (b) we passed TRUE to reject a tables-only JPEG file as an error. * See libjpeg.doc for more info. */ /* Step 4: set parameters for decompression */ /* In this example, we don't need to change any of the defaults set by * jpeg_read_header(), so we do nothing here. */ /* Step 5: Start decompressor */ jpeg_start_decompress (&cinfo); /* We may need to do some setup of our own at this point before reading * the data. After jpeg_start_decompress() we have the correct scaled * output image dimensions available, as well as the output colormap * if we asked for color quantization. * In this example, we need to make an output work buffer of the right size. */ /* temporary buffer (for read in jpeg lines) */ l_tile_height = gimp_tile_height (); l_buf = g_new (guchar, l_tile_height * cinfo.output_width * cinfo.output_components); l_rowbuf = g_new (guchar*, l_tile_height); for (l_idx = 0; l_idx < l_tile_height; l_idx++) { l_rowbuf[l_idx] = l_buf + cinfo.output_width * cinfo.output_components * l_idx; } l_drawable = gimp_drawable_get (layer_id); if(l_drawable == NULL) { g_printerr ("XJT: gimp_drawable_get failed on layer id %d\n", (int)layer_id); fclose(infile); return -1; } /* Check if jpeg file can be used as alpha channel */ if((cinfo.output_components != 1) || (cinfo.output_width != l_drawable->width) || (cinfo.output_height != l_drawable->height)) { g_printerr ("XJT: cant load %s as alpha channel\n", filename); fclose (infile); return -1; } /* buffer to read in the layer and merge with the alpha from jpeg file */ l_dstbuf = g_new (guchar, l_tile_height * l_drawable->width * l_drawable->bpp); gimp_pixel_rgn_init (&l_pixel_rgn, l_drawable, 0, 0, l_drawable->width, l_drawable->height, TRUE, FALSE); l_alpha_offset = l_drawable->bpp -1; /* Step 6: while (scan lines remain to be read) */ /* jpeg_read_scanlines(...); */ /* Here we use the library's state variable cinfo.output_scanline as the * loop counter, so that we don't have to keep track ourselves. */ while (cinfo.output_scanline < cinfo.output_height) { l_start = cinfo.output_scanline; l_end = cinfo.output_scanline + l_tile_height; l_end = MIN (l_end, cinfo.output_height); l_scanlines = l_end - l_start; for (l_idx = 0; l_idx < l_scanlines; l_idx++) { jpeg_read_scanlines (&cinfo, (JSAMPARRAY) &l_rowbuf[l_idx], 1); } gimp_pixel_rgn_get_rect (&l_pixel_rgn, l_dstbuf, 0, l_start, l_drawable->width, l_scanlines); /* copy the loaded jpeg data (from buf) to the layers alpha channel data */ l_idx = l_tile_height * l_drawable->width; l_buf_ptr = l_buf; l_dstbuf_ptr = l_dstbuf; while(l_idx--) { l_dstbuf_ptr += l_alpha_offset; *l_dstbuf_ptr++ = *l_buf_ptr++; } gimp_pixel_rgn_set_rect (&l_pixel_rgn, l_dstbuf, 0, l_start, l_drawable->width, l_scanlines); gimp_progress_update ((double) cinfo.output_scanline / (double) cinfo.output_height); } /* Step 7: Finish decompression */ jpeg_finish_decompress (&cinfo); /* We can ignore the return value since suspension is not possible * with the stdio data source. */ /* Step 8: Release JPEG decompression object */ /* This is an important step since it will release a good deal of memory. */ jpeg_destroy_decompress (&cinfo); /* free up the temporary buffers */ g_free (l_rowbuf); g_free (l_buf); g_free (l_dstbuf); /* After finish_decompress, we can close the input file. * Here we postpone it until after no more JPEG errors are possible, * so as to simplify the setjmp error logic above. (Actually, I don't * think that jpeg_destroy can do an error exit, but why assume anything...) */ fclose (infile); /* At this point you may want to check to see whether any corrupt-data * warnings occurred (test whether jerr.num_warnings is nonzero). */ return (0); /* OK */ } /* xjpg_load_layer_alpha */
static void migrate_buddy_icon(PurpleBlistNode *node, const char *setting_name, const char *dirname, const char *filename) { char *path; if (filename[0] != '/') { path = g_build_filename(dirname, filename, NULL); if (g_file_test(path, G_FILE_TEST_EXISTS)) { g_free(path); return; } g_free(path); path = g_build_filename(old_icons_dir, filename, NULL); } else path = g_strdup(filename); if (g_file_test(path, G_FILE_TEST_EXISTS)) { guchar *icon_data; size_t icon_len; FILE *file; char *new_filename; if (!read_icon_file(path, &icon_data, &icon_len)) { g_free(path); delete_buddy_icon_settings(node, setting_name); return; } if (icon_data == NULL || icon_len <= 0) { /* This really applies to the icon_len check. * icon_data should never be NULL if * read_icon_file() returns TRUE. */ purple_debug_error("buddyicon", "Empty buddy icon file: %s\n", path); delete_buddy_icon_settings(node, setting_name); g_free(path); return; } g_free(path); new_filename = purple_util_get_image_filename(icon_data, icon_len); if (new_filename == NULL) { purple_debug_error("buddyicon", "New icon filename is NULL. This should never happen! " "The old filename was: %s\n", path); delete_buddy_icon_settings(node, setting_name); g_return_if_reached(); } path = g_build_filename(dirname, new_filename, NULL); if ((file = g_fopen(path, "wb")) != NULL) { if (!fwrite(icon_data, icon_len, 1, file)) { purple_debug_error("buddyicon", "Error writing %s: %s\n", path, g_strerror(errno)); } else purple_debug_info("buddyicon", "Wrote migrated cache file: %s\n", path); fclose(file); } else { purple_debug_error("buddyicon", "Unable to create file %s: %s\n", path, g_strerror(errno)); g_free(new_filename); g_free(path); delete_buddy_icon_settings(node, setting_name); return; } g_free(path); purple_blist_node_set_string(node, setting_name, new_filename); ref_filename(new_filename); g_free(new_filename); if (purple_strequal(setting_name, "buddy_icon")) { const char *hash; hash = purple_blist_node_get_string(node, "avatar_hash"); if (hash != NULL) { purple_blist_node_set_string(node, "icon_checksum", hash); purple_blist_node_remove_setting(node, "avatar_hash"); } else { PurpleAccount *account = purple_buddy_get_account((PurpleBuddy *)node); const char *prpl_id = purple_account_get_protocol_id(account); if (g_str_equal(prpl_id, "prpl-yahoo") || g_str_equal(prpl_id, "prpl-yahoojp")) { int checksum = purple_blist_node_get_int(node, "icon_checksum"); if (checksum != 0) { char *checksum_str = g_strdup_printf("%i", checksum); purple_blist_node_remove_setting(node, "icon_checksum"); purple_blist_node_set_string(node, "icon_checksum", checksum_str); g_free(checksum_str); } } } } } else { purple_debug_error("buddyicon", "Old icon file doesn't exist: %s\n", path); delete_buddy_icon_settings(node, setting_name); g_free(path); } }
gboolean tanloadfigtab (char *name){ FILE *hand=NULL; int i,j; gboolean succes; int newfigtabsize; tanfigure *newfigtab=NULL,*figs; int lres; lres=0; if ( (hand = g_fopen(name, "r"))!=NULL && fscanf(hand, "gTans v1.0 %d \n", &newfigtabsize)==1 && (newfigtab = (tanfigure *)g_malloc(sizeof(tanfigure)*newfigtabsize))!=NULL ){ lres=1; figs = newfigtab; for (i = 0; i<newfigtabsize; i++){ *figs = figuredebut; figs->zoom = tanreadfloat(hand, &lres); figs->distmax = tanreadfloat(hand, &lres); SPESC(hand,"%d \n", &figs->drotmax); /*fscanf(hand,"%le %le %d \n",&figs->zoom,&figs->distmax,&figs->drotmax);*/ for (j=0; j<PIECENBR; j++){ SPESC(hand,"p %d", &figs->piecepos[j].type); SPESC(hand,"%d", &figs->piecepos[j].flipped); figs->piecepos[j].posx = tanreadfloat(hand, &lres); figs->piecepos[j].posy = tanreadfloat(hand, &lres); SPESC(hand,"%d \n", &figs->piecepos[j].rot); /*fscanf(hand,"%d %d %le %le %d \n",&figs->piecepos[j].type,&figs->piecepos[j].flipped, &figs->piecepos[j].posx,&figs->piecepos[j].posy,&figs->piecepos[j].rot);*/ } figs++; } } else g_warning("Opening file %s fails",name); if (hand!=NULL) fclose(hand); succes=FALSE; if (lres==1){ succes=TRUE; if(figtab!=NULL) g_free(figtab); figtab=newfigtab; figtabsize=newfigtabsize; actual_figure = 0; tansetnewfigurepart1(actual_figure); tansetnewfigurepart2(); //tanspinsetvalmax(figtabsize-1); } if (succes || figfilename==NULL) tanallocname(&figfilename, name); return(succes); }
static void pop3_get_uidl_table(PrefsAccount *ac_prefs, Pop3Session *session) { GHashTable *table; GHashTable *partial_recv_table; gchar *path; FILE *fp; gchar buf[POPBUFSIZE]; gchar uidl[POPBUFSIZE]; time_t recv_time; time_t now; gint partial_recv; gchar *sanitized_uid = g_strdup(ac_prefs->userid); subst_for_filename(sanitized_uid); table = g_hash_table_new(g_str_hash, g_str_equal); partial_recv_table = g_hash_table_new(g_str_hash, g_str_equal); path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "uidl", G_DIR_SEPARATOR_S, ac_prefs->recv_server, "-", sanitized_uid, NULL); g_free(sanitized_uid); if ((fp = g_fopen(path, "rb")) == NULL) { if (ENOENT != errno) FILE_OP_ERROR(path, "fopen"); g_free(path); path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "uidl-", ac_prefs->recv_server, "-", ac_prefs->userid, NULL); if ((fp = g_fopen(path, "rb")) == NULL) { if (ENOENT != errno) FILE_OP_ERROR(path, "fopen"); g_free(path); session->uidl_table = table; session->partial_recv_table = partial_recv_table; return; } } g_free(path); now = time(NULL); while (fgets(buf, sizeof(buf), fp) != NULL) { gchar tmp[POPBUFSIZE]; strretchomp(buf); recv_time = RECV_TIME_NONE; partial_recv = POP3_TOTALLY_RECEIVED; if (sscanf(buf, "%s\t%ld\t%s", uidl, (long int *) &recv_time, tmp) < 3) { if (sscanf(buf, "%s\t%ld", uidl, (long int *) &recv_time) != 2) { if (sscanf(buf, "%s", uidl) != 1) continue; else { recv_time = now; strcpy(tmp, "0"); } } else { strcpy(tmp, "0"); } } if (recv_time == RECV_TIME_NONE) recv_time = RECV_TIME_RECEIVED; g_hash_table_insert(table, g_strdup(uidl), GINT_TO_POINTER(recv_time)); if (strlen(tmp) == 1) partial_recv = atoi(tmp); /* totally received ?*/ else partial_recv = POP3_MUST_COMPLETE_RECV; g_hash_table_insert(partial_recv_table, g_strdup(uidl), GINT_TO_POINTER(partial_recv)); } fclose(fp); session->uidl_table = table; session->partial_recv_table = partial_recv_table; return; }
static gboolean save_image (const gchar *filename, GeglBuffer *buffer, GError **error) { const Babl *format = babl_format ("R'G'B'A u8"); gint row, col, cols, rows, x, y; gint colcount, colspan, rowspan; gint *palloc; guchar *buf, *buf2; gchar *width, *height; FILE *fp; cols = gegl_buffer_get_width (buffer); rows = gegl_buffer_get_height (buffer); fp = g_fopen (filename, "w"); if (! fp) { g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno), _("Could not open '%s' for writing: %s"), gimp_filename_to_utf8 (filename), g_strerror (errno)); return FALSE; } palloc = g_new (int, rows * cols); if (gtmvals.fulldoc) { fprintf (fp, "<HTML>\n<HEAD><TITLE>%s</TITLE></HEAD>\n<BODY>\n", filename); fprintf (fp, "<H1>%s</H1>\n", filename); } fprintf (fp, "<TABLE BORDER=%d CELLPADDING=%d CELLSPACING=%d>\n", gtmvals.border, gtmvals.cellpadding, gtmvals.cellspacing); if (gtmvals.caption) fprintf (fp, "<CAPTION>%s</CAPTION>\n", gtmvals.captiontxt); gimp_progress_init_printf (_("Saving '%s'"), gimp_filename_to_utf8 (filename)); buf = g_newa (guchar, babl_format_get_bytes_per_pixel (format)); buf2 = g_newa (guchar, babl_format_get_bytes_per_pixel (format)); width = height = NULL; if (strcmp (gtmvals.clwidth, "") != 0) { width = g_strdup_printf (" WIDTH=\"%s\"", gtmvals.clwidth); } if (strcmp (gtmvals.clheight, "") != 0) { height = g_strdup_printf (" HEIGHT=\"%s\" ", gtmvals.clheight); } if (! width) width = g_strdup (" "); if (! height) height = g_strdup (" "); /* Initialize array to hold ROWSPAN and COLSPAN cell allocation table */ for (row = 0; row < rows; row++) for (col = 0; col < cols; col++) palloc[cols * row + col] = 1; colspan = 0; rowspan = 0; for (y = 0; y < rows; y++) { fprintf (fp," <TR>\n"); for (x = 0; x < cols; x++) { gegl_buffer_sample (buffer, x, y, NULL, buf, format, GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE); /* Determine ROWSPAN and COLSPAN */ if (gtmvals.spantags) { col = x; row = y; colcount = 0; colspan = 0; rowspan = 0; gegl_buffer_sample (buffer, col, row, NULL, buf2, format, GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE); while (color_comp (buf, buf2) && palloc[cols * row + col] == 1 && row < rows) { while (color_comp (buf, buf2) && palloc[cols * row + col] == 1 && col < cols) { colcount++; col++; gegl_buffer_sample (buffer, col, row, NULL, buf2, format, GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE); } if (colcount != 0) { row++; rowspan++; } if (colcount < colspan || colspan == 0) colspan = colcount; col = x; colcount = 0; gegl_buffer_sample (buffer, col, row, NULL, buf2, format, GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE); } if (colspan > 1 || rowspan > 1) { for (row = 0; row < rowspan; row++) for (col = 0; col < colspan; col++) palloc[cols * (row + y) + (col + x)] = 0; palloc[cols * y + x] = 2; } } if (palloc[cols * y + x] == 1) fprintf (fp, " <TD%s%sBGCOLOR=#%02x%02x%02x>", width, height, buf[0], buf[1], buf[2]); if (palloc[cols * y + x] == 2) fprintf (fp," <TD ROWSPAN=\"%d\" COLSPAN=\"%d\"%s%sBGCOLOR=#%02x%02x%02x>", rowspan, colspan, width, height, buf[0], buf[1], buf[2]); if (palloc[cols * y + x] != 0) { if (gtmvals.tdcomp) fprintf (fp, "%s</TD>\n", gtmvals.cellcontent); else fprintf (fp, "\n %s\n </TD>\n", gtmvals.cellcontent); } } fprintf (fp," </TR>\n"); gimp_progress_update ((double) y / (double) rows); } gimp_progress_update (1.0); if (gtmvals.fulldoc) fprintf (fp, "</TABLE></BODY></HTML>\n"); else fprintf (fp, "</TABLE>\n"); fclose (fp); g_free (width); g_free (height); g_free (palloc); return TRUE; }
gint pop3_write_uidl_list(Pop3Session *session) { gchar *path, *tmp_path; FILE *fp; Pop3MsgInfo *msg; gint n; gchar *sanitized_uid = g_strdup(session->ac_prefs->userid); subst_for_filename(sanitized_uid); if (!session->uidl_is_valid) { g_free(sanitized_uid); return 0; } path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "uidl", G_DIR_SEPARATOR_S, session->ac_prefs->recv_server, "-", sanitized_uid, NULL); tmp_path = g_strconcat(path, ".tmp", NULL); g_free(sanitized_uid); if ((fp = g_fopen(tmp_path, "wb")) == NULL) { FILE_OP_ERROR(tmp_path, "fopen"); goto err_write; } for (n = 1; n <= session->count; n++) { msg = &session->msg[n]; if (msg->uidl && msg->received && (!msg->deleted || session->state != POP3_DONE)) TRY(fprintf(fp, "%s\t%ld\t%d\n", msg->uidl, (long int) msg->recv_time, msg->partial_recv) > 0); } if (fclose(fp) == EOF) { FILE_OP_ERROR(tmp_path, "fclose"); fp = NULL; goto err_write; } fp = NULL; #ifdef G_OS_WIN32 claws_unlink(path); #endif if (g_rename(tmp_path, path) < 0) { FILE_OP_ERROR(path, "rename"); goto err_write; } g_free(path); g_free(tmp_path); return 0; err_write: if (fp) fclose(fp); g_free(path); g_free(tmp_path); return -1; }
void convert(const char *filename, print_info_t print_info) { struct stat stats; if (g_stat (filename, &stats) == -1) { print_info("File not exist!\n"); return; } gchar *basefilename = g_path_get_basename(filename); gchar *ch = strrchr(basefilename, '.'); if (ch) *ch = '\0'; gchar *dirname = g_path_get_dirname(filename); FILE *tabfile; tabfile = g_fopen(filename,"r"); gchar *buffer = (gchar *)g_malloc (stats.st_size + 1); size_t readsize = fread (buffer, 1, stats.st_size, tabfile); fclose (tabfile); buffer[readsize] = '\0'; GArray *array = g_array_sized_new(FALSE,FALSE, sizeof(struct _worditem),20000); gchar *p, *p1, *p2; p = buffer; if ((guchar)*p==0xEF && (guchar)*(p+1)==0xBB && (guchar)*(p+2)==0xBF) // UTF-8 order characters. p+=3; struct _worditem worditem; glong linenum=1; while (1) { if (*p == '\0') { print_info("Convert over.\n"); break; } p1 = strchr(p,'\n'); if (!p1) { print_info("Error, no new line at the end\n"); return; } *p1 = '\0'; p1++; p2 = strchr(p,'='); if (!p2) { gchar *str = g_strdup_printf("Warning, no separater, %ld\n", linenum); print_info(str); g_free(str); p= p1; linenum++; continue; } *p2 = '\0'; p2++; worditem.word = p; worditem.definition = p2; my_strstrip(worditem.definition, linenum, print_info); g_strstrip(worditem.word); g_strstrip(worditem.definition); if (!worditem.word[0]) { gchar *str = g_strdup_printf("Warning: line %ld, bad word!\n", linenum); print_info(str); g_free(str); p= p1; linenum++; continue; } if (!worditem.definition[0]) { gchar *str = g_strdup_printf("Warning: line %ld, bad definition!\n", linenum); print_info(str); g_free(str); p= p1; linenum++; continue; } g_array_append_val(array, worditem); p= p1; linenum++; } g_array_sort(array,comparefunc); gchar ifofilename[256]; gchar idxfilename[256]; gchar dicfilename[256]; sprintf(ifofilename, "%s" G_DIR_SEPARATOR_S "%s.ifo", dirname, basefilename); sprintf(idxfilename, "%s" G_DIR_SEPARATOR_S "%s.idx", dirname, basefilename); sprintf(dicfilename, "%s" G_DIR_SEPARATOR_S "%s.dict", dirname, basefilename); FILE *ifofile = g_fopen(ifofilename,"wb"); if (!ifofile) { print_info("Write to ifo file failed!\n"); return; } FILE *idxfile = g_fopen(idxfilename,"wb"); if (!idxfile) { print_info("Write to idx file failed!\n"); return; } FILE *dicfile = g_fopen(dicfilename,"wb"); if (!dicfile) { print_info("Write to dict file failed!\n"); return; } guint32 offset_old; guint32 tmpglong; struct _worditem *pworditem; gint definition_len; gulong i; for (i=0; i< array->len; i++) { offset_old = ftell(dicfile); pworditem = &g_array_index(array, struct _worditem, i); definition_len = strlen(pworditem->definition); fwrite(pworditem->definition, 1 ,definition_len,dicfile); fwrite(pworditem->word,sizeof(gchar),strlen(pworditem->word)+1,idxfile); tmpglong = g_htonl(offset_old); fwrite(&(tmpglong),sizeof(guint32),1,idxfile); tmpglong = g_htonl(definition_len); fwrite(&(tmpglong),sizeof(guint32),1,idxfile); } fclose(idxfile); fclose(dicfile); gchar *str = g_strdup_printf("%s wordcount: %d\n", basefilename, array->len); print_info(str); g_free(str); #ifndef _WIN32 gchar command[256]; sprintf(command, "dictzip %s", dicfilename); system(command); #endif g_stat(idxfilename, &stats); fprintf(ifofile, "StarDict's dict ifo file\nversion=2.4.2\nwordcount=%d\nidxfilesize=%ld\nbookname=%s\nsametypesequence=m\n", array->len, stats.st_size, basefilename); fclose(ifofile); g_free(buffer); g_array_free(array,TRUE); g_free(basefilename); g_free(dirname); }
GimpPDBStatusType ico_save_image (const gchar *filename, gint32 image, gint32 run_mode, GError **error) { FILE *fp; gint i; gint width, height; IcoSaveInfo info; IcoFileHeader header; IcoFileEntry *entries; gboolean saved; D(("*** Saving Microsoft icon file %s\n", filename)); ico_save_init (image, &info); if (run_mode == GIMP_RUN_INTERACTIVE) { /* Allow user to override default values */ if ( !ico_save_dialog (image, &info)) return GIMP_PDB_CANCEL; } gimp_progress_init_printf (_("Saving '%s'"), gimp_filename_to_utf8 (filename)); if (! (fp = g_fopen (filename, "wb"))) { g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno), _("Could not open '%s' for writing: %s"), gimp_filename_to_utf8 (filename), g_strerror (errno)); return GIMP_PDB_EXECUTION_ERROR; } header.reserved = 0; header.resource_type = 1; header.icon_count = info.num_icons; if ( !ico_write_int16 (fp, &header.reserved, 1) || !ico_write_int16 (fp, &header.resource_type, 1) || !ico_write_int16 (fp, &header.icon_count, 1) ) { ico_save_info_free (&info); fclose (fp); return GIMP_PDB_EXECUTION_ERROR; } entries = g_new0 (IcoFileEntry, info.num_icons); if (fwrite (entries, sizeof (IcoFileEntry), info.num_icons, fp) <= 0) { ico_save_info_free (&info); g_free (entries); fclose (fp); return GIMP_PDB_EXECUTION_ERROR; } for (i = 0; i < info.num_icons; i++) { gimp_progress_update ((gdouble)i / (gdouble)info.num_icons); width = gimp_drawable_width (info.layers[i]); height = gimp_drawable_height (info.layers[i]); if (width <= 255 && height <= 255) { entries[i].width = width; entries[i].height = height; } else { entries[i].width = 0; entries[i].height = 0; } if ( info.depths[i] <= 8 ) entries[i].num_colors = 1 << info.depths[i]; else entries[i].num_colors = 0; entries[i].reserved = 0; entries[i].planes = 1; entries[i].bpp = info.depths[i]; entries[i].offset = ftell (fp); if (info.compress[i]) saved = ico_write_png (fp, info.layers[i], info.depths[i]); else saved = ico_write_icon (fp, info.layers[i], info.depths[i]); if (!saved) { ico_save_info_free (&info); fclose (fp); return GIMP_PDB_EXECUTION_ERROR; } entries[i].size = ftell (fp) - entries[i].offset; } for (i = 0; i < info.num_icons; i++) { entries[i].planes = GUINT16_TO_LE (entries[i].planes); entries[i].bpp = GUINT16_TO_LE (entries[i].bpp); entries[i].size = GUINT32_TO_LE (entries[i].size); entries[i].offset = GUINT32_TO_LE (entries[i].offset); } if (fseek (fp, sizeof(IcoFileHeader), SEEK_SET) < 0 || fwrite (entries, sizeof (IcoFileEntry), info.num_icons, fp) <= 0) { ico_save_info_free (&info); fclose (fp); return GIMP_PDB_EXECUTION_ERROR; } gimp_progress_update (1.0); ico_save_info_free (&info); fclose (fp); g_free (entries); return GIMP_PDB_SUCCESS; }
int read_header(const char *filename, dt_imageio_png_t *png) { png->f = g_fopen(filename, "rb"); if(!png->f) return 1; #define NUM_BYTES_CHECK (8) png_byte dat[NUM_BYTES_CHECK]; size_t cnt = fread(dat, 1, NUM_BYTES_CHECK, png->f); if(cnt != NUM_BYTES_CHECK || png_sig_cmp(dat, (png_size_t)0, NUM_BYTES_CHECK)) { fclose(png->f); return 1; } png->png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if(!png->png_ptr) { fclose(png->f); return 1; } png->info_ptr = png_create_info_struct(png->png_ptr); if(!png->info_ptr) { fclose(png->f); png_destroy_read_struct(&png->png_ptr, NULL, NULL); return 1; } if(setjmp(png_jmpbuf(png->png_ptr))) { fclose(png->f); png_destroy_read_struct(&png->png_ptr, &png->info_ptr, NULL); return 1; } png_init_io(png->png_ptr, png->f); // we checked some bytes png_set_sig_bytes(png->png_ptr, NUM_BYTES_CHECK); // image info png_read_info(png->png_ptr, png->info_ptr); png->bit_depth = png_get_bit_depth(png->png_ptr, png->info_ptr); png->color_type = png_get_color_type(png->png_ptr, png->info_ptr); // image input transformations // palette => rgb if(png->color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png->png_ptr); // 1, 2, 4 bit => 8 bit if(png->color_type == PNG_COLOR_TYPE_GRAY && png->bit_depth < 8) { png_set_expand_gray_1_2_4_to_8(png->png_ptr); png->bit_depth = 8; } // strip alpha channel if(png->color_type & PNG_COLOR_MASK_ALPHA) png_set_strip_alpha(png->png_ptr); // grayscale => rgb if(png->color_type == PNG_COLOR_TYPE_GRAY || png->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png->png_ptr); // reflect changes png_read_update_info(png->png_ptr, png->info_ptr); // png->bytespp = 3*bit_depth/8; png->width = png_get_image_width(png->png_ptr, png->info_ptr); png->height = png_get_image_height(png->png_ptr, png->info_ptr); #undef NUM_BYTES_CHECK return 0; }
static void draw_image(DiaRenderer *self, Point *point, real width, real height, DiaImage *image) { WpgRenderer *renderer = WPG_RENDERER (self); WPGBitmap2 bmp; guint8 * pDiaImg = NULL, * pOut = NULL, * pIn = NULL, * p = NULL; guint8 b_1 = 0, b = 0, cnt; int x, y, stride; bmp.Angle = 0; bmp.Left = SCX(point->x); bmp.Top = SCY(-point->y); bmp.Right = SCX(point->x + width); bmp.Bottom = SCY(-point->y - height); bmp.Width = dia_image_width(image); bmp.Height = dia_image_height(image); bmp.Depth = 8; /* maximum allowed */ bmp.Xdpi = 72; /* ??? */ bmp.Ydpi = 72; DIAG_NOTE(g_message("draw_image %fx%f [%d,%d] @%f,%f", width, height, bmp.Width, bmp.Height, point->x, point->y)); pDiaImg = dia_image_rgb_data(image); if (!pDiaImg) { dia_context_add_message(renderer->ctx, _("Not enough memory for image drawing.")); return; } stride = dia_image_rowstride(image); pOut = g_new(guint8, bmp.Width * bmp.Height * 2); /* space for worst case RLE */ p = pOut; for (y = 0; y < bmp.Height; y++) { /* from top to bottom line */ pIn = pDiaImg + stride * y; cnt = 0; /* reset with every line */ for (x = 0; x < bmp.Width; x ++) { /* simple color reduction to default palette */ b = (((CC_LEN - 1) * pIn[0]) / 255) /* red */ + (((CC_LEN - 1) * pIn[1]) / 255) * CC_LEN /* green */ + (((CC_LEN - 1) * pIn[2]) / 255) * CC_LEN * CC_LEN /* blue */ + WPG_NUM_DEF_COLORS; pIn += 3; /* increase read pointer */ if (cnt > 0) { if ((b == b_1) && (cnt < 127)) cnt++; /* increase counter*/ else { *p++ = (cnt | 0x80); /* write run length and value */ *p++ = b_1; cnt = 1; /* reset */ b_1 = b; } } else { b_1 = b; cnt = 1; } } *p++ = (cnt | 0x80); /* write last value(s) */ *p++ = b; } DIAG_NOTE(g_message( "Width x Height: %d RLE: %d", bmp.Width * bmp.Height, p - pOut)); if ((p - pOut) > 32767) { dia_context_add_message(renderer->ctx, "Bitmap size exceeds blocksize. Ignored."); } else { WriteRecHead(renderer, WPG_BITMAP2, sizeof(WPGBitmap2) + (p - pOut)); #if 0 fwrite(&bmp, sizeof(WPGBitmap2), 1, renderer->file); #else g_assert(20 == sizeof(WPGBitmap2)); fwrite(&bmp, sizeof(guint16), sizeof(WPGBitmap2) / sizeof(guint16), renderer->file); #endif fwrite(pOut, sizeof(guint8), p - pOut, renderer->file); } #if 0 /* RLE diagnose */ { FILE* f; int i, j; f = g_fopen("c:\\temp\\wpg_bmp.raw", "wb"); j = p - pOut; for (i = 0; i < j; i+=2) { for (x = 0; x < (pOut[i] & 0x7F); x++) fwrite(&pOut[i+1], 1, 1, f); } fclose(f); } #endif g_free(pDiaImg); g_free(pOut); }
int sr_session_save(const char *filename) { GSList *l, *p, *d; FILE *meta; struct sr_device *device; struct sr_probe *probe; struct sr_datastore *ds; struct zip *zipfile; struct zip_source *versrc, *metasrc, *logicsrc; int bufcnt, devcnt, tmpfile, ret, error, probecnt; uint64_t samplerate; char version[1], rawname[16], metafile[32], *buf, *s; /* Quietly delete it first, libzip wants replace ops otherwise. */ unlink(filename); if (!(zipfile = zip_open(filename, ZIP_CREATE, &error))) return SR_ERR; /* "version" */ version[0] = '1'; if (!(versrc = zip_source_buffer(zipfile, version, 1, 0))) return SR_ERR; if (zip_add(zipfile, "version", versrc) == -1) { sr_info("error saving version into zipfile: %s", zip_strerror(zipfile)); return SR_ERR; } /* init "metadata" */ strcpy(metafile, "sigrok-meta-XXXXXX"); if ((tmpfile = g_mkstemp(metafile)) == -1) return SR_ERR; close(tmpfile); meta = g_fopen(metafile, "wb"); fprintf(meta, "[global]\n"); fprintf(meta, "sigrok version = %s\n", PACKAGE_VERSION); /* TODO: save protocol decoders used */ /* all datastores in all devices */ devcnt = 1; for (l = session->devices; l; l = l->next) { device = l->data; /* metadata */ fprintf(meta, "[device %d]\n", devcnt); if (device->plugin) fprintf(meta, "driver = %s\n", device->plugin->name); ds = device->datastore; if (ds) { /* metadata */ fprintf(meta, "capturefile = logic-%d\n", devcnt); fprintf(meta, "unitsize = %d\n", ds->ds_unitsize); fprintf(meta, "total probes = %d\n", g_slist_length(device->probes)); if (sr_device_has_hwcap(device, SR_HWCAP_SAMPLERATE)) { samplerate = *((uint64_t *) device->plugin->get_device_info( device->plugin_index, SR_DI_CUR_SAMPLERATE)); s = sr_samplerate_string(samplerate); fprintf(meta, "samplerate = %s\n", s); free(s); } probecnt = 1; for (p = device->probes; p; p = p->next) { probe = p->data; if (probe->enabled) { if (probe->name) fprintf(meta, "probe%d = %s\n", probecnt, probe->name); if (probe->trigger) fprintf(meta, " trigger%d = %s\n", probecnt, probe->trigger); probecnt++; } } /* dump datastore into logic-n */ buf = malloc(ds->num_units * ds->ds_unitsize + DATASTORE_CHUNKSIZE); bufcnt = 0; for (d = ds->chunklist; d; d = d->next) { memcpy(buf + bufcnt, d->data, DATASTORE_CHUNKSIZE); bufcnt += DATASTORE_CHUNKSIZE; } if (!(logicsrc = zip_source_buffer(zipfile, buf, ds->num_units * ds->ds_unitsize, TRUE))) return SR_ERR; snprintf(rawname, 15, "logic-%d", devcnt); if (zip_add(zipfile, rawname, logicsrc) == -1) return SR_ERR; } devcnt++; } fclose(meta); if (!(metasrc = zip_source_file(zipfile, metafile, 0, -1))) return SR_ERR; if (zip_add(zipfile, "metadata", metasrc) == -1) return SR_ERR; if ((ret = zip_close(zipfile)) == -1) { sr_info("error saving zipfile: %s", zip_strerror(zipfile)); return SR_ERR; } unlink(metafile); return SR_OK; }
GSList *news_get_group_list(Folder *folder) { gchar *path, *filename; FILE *fp; GSList *list = NULL; GSList *last = NULL; gchar buf[BUFFSIZE]; cm_return_val_if_fail(folder != NULL, NULL); cm_return_val_if_fail(FOLDER_CLASS(folder) == &news_class, NULL); path = folder_item_get_path(FOLDER_ITEM(folder->node->data)); if (!is_dir_exist(path)) make_dir_hier(path); filename = g_strconcat(path, G_DIR_SEPARATOR_S, NEWSGROUP_LIST, NULL); g_free(path); if ((fp = g_fopen(filename, "rb")) == NULL) { NewsSession *session; gint ok; clist *grouplist = NULL; clistiter *cur; fp = g_fopen(filename, "wb"); if (!fp) { g_free(filename); return NULL; } session = news_session_get(folder); if (!session) { fclose(fp); g_free(filename); return NULL; } ok = nntp_threaded_list(folder, &grouplist); if (ok != NEWSNNTP_NO_ERROR) { if (ok == NEWSNNTP_ERROR_STREAM) { session_destroy(SESSION(session)); REMOTE_FOLDER(folder)->session = NULL; } fclose(fp); g_free(filename); return NULL; } if (grouplist) { for (cur = clist_begin(grouplist); cur; cur = clist_next(cur)) { struct newsnntp_group_info *info = (struct newsnntp_group_info *) clist_content(cur); if (fprintf(fp, "%s %d %d %c\n", info->grp_name, info->grp_last, info->grp_first, info->grp_type) < 0) { log_error(LOG_PROTOCOL, ("Can't write newsgroup list\n")); session_destroy(SESSION(session)); REMOTE_FOLDER(folder)->session = NULL; fclose(fp); g_free(filename); newsnntp_list_free(grouplist); return NULL; } } newsnntp_list_free(grouplist); } if (fclose(fp) == EOF) { log_error(LOG_PROTOCOL, ("Can't write newsgroup list\n")); session_destroy(SESSION(session)); REMOTE_FOLDER(folder)->session = NULL; g_free(filename); return NULL; } if ((fp = g_fopen(filename, "rb")) == NULL) { FILE_OP_ERROR(filename, "fopen"); g_free(filename); return NULL; } } while (fgets(buf, sizeof(buf), fp) != NULL) { gchar *p = buf; gchar *name; gint last_num; gint first_num; gchar type; NewsGroupInfo *ginfo; p = strchr(p, ' '); if (!p) continue; *p = '\0'; p++; name = buf; if (sscanf(p, "%d %d %c", &last_num, &first_num, &type) < 3) continue; ginfo = news_group_info_new(name, first_num, last_num, type); if (!last) last = list = g_slist_append(NULL, ginfo); else { last = g_slist_append(last, ginfo); last = last->next; } } fclose(fp); g_free(filename); list = g_slist_sort(list, (GCompareFunc)news_group_info_compare); return list; }
/**** log_score Inputs: 'progname' - the program to log a score for 'level' - the freeform level identifier 'username' - the username that this score is logged under 'score' - the game score 'ordering' - whether lower scores are better. Outputs: 'retval' - Whether the score got onto the highscore list Description: Loads all the existing scores into the 'scores' list. Goes through and finds out whether there's a place for the new score on the high-score list, and if so, inserts it. Writes out the new high-score list. */ static gint log_score (const gchar * progname, const gchar * level, gchar * username, gfloat score, gboolean ordering) { FILE *infile; FILE *outfile; gchar buf[512], *buf2; GList *scores = NULL, *anode; gchar *game_score_file; gfloat ascore; struct ascore_t *anitem, *curscore; int i; gint retval = 1; gint pos; game_score_file = gnome_get_score_file_name (progname, level); infile = g_fopen (game_score_file, "r"); if (infile) { while(fgets(buf, sizeof(buf), infile)) { long ltime; i = strlen (buf) - 1; /* Chomp */ while (g_ascii_isspace (buf[i])) buf[i--] = '\0'; { char *tokp; if((buf2 = strtok_r (buf, " ", &tokp)) == NULL) break; ascore = g_ascii_strtod (buf2, NULL); if((buf2 = strtok_r (NULL, " ", &tokp)) == NULL) break; ltime = atoi (buf2); if((buf2 = strtok_r (NULL, "\n", &tokp)) == NULL) break; } anitem = g_new(struct ascore_t, 1); anitem->score = ascore; anitem->username = g_strdup (buf2); anitem->scoretime = (time_t)ltime; scores = g_list_append (scores, (gpointer) anitem); } fclose (infile); } anitem = g_new(struct ascore_t, 1); anitem->score = score; anitem->username = g_strdup (username); anitem->scoretime = time (NULL); for (pos = 0, anode = scores; pos < NSCORES && anode; pos++, anode = anode->next) { curscore = anode->data; if (ordering) { if (curscore->score < anitem->score) break; } else { if (curscore->score > anitem->score) break; } } if (pos < NSCORES) { scores = g_list_insert (scores, anitem, pos); if ((anode = g_list_nth (scores, NSCORES))) { free_ascore (anode->data); scores = g_list_remove_link (scores, g_list_nth (scores, NSCORES)); } retval = pos + 1; } else retval = 0; /* we dont create the file; it must already exist */ outfile = g_fopen (game_score_file, "r+"); #ifndef G_OS_WIN32 ftruncate (fileno (outfile), 0); #else _chsize (fileno (outfile), 0); #endif if (outfile) { g_list_foreach (scores, (GFunc) print_ascore, outfile); fclose (outfile); } else perror (game_score_file); g_free (game_score_file); g_list_foreach (scores, (GFunc) free_ascore, NULL); g_list_free (scores); return retval; }
extern void CommandExportPositionText(char *sz) { FILE *pf; int fHistory; moverecord *pmr; int iMove; GString *gsz; sz = NextToken(&sz); if (ms.gs == GAME_NONE) { outputl(_("No game in progress (type `new game' to start one).")); return; } if (!sz || !*sz) { outputl(_("You must specify a file to export to (see `help export " "position text').")); return; } pmr = get_current_moverecord(&fHistory); if (!confirmOverwrite(sz, fConfirmSave)) return; if (!strcmp(sz, "-")) pf = stdout; else if ((pf = g_fopen(sz, "w")) == 0) { outputerr(sz); return; } gsz = g_string_new(NULL); TextPrologue(gsz, &ms, getGameNumber(plGame)); fputs(gsz->str, pf); g_string_free(gsz, TRUE); if (exsExport.fIncludeMatchInfo) TextMatchInfo(pf, &mi); if (fHistory) iMove = getMoveNumber(plGame, pmr) - 1; else if (plLastMove) iMove = getMoveNumber(plGame, plLastMove->p); else iMove = -1; gsz = g_string_new(NULL); TextBoardHeader(gsz, &ms, getGameNumber(plGame), iMove); fputs(gsz->str, pf); g_string_free(gsz, TRUE); printTextBoard(pf, &ms); if (pmr) { gsz = g_string_new(NULL); TextAnalysis(gsz, &ms, pmr); fputs(gsz->str, pf); g_string_free(gsz, TRUE); if (exsExport.fIncludeAnnotation) TextPrintComment(pf, pmr); } TextEpilogue(pf, &ms); if (pf != stdout) fclose(pf); setDefaultFileName(sz); }
/* Loads the global tag list from the specified file. The global tag list should have been first created using tm_workspace_create_global_tags(). @param tags_file The file containing global tags. @return TRUE on success, FALSE on failure. @see tm_workspace_create_global_tags() */ gboolean tm_workspace_load_global_tags(const char *tags_file, gint mode) { guchar buf[BUFSIZ]; FILE *fp; GPtrArray *file_tags, *new_tags; TMTag *tag; TMFileFormat format = TM_FILE_FORMAT_TAGMANAGER; if (NULL == (fp = g_fopen(tags_file, "r"))) return FALSE; if ((NULL == fgets((gchar*) buf, BUFSIZ, fp)) || ('\0' == *buf)) { fclose(fp); return FALSE; /* early out on error */ } else { /* We read the first line for the format specification. */ if (buf[0] == '#' && strstr((gchar*) buf, "format=pipe") != NULL) format = TM_FILE_FORMAT_PIPE; else if (buf[0] == '#' && strstr((gchar*) buf, "format=tagmanager") != NULL) format = TM_FILE_FORMAT_TAGMANAGER; else if (buf[0] == '#' && strstr((gchar*) buf, "format=ctags") != NULL) format = TM_FILE_FORMAT_CTAGS; else if (strncmp((gchar*) buf, "!_TAG_", 6) == 0) format = TM_FILE_FORMAT_CTAGS; else { /* We didn't find a valid format specification, so we try to auto-detect the format * by counting the pipe characters on the first line and asumme pipe format when * we find more than one pipe on the line. */ guint i, pipe_cnt = 0, tab_cnt = 0; for (i = 0; i < BUFSIZ && buf[i] != '\0' && pipe_cnt < 2; i++) { if (buf[i] == '|') pipe_cnt++; else if (buf[i] == '\t') tab_cnt++; } if (pipe_cnt > 1) format = TM_FILE_FORMAT_PIPE; else if (tab_cnt > 1) format = TM_FILE_FORMAT_CTAGS; } rewind(fp); /* reset the file pointer, to start reading again from the beginning */ } file_tags = g_ptr_array_new(); while (NULL != (tag = tm_tag_new_from_file(NULL, fp, mode, format))) g_ptr_array_add(file_tags, tag); fclose(fp); tm_tags_sort(file_tags, global_tags_sort_attrs, TRUE, TRUE); /* reorder the whole array, because tm_tags_find expects a sorted array */ new_tags = tm_tags_merge(theWorkspace->global_tags, file_tags, global_tags_sort_attrs, TRUE); g_ptr_array_free(theWorkspace->global_tags, TRUE); g_ptr_array_free(file_tags, TRUE); theWorkspace->global_tags = new_tags; return TRUE; }
/** * ti9x_file_read_flash: * @filename: name of flash file to open. * @content: where to store the file content. * * Load the flash file into a #FlashContent structure. * * Structure content must be freed with #tifiles_content_delete_flash when * no longer used. If error occurs, the structure content is released for you. * * Return value: an error code, 0 otherwise. **/ int ti9x_file_read_flash(const char *filename, Ti9xFlash *head) { FILE *f; Ti9xFlash *content = head; int tib = 0; char signature[9]; if (!tifiles_file_is_flash(filename) && !tifiles_file_is_tib(filename)) { return ERR_INVALID_FILE; } if (head == NULL) { tifiles_critical("%s: an argument is NULL", __FUNCTION__); return ERR_INVALID_FILE; } // detect file type (old or new format) tib = tifiles_file_is_tib(filename); f = g_fopen(filename, "rb"); if (f == NULL) { tifiles_info("Unable to open this file: %s\n", filename); return ERR_FILE_OPEN; } if (tib) { // tib is an old format but mainly used by developers memset(content, 0, sizeof(Ti9xFlash)); if(fseek(f, 0, SEEK_END)) goto tfrf; content->data_length = (uint32_t) ftell(f); if(fseek(f, 0, SEEK_SET)) goto tfrf; strcpy(content->name, "basecode"); content->data_type = 0x23; // FLASH os content->data_part = (uint8_t *)g_malloc0(content->data_length); if (content->data_part == NULL) { fclose(f); return ERR_MALLOC; } if(fread(content->data_part, 1, content->data_length, f) < content->data_length) goto tfrf; switch(content->data_part[8]) { case 1: content->device_type = DEVICE_TYPE_92P; break; // TI92+ case 3: content->device_type = DEVICE_TYPE_89; break; // TI89 // value added by the TI community according to HWID parameter // doesn't have any 'legal' existence. case 8: content->device_type = DEVICE_TYPE_92P; break; // V200PLT case 9: content->device_type = DEVICE_TYPE_89; break; // Titanium } content->next = NULL; } else { for (content = head;; content = content->next) { if(fread_8_chars(f, signature) < 0) goto tfrf; content->model = tifiles_file_get_model(filename); if(fread_byte(f, &(content->revision_major)) < 0) goto tfrf; if(fread_byte(f, &(content->revision_minor)) < 0) goto tfrf; if(fread_byte(f, &(content->flags)) < 0) goto tfrf; if(fread_byte(f, &(content->object_type)) < 0) goto tfrf; if(fread_byte(f, &(content->revision_day)) < 0) goto tfrf; if(fread_byte(f, &(content->revision_month)) < 0) goto tfrf; if(fread_word(f, &(content->revision_year)) < 0) goto tfrf; if(fskip(f, 1) < 0) goto tfrf; if(fread_8_chars(f, content->name) < 0) goto tfrf; if(fskip(f, 23) < 0) goto tfrf; if(fread_byte(f, &(content->device_type)) < 0) goto tfrf; if(fread_byte(f, &(content->data_type)) < 0) goto tfrf; if(fskip(f, 23) < 0) goto tfrf; if(fread_byte(f, &(content->hw_id)) < 0) goto tfrf; if(fread_long(f, &(content->data_length)) < 0) goto tfrf; if(content->data_type != TI89_LICENSE && !check_device_type(content->device_type)) { return ERR_INVALID_FILE; } if(!check_data_type(content->data_type)) { return ERR_INVALID_FILE; } content->data_part = (uint8_t *)g_malloc0(content->data_length); if (content->data_part == NULL) { fclose(f); tifiles_content_delete_flash(content); return ERR_MALLOC; } if(fread(content->data_part, 1, content->data_length, f) < content->data_length) goto tfrf; content->next = NULL; // check for end of file if(fread_8_chars(f, signature) < 0) { break; } if(strcmp(signature, "**TIFL**") || feof(f)) { break; } if(fseek(f, -8, SEEK_CUR)) goto tfrf; content->next = (Ti9xFlash *)g_malloc0(sizeof(Ti9xFlash)); if (content->next == NULL) { fclose(f); tifiles_content_delete_flash(content); return ERR_MALLOC; } } } fclose(f); return 0; tfrf: // release on exit tifiles_critical("%s: error reading / understanding file %s", __FUNCTION__, filename); fclose(f); tifiles_content_delete_flash(content); return ERR_FILE_IO; }
/* Creates a list of global tags. Ideally, this should be created once during installations so that all users can use the same file. Thsi is because a full scale global tag list can occupy several megabytes of disk space. @param pre_process The pre-processing command. This is executed via system(), so you can pass stuff like 'gcc -E -dD -P `gnome-config --cflags gnome`'. @param includes Include files to process. Wildcards such as '/usr/include/a*.h' are allowed. @param tags_file The file where the tags will be stored. @param lang The language to use for the tags file. @return TRUE on success, FALSE on failure. */ gboolean tm_workspace_create_global_tags(const char *pre_process, const char **includes, int includes_count, const char *tags_file, int lang) { #ifdef HAVE_GLOB_H glob_t globbuf; size_t idx_glob; #endif int idx_inc; char *command; guint i; FILE *fp; TMSourceFile *source_file; GPtrArray *tags_array; GHashTable *includes_files_hash; GList *includes_files = NULL; gchar *temp_file = create_temp_file("tmp_XXXXXX.cpp"); gchar *temp_file2 = create_temp_file("tmp_XXXXXX.cpp"); if (NULL == temp_file || NULL == temp_file2 || NULL == (fp = g_fopen(temp_file, "w"))) { g_free(temp_file); g_free(temp_file2); return FALSE; } includes_files_hash = g_hash_table_new_full (tm_file_inode_hash, g_direct_equal, NULL, g_free); #ifdef HAVE_GLOB_H globbuf.gl_offs = 0; if (includes[0][0] == '"') /* leading \" char for glob matching */ for(idx_inc = 0; idx_inc < includes_count; idx_inc++) { size_t dirty_len = strlen(includes[idx_inc]); char *clean_path = g_malloc(dirty_len - 1); strncpy(clean_path, includes[idx_inc] + 1, dirty_len - 1); clean_path[dirty_len - 2] = 0; #ifdef TM_DEBUG g_message ("[o][%s]\n", clean_path); #endif glob(clean_path, 0, NULL, &globbuf); #ifdef TM_DEBUG g_message ("matches: %d\n", globbuf.gl_pathc); #endif for(idx_glob = 0; idx_glob < globbuf.gl_pathc; idx_glob++) { #ifdef TM_DEBUG g_message (">>> %s\n", globbuf.gl_pathv[idx_glob]); #endif if (!g_hash_table_lookup(includes_files_hash, globbuf.gl_pathv[idx_glob])) { char* file_name_copy = strdup(globbuf.gl_pathv[idx_glob]); g_hash_table_insert(includes_files_hash, file_name_copy, file_name_copy); #ifdef TM_DEBUG g_message ("Added ...\n"); #endif } } globfree(&globbuf); g_free(clean_path); } else #endif /* no glob support or globbing not wanted */ for(idx_inc = 0; idx_inc < includes_count; idx_inc++) { if (!g_hash_table_lookup(includes_files_hash, includes[idx_inc])) { char* file_name_copy = strdup(includes[idx_inc]); g_hash_table_insert(includes_files_hash, file_name_copy, file_name_copy); } } /* Checks for duplicate file entries which would case trouble */ g_hash_table_foreach(includes_files_hash, tm_move_entries_to_g_list, &includes_files); includes_files = g_list_reverse (includes_files); #ifdef TM_DEBUG g_message ("writing out files to %s\n", temp_file); #endif if (pre_process != NULL) write_includes_file(fp, includes_files); else append_to_temp_file(fp, includes_files); g_list_free (includes_files); g_hash_table_destroy(includes_files_hash); includes_files_hash = NULL; includes_files = NULL; fclose(fp); if (pre_process != NULL) { gint ret; gchar *tmp_errfile = create_temp_file("tmp_XXXXXX"); gchar *errors = NULL; command = g_strdup_printf("%s %s >%s 2>%s", pre_process, temp_file, temp_file2, tmp_errfile); #ifdef TM_DEBUG g_message("Executing: %s", command); #endif ret = system(command); g_free(command); g_unlink(temp_file); g_free(temp_file); g_file_get_contents(tmp_errfile, &errors, NULL, NULL); if (errors && *errors) g_printerr("%s", errors); g_free(errors); g_unlink(tmp_errfile); g_free(tmp_errfile); if (ret == -1) { g_unlink(temp_file2); return FALSE; } } else { /* no pre-processing needed, so temp_file2 = temp_file */ g_unlink(temp_file2); g_free(temp_file2); temp_file2 = temp_file; temp_file = NULL; } source_file = tm_source_file_new(temp_file2, tm_source_file_get_lang_name(lang)); update_source_file(source_file, NULL, 0, FALSE, FALSE); if (NULL == source_file) { g_unlink(temp_file2); return FALSE; } g_unlink(temp_file2); g_free(temp_file2); if (0 == source_file->tags_array->len) { tm_source_file_free(source_file); return FALSE; } tags_array = tm_tags_extract(source_file->tags_array, tm_tag_max_t); if ((NULL == tags_array) || (0 == tags_array->len)) { if (tags_array) g_ptr_array_free(tags_array, TRUE); tm_source_file_free(source_file); return FALSE; } if (FALSE == tm_tags_sort(tags_array, global_tags_sort_attrs, TRUE, FALSE)) { tm_source_file_free(source_file); return FALSE; } if (NULL == (fp = g_fopen(tags_file, "w"))) { tm_source_file_free(source_file); return FALSE; } fprintf(fp, "# format=tagmanager\n"); for (i = 0; i < tags_array->len; ++i) { tm_tag_write(TM_TAG(tags_array->pdata[i]), fp, tm_tag_attr_type_t | tm_tag_attr_scope_t | tm_tag_attr_arglist_t | tm_tag_attr_vartype_t | tm_tag_attr_pointer_t); } fclose(fp); tm_source_file_free(source_file); g_ptr_array_free(tags_array, TRUE); return TRUE; }
/** * ti9x_file_read_regular: * @filename: name of single/group file to open. * @content: where to store the file content. * * Load the single/group file into a Ti9xRegular structure. * * Structure content must be freed with #tifiles_content_delete_regular when * no longer used. If error occurs, the structure content is released for you. * * Return value: an error code, 0 otherwise. **/ int ti9x_file_read_regular(const char *filename, Ti9xRegular *content) { FILE *f; long cur_pos = 0; char default_folder[FLDNAME_MAX]; char current_folder[FLDNAME_MAX]; uint32_t curr_offset = 0; uint32_t next_offset = 0; uint16_t tmp; int i, j; char signature[9]; char varname[VARNAME_MAX]; if (!tifiles_file_is_regular(filename)) { return ERR_INVALID_FILE; } if (content == NULL) { tifiles_critical("%s: an argument is NULL", __FUNCTION__); return ERR_INVALID_FILE; } f = g_fopen(filename, "rb"); if (f == NULL) { tifiles_info( "Unable to open this file: %s", filename); return ERR_FILE_OPEN; } if(fread_8_chars(f, signature) < 0) goto tffr; content->model = tifiles_signature2calctype(signature); if (content->model == CALC_NONE) { return ERR_INVALID_FILE; } if(content->model_dst == CALC_NONE) { content->model_dst = content->model; } if(fread_word(f, NULL) < 0) goto tffr; if(fread_8_chars(f, default_folder) < 0) goto tffr; ticonv_varname_from_tifile_s(content->model_dst, default_folder, content->default_folder, -1); strcpy(current_folder, content->default_folder); if(fread_n_chars(f, 40, content->comment) < 0) goto tffr; if(fread_word(f, &tmp) < 0) goto tffr; content->num_entries = tmp; content->entries = g_malloc0((content->num_entries + 1) * sizeof(VarEntry*)); if (content->entries == NULL) { fclose(f); return ERR_MALLOC; } for (i = 0, j = 0; i < content->num_entries; i++) { VarEntry *entry = content->entries[j] = g_malloc0(sizeof(VarEntry)); if(fread_long(f, &curr_offset) < 0) goto tffr; if(fread_8_chars(f, varname) < 0) goto tffr; ticonv_varname_from_tifile_s(content->model_dst, varname, entry->name, entry->type); if(fread_byte(f, &(entry->type)) < 0) goto tffr; if(fread_byte(f, &(entry->attr)) < 0) goto tffr; entry->attr = (entry->attr == 2 || entry->attr == 3) ? ATTRB_ARCHIVED : entry->attr; if(fread_word(f, NULL) < 0) goto tffr; if (entry->type == TI92_DIR) // same as TI89_DIR, TI89t_DIR, ... { strcpy(current_folder, entry->name); g_free(entry); continue; // folder: skip entry } else { uint16_t checksum, sum = 0; j++; strcpy(entry->folder, current_folder); cur_pos = ftell(f); if(cur_pos == -1L) goto tffr; if(fread_long(f, &next_offset) < 0) goto tffr; entry->size = next_offset - curr_offset - 4 - 2; entry->data = (uint8_t *)g_malloc0(entry->size); if (entry->data == NULL) { fclose(f); tifiles_content_delete_regular(content); return ERR_MALLOC; } if(fseek(f, curr_offset, SEEK_SET)) goto tffr; if(fread_long(f, NULL) < 0) goto tffr; // 4 bytes (NULL) if(fread(entry->data, 1, entry->size, f) < entry->size) goto tffr; if(fread_word(f, &checksum) < 0) goto tffr; if(fseek(f, cur_pos, SEEK_SET)) goto tffr; sum = tifiles_checksum(entry->data, entry->size); if(sum != checksum) { fclose(f); tifiles_content_delete_regular(content); return ERR_FILE_CHECKSUM; } content->checksum += sum; // sum of all checksums but unused } } content->num_entries = j; content->entries = g_realloc(content->entries, content->num_entries * sizeof(VarEntry*)); //fread_long(f, &next_offset); //fseek(f, next_offset - 2, SEEK_SET); //fread_word(f, &(content->checksum)); fclose(f); return 0; tffr: // release on exit tifiles_critical("%s: error reading / understanding file %s", __FUNCTION__, filename); fclose(f); tifiles_content_delete_regular(content); return ERR_FILE_IO; }
gboolean Distro_WindowsCreate( const gchar * project_title, const gchar * game_path ) { gchar * blank_buffer = g_new(gchar, 512); gchar * game_buffer = NULL; gchar * binary_buffer = NULL; gsize game_buffer_length = 0; gsize binary_buffer_length = 0; gsize bytes_read = 0; gzFile binary_original; FILE * binary_temporary; gchar * shared_directory = Meg_Directory_Share("binaries"); gchar * binary_original_path; gchar * binary_temporary_path; gchar * target_name; gchar * zip_original_path; gchar * zip_target_path; if ( g_file_get_contents( game_path, &game_buffer, &game_buffer_length, NULL ) ) { target_name = g_strdup_printf("%s.exe", project_title ); binary_original_path = g_build_filename( shared_directory, "windows-exe.gz", NULL); binary_temporary_path = g_build_filename( g_get_tmp_dir(), target_name, NULL); zip_original_path = g_build_filename( shared_directory, "windows-dll.zip", NULL); zip_target_path = g_strdup_printf( "%s"G_DIR_SEPARATOR_S"%s-windows.zip", Meg_Directory_Document(), project_title ); binary_original = gzopen( binary_original_path, "rb" ); binary_temporary = g_fopen( binary_temporary_path, "wb" ); g_print( "binary_original: %p\n", binary_original ); g_print( "binary_temporary: %p\n", binary_temporary ); g_print( "binary_original_path: %s\n", binary_original_path ); g_print( "binary_temporary_path: %s\n", binary_temporary_path ); g_print( "zip_original_path: %s\n", zip_original_path ); g_print( "zip_target_path: %s\n", zip_target_path ); if ( binary_original && binary_temporary ) { while ( TRUE ) // Read gzip { bytes_read = gzread( binary_original, blank_buffer, 512); if ( bytes_read > 0 ) { fwrite( blank_buffer, bytes_read, 1, binary_temporary ); } else { break; } } fwrite( game_buffer, game_buffer_length, 1, binary_temporary ); if ( g_file_get_contents( binary_temporary_path, &binary_buffer, &binary_buffer_length, NULL ) ) { Meg_FileCopy( zip_original_path, zip_target_path ); mz_zip_add_mem_to_archive_file_in_place( zip_target_path, target_name, binary_buffer, binary_buffer_length, NULL, 0, 0 ); } g_free(binary_buffer); } else { g_warning("Distro_WindowsCreate Failed"); } gzclose(binary_original); fclose(binary_temporary); g_free(game_buffer); g_free(zip_original_path); g_free(zip_target_path); g_free(binary_temporary_path); g_free(binary_original_path); return TRUE; } return FALSE; }