gboolean readUserInput_two(GIOChannel *ioch, GIOCondition cond, gpointer data) { int bytes_read; int length = 1000; GString* g_string_new = g_new0(GString,1); GIOStatus out = G_IO_STATUS_NORMAL; do { out = g_io_channel_read_line_string(ioch, g_string_new, &length, NULL); if (out != G_IO_STATUS_ERROR) { char * temp = strchr(g_string_new->str,'\n'); if(temp != NULL) { *temp = '\0'; } char * town = strtok(g_string_new->str,":"); char * street = strtok(NULL,":"); if(street != NULL) { printf("Town: %s\n",town); printf("Street: %s\n",street); setPosition(town,street); hasGottenUserInput = 1; } //process_char(chr); //if (pref.diag_comm) printf("%02x\n", chr); } } while (out == G_IO_STATUS_AGAIN); return TRUE; }
/*---------------------------------------------------------------------*/ static gboolean watch_output( GIOChannel *chann, GIOCondition condition, gpointer data ) { gchar buf[ BUFSIZ + 1 ]; gsize n; GError *err = NULL; gui_stop_waiting(); if( condition & G_IO_HUP ) return watch_hup( chann, condition, data ); while( G_IO_STATUS_NORMAL == g_io_channel_read_line_string( chann, buffer, 0, &err ) ) { hop_console_insert( buffer->str, buffer->len ); buffer->str[ buffer->len ] = 0; } while( G_IO_STATUS_NORMAL == g_io_channel_read_chars( chann, buf, BUFSIZ, &n, &err ) ) { hop_console_insert( buf, n ); buffer->str[ n ] = 0; if( n < BUFSIZ ) break; } hop_console_adjust(); return TRUE; }
int main(int argc, char * argv[]) { xmlNodePtr sentence; gchar ** tokens; GString * linebuffer = g_string_new(""); GIOChannel * in = g_io_channel_unix_new(fileno(stdin)); //首先读取一行文字 g_io_channel_read_line_string(in,linebuffer,NULL,NULL); //分割 tokens = g_strsplit_set(linebuffer->str," ",1024); //为此行文字打标记 init_yylex(tokens); //打好词性标记后开始解析语法结构 xmlInitGlobals(); xmlInitMemory(); yyparse(&sentence); xmlCleanupGlobals(); xmlCleanupMemory(); xmlSaveCtxtPtr saver = xmlSaveToFd(2,"UTF-8",0); xmlSaveTree(saver,sentence); xmlSaveFlush(saver); xmlSaveClose(saver); write(2,"\n",1); //输出语法树, 以 XML 形式 return 0; }
static void autorun_startup(void) { char *path; GIOChannel *handle; GString *buf; gsize tpos; /* open ~/.irssi/startup and run all commands in it */ path = g_strdup_printf("%s/startup", get_irssi_dir()); handle = g_io_channel_new_file(path, "r", NULL); g_free(path); if (handle == NULL) { /* file not found */ return; } g_io_channel_set_encoding(handle, NULL, NULL); buf = g_string_sized_new(512); while (g_io_channel_read_line_string(handle, buf, &tpos, NULL) == G_IO_STATUS_NORMAL) { buf->str[tpos] = '\0'; if (buf->str[0] != '#') { eval_special_string(buf->str, "", active_win->active_server, active_win->active); } } g_string_free(buf, TRUE); g_io_channel_unref(handle); }
/*! \brief process_vex_line() is called for to read the VEX file and dispatch handlers to process sections of the file. \param vex (Vex_Import *) pointer to Vex_Import structure. \param iochannel (GIOChannel *) the bytestream represented by the VEXfile \returns The status of the operation (G_IO_STATUS_ERROR/G_IO_STATUS_NORMAL usually */ G_MODULE_EXPORT GIOStatus process_vex_line(Vex_Import * vex, GIOChannel *iochannel) { GString *a_line = g_string_new("\0"); GIOStatus status = g_io_channel_read_line_string(iochannel, a_line, NULL, NULL); gint i = 0; gint num_tests = sizeof(import_handlers)/sizeof(import_handlers[0]); if (status == G_IO_STATUS_NORMAL) { for (i=0;i<num_tests;i++) { if (g_strrstr(a_line->str,import_handlers[i].import_tag) != NULL) { status = handler_dispatch(vex, import_handlers[i].function, import_handlers[i].parsetag,a_line->str, iochannel); if (status != G_IO_STATUS_NORMAL) { dbg_func_f(CRITICAL,g_strdup(__FILE__": process_vex_line()\n\tVEX_line parsing ERROR\n")); return status; } goto breakout; } } } breakout: g_string_free(a_line, TRUE); return status; }
/*! \brief load_table() physically handles loading the table datafrom disk, populating and array and sotring a pointer to that array in the lookuptables hashtable referenced by the table_name passed \param table_name (gchar *) key to lookuptables hashtable \param filename (gchar *) filename to load table data from \returns TRUE on success, FALSE on failure */ gboolean load_table(gchar *table_name, gchar *filename) { GIOStatus status; GIOChannel *iochannel; gboolean done = FALSE; gchar * str = NULL; gchar * tmp = NULL; gchar * end = NULL; GString *a_line; LookupTable *lookuptable = NULL; gint tmparray[2048]; /* bad idea being static!!*/ gchar ** vector = NULL; gint i = 0; iochannel = g_io_channel_new_file(filename,"r", NULL); status = g_io_channel_seek_position(iochannel,0,G_SEEK_SET,NULL); if (status != G_IO_STATUS_NORMAL) { dbg_func(CRITICAL,g_strdup(__FILE__": load_lookuptables()\n\tError seeking to beginning of the file\n")); } while (!done) { a_line = g_string_new("\0"); status = g_io_channel_read_line_string(iochannel, a_line, NULL, NULL); if (status == G_IO_STATUS_EOF) done = TRUE; else { /* str = g_strchug(g_strdup(a_line->str));*/ str = g_strchug(a_line->str); if (g_str_has_prefix(str,"DB")) { str+=2; /* move 2 places in */ end = g_strrstr(str,"T"); tmp = g_strndup(str,end-str); tmparray[i]=atoi(tmp); g_free(tmp); i++; } } g_string_free(a_line,TRUE); } g_io_channel_shutdown(iochannel,TRUE,NULL); g_io_channel_unref(iochannel); vector = g_strsplit(filename,PSEP,-1); lookuptable = g_new0(LookupTable, 1); lookuptable->array = g_memdup(&tmparray,i*sizeof(gint)); lookuptable->filename = g_strdup(vector[g_strv_length(vector)-1]); g_strfreev(vector); if (!lookuptables) lookuptables = g_hash_table_new_full(g_str_hash,g_str_equal,g_free,dealloc_lookuptable); g_hash_table_insert(lookuptables,g_strdup(table_name),lookuptable); /*g_hash_table_foreach(lookuptables,dump_lookuptables,NULL);*/ return TRUE; }
static gboolean read_stdin(GIOChannel *source, GIOCondition condition, gpointer data) { /* Unused. */ (void)source; (void)condition; GString *buffer = g_string_new(""); GError *err = NULL; gchar **tokens = NULL; gchar *line_copy = NULL; gint num_tokens = 0; struct application_info *app = (struct application_info *)data; /* Mixing stdio.h and GIO is probably a bad idea, thus we better use * GIO here to read from stdin. */ if (g_io_channel_read_line_string(app->gio.stdin_channel, buffer, NULL, &err) == G_IO_STATUS_NORMAL) { /* Copy string from GString into a gchar so we can use * g_strchomp() on it. */ line_copy = g_strdup(buffer->str); g_string_free(buffer, TRUE); tokens = g_strsplit(g_strchomp(line_copy), " ", -1); for (num_tokens = 0; tokens[num_tokens] != NULL; num_tokens++) /* No body, just count the tokens. */ ; if (num_tokens >= 1) { if (g_strcmp0(tokens[0], "start") == 0) { timer_start(app); } else if (g_strcmp0(tokens[0], "pause") == 0) { timer_pause(app); } else if (g_strcmp0(tokens[0], "reset") == 0) { timer_reset(app); } } g_strfreev(tokens); g_free(line_copy); } if (err != NULL) { g_error_free(err); } /* Do not remove this watch. */ return TRUE; }
/* io out watch callback */ static gboolean cb_out_watch( GIOChannel *channel, GIOCondition cond, GString *data ) { GIOStatus status; gchar detect_str[8]; memset(detect_str,0,8); data = g_string_new(NULL); if( cond == G_IO_HUP ) { g_io_channel_unref( channel ); return( FALSE ); } status = g_io_channel_read_line_string( channel, data, NULL, NULL ); switch(status) { case G_IO_STATUS_EOF: printf("EOF\n"); break; case G_IO_STATUS_NORMAL: //~ fprintf(stdout,"%s",data->str); memcpy(detect_str,data->str,5); if(!strcmp(detect_str,"DATA:")) { if(parse_nfc_data(data) == TRUE) { Bitwise WindowSwitcherFlag; f_status_window = FALSE; f_sending_window = TRUE; if(lastParkingData.park_key_long == 0)f_sync_in = TRUE; else f_sync_out = TRUE; WindowSwitcher(WindowSwitcherFlag); } } break; case G_IO_STATUS_AGAIN: break; case G_IO_STATUS_ERROR: default: printf("Error stdout from child process\n"); error_message("Error reading from child process"); break; } g_string_free(data,TRUE); return( TRUE ); }
/* io out watch callback */ static gboolean cb_out_watch( GIOChannel *channel, GIOCondition cond, GString *data ) { GIOStatus status; gchar detect_str[8]; memset(detect_str,0,8); data = g_string_new(NULL); if( cond == G_IO_HUP ) { g_io_channel_unref( channel ); return( FALSE ); } status = g_io_channel_read_line_string( channel, data, NULL, NULL ); switch(status) { case G_IO_STATUS_EOF: printf("EOF\n"); break; case G_IO_STATUS_NORMAL: //~ fprintf(stdout,"%s",data->str); memcpy(detect_str,data->str,5); if(!strcmp(detect_str,"DATA:")) { kill_nfc_poll_process(); if(parse_nfc_data(data) == TRUE) { g_idle_add(absen_valid_data, NULL); } } break; case G_IO_STATUS_AGAIN: break; case G_IO_STATUS_ERROR: default: printf("Error stdout from child process\n"); error_message("Error reading from child process"); break; } g_string_free(data,TRUE); return( TRUE ); }
/* SYNTAX: CAT <file> */ static void cmd_cat(const char *data) { char *fname, *fposstr; void *free_arg; int fpos; GIOChannel *handle; GString *buf; gsize tpos; #ifdef HAVE_CAPSICUM int fd; #endif if (!cmd_get_params(data, &free_arg, 2, &fname, &fposstr)) return; fname = convert_home(fname); fpos = atoi(fposstr); cmd_params_free(free_arg); #ifdef HAVE_CAPSICUM fd = capsicum_open_wrapper(fname, O_RDONLY, 0); if (fd > 0) handle = g_io_channel_unix_new(fd); else handle = NULL; #else handle = g_io_channel_new_file(fname, "r", NULL); #endif g_free(fname); if (handle == NULL) { /* file not found */ printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "%s", g_strerror(errno)); return; } g_io_channel_set_encoding(handle, NULL, NULL); g_io_channel_seek_position(handle, fpos, G_SEEK_SET, NULL); buf = g_string_sized_new(512); while (g_io_channel_read_line_string(handle, buf, &tpos, NULL) == G_IO_STATUS_NORMAL) { buf->str[tpos] = '\0'; printtext(NULL, NULL, MSGLEVEL_CLIENTCRAP | MSGLEVEL_NEVER, "%s", buf->str); } g_string_free(buf, TRUE); g_io_channel_unref(handle); }
struct tilt_data* tilt_data_read_log(const char* filename) { GError* _err = NULL; GIOChannel* in_c = g_io_channel_new_file(filename, "r", &_err); if (_err) { g_free(_err); return NULL; } GArray* ga_gyro = g_array_new(FALSE, FALSE, sizeof(double)); GArray* ga_ay = g_array_new(FALSE, FALSE, sizeof(double)); GArray* ga_az = g_array_new(FALSE, FALSE, sizeof(double)); GString *str = g_string_sized_new(256); GIOStatus st; do { double gx, gy, gz, ax, ay, az; st = g_io_channel_read_line_string(in_c, str, NULL, &_err); if (g_str_has_prefix(str->str, "IMU_GYRO")) { if (sscanf(str->str, "IMU_GYRO %lf %lf %lf", &gx, &gy, &gz) == 3) { g_array_append_val(ga_gyro, gx); } } else if (g_str_has_prefix(str->str, "IMU_ACCEL")) { if (sscanf(str->str, "IMU_ACCEL %lf %lf %lf", &ax, &ay, &az) == 3) { g_array_append_val(ga_ay, ay); g_array_append_val(ga_az, az); } } } while (st != G_IO_STATUS_EOF); g_string_free(str, TRUE); g_free(in_c); struct tilt_data* td = tilt_data_new(ga_gyro->len, 0.015625); int i; for (i=0; i<ga_gyro->len; i++) { double* ggx = &g_array_index(ga_gyro, double, i); td->gyro[i] = *ggx; double* gay = &g_array_index(ga_ay, double, i); td->ay[i] = *gay; double* gaz = &g_array_index(ga_az, double, i); td->az[i] = *gaz; td->m_angle[i] = atan2(td->ay[i], td->az[i]); } return td; }
static int show_help_file(const char *file) { const char *helppath; char *path, **paths, **tmp; GIOChannel *handle; GString *buf; gsize tpos; helppath = settings_get_str("help_path"); paths = g_strsplit(helppath, ":", -1); handle = NULL; for (tmp = paths; *tmp != NULL; tmp++) { /* helpdir/command or helpdir/category/command */ path = g_strdup_printf("%s/%s", *tmp, file); handle = g_io_channel_new_file(path, "r", NULL); g_free(path); if (handle != NULL) break; } g_strfreev(paths); if (handle == NULL) return FALSE; g_io_channel_set_encoding(handle, NULL, NULL); buf = g_string_sized_new(512); /* just print to screen whatever is in the file */ while (g_io_channel_read_line_string(handle, buf, &tpos, NULL) == G_IO_STATUS_NORMAL) { buf->str[tpos] = '\0'; g_string_prepend(buf, "%|"); printtext_string(NULL, NULL, MSGLEVEL_CLIENTCRAP, buf->str); } g_string_free(buf, TRUE); g_io_channel_unref(handle); return TRUE; }
static gboolean io_watch_cb (GIOChannel * channel, GIOCondition condition, gpointer data) { GString * buffer = g_string_new (""); GIOStatus state = G_IO_STATUS_NORMAL; GfcReader* self = GFC_READER (data); while (state == G_IO_STATUS_NORMAL) { gsize delim = 0; // FIXME: add GError here state = g_io_channel_read_line_string (channel, buffer, &delim, NULL); switch (state) { case G_IO_STATUS_NORMAL: /* sometimes we get an empty string because we stopped reading at the last character */ if (delim < buffer->len && buffer->str[delim]) { g_string_set_size (buffer, delim); g_signal_emit (self, signals[READ_LINE], 0, buffer->str); // FIXME: emit by signal id g_string_set_size (buffer, 0); } break; case G_IO_STATUS_AGAIN: /* no data right now... try again later */ break; case G_IO_STATUS_ERROR: case G_IO_STATUS_EOF: // FIXME: call g_source_remove() here instead of flush()? g_source_remove (self->_private->io_handler); self->_private->io_handler = 0; g_string_free (buffer, TRUE); return FALSE; } } g_string_free (buffer, TRUE); return TRUE; }
/* fills in line_buf with the line that pos is in the middle of, returns * position of beginning of line */ static gint64 get_line_at_pos (GIOChannel *io_channel, gint64 start_pos, GString *line_buf) { gint64 pos; int c = -1; /* find beginning of line */ for (pos = start_pos - 1; pos >= 0 && c != '\n'; pos--) { seek (io_channel, pos); c = read_byte (io_channel); /* advances seek position by 1 */ } if (c == '\n') { /* pos is pointing to byte before '\n' */ pos += 2; } else if (pos < 0) { /* either we never seeked or read_byte() ate first byte of file */ pos = 0; seek (io_channel, pos); } /* read in the line */ GError *error = NULL; GIOStatus status = g_io_channel_read_line_string (io_channel, line_buf, NULL, &error); g_assert (status != G_IO_STATUS_AGAIN); if (status == G_IO_STATUS_ERROR) { g_printerr ("bin-search: g_io_channel_read_line_string: %s\n", error->message); exit (7); } return pos; }
static gboolean on_input(GIOChannel* in, GIOCondition condition, GMainLoop* loop) { static GString* buf = NULL; if(!buf) { buf = g_string_sized_new(0x40); } GError* error = NULL; GIOStatus status = g_io_channel_read_line_string(in,buf,NULL,&error); switch(status) { case G_IO_STATUS_AGAIN: return TRUE; case G_IO_STATUS_EOF: case G_IO_STATUS_ERROR: fprintf(stderr,"EEEP\n"); g_main_loop_quit(loop); return FALSE; case G_IO_STATUS_NORMAL: buf->str[buf->len-1] = '\0'; nextSong(buf); return TRUE; }; }
/*! \brief read_number_from_line() is used to read the RPM/LOAD values from the VEX file and store them in the Vex_Import structure \param dest (gint *) pointer to array within the Vex_Import struct \param iochannel (GIOChannel *) pointer to the iochannel representing the VEX file \returns status of the operation (G_IO_STATUS_ERROR/G_IO_STATUS_NORMAL) */ G_MODULE_EXPORT GIOStatus read_number_from_line(gint *dest, GIOChannel *iochannel) { GIOStatus status; gchar ** str_array = NULL; gchar * result = NULL; GString *a_line = g_string_new("\0"); status = g_io_channel_read_line_string(iochannel, a_line, NULL, NULL); if (status != G_IO_STATUS_NORMAL) return status; /* Make sure the line contains an "=" sign, otherwise we'll segfault*/ if (strstr(a_line->str, "=") != NULL) { str_array = g_strsplit(a_line->str, "=", 2); result = g_strdup(str_array[1]); g_strfreev(str_array); *dest = atoi(result); } else status = G_IO_STATUS_ERROR; g_string_free(a_line, TRUE); return status; }
/* * NOTE: the channel is not in nonblocking mode, thus the control channel * may block syslog-ng completely. */ static gboolean control_channel_input(GIOChannel *channel, GIOCondition cond, gpointer user_data) { GString *command = g_string_sized_new(32); gsize command_len = 0; GError *error = NULL; gint cmd; GIOStatus status; status = g_io_channel_read_line_string(channel, command, &command_len, &error); if (status == G_IO_STATUS_ERROR) { msg_error("Error reading command on control channel, closing control channel", evt_tag_str("error", error->message), NULL); g_clear_error(&error); return FALSE; } else if (status != G_IO_STATUS_NORMAL) { /* EAGAIN or EOF */ msg_verbose("EOF or EAGAIN on control channel, closing control channel", NULL); return FALSE; } /* strip EOL */ g_string_truncate(command, command_len); for (cmd = 0; commands[cmd].func; cmd++) { if (strncmp(commands[cmd].command, command->str, strlen(commands[cmd].command)) == 0) return commands[cmd].func(channel, command); } msg_error("Unknown command read on control channel, closing control channel", evt_tag_str("command", command->str), NULL); return FALSE; }
static GHashTable * read_country_codes (void) { GHashTable *table; GIOChannel *channel; GString *buffer; GError *error = NULL; GIOStatus status; channel = g_io_channel_new_file (ISO_3166_COUNTRY_CODES, "r", &error); if (!channel) { if (error) { g_warning ("Could not read " ISO_3166_COUNTRY_CODES ": %s", error->message); g_error_free (error); } else g_warning ("Could not read " ISO_3166_COUNTRY_CODES ": Unknown error"); return NULL; } table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); buffer = g_string_sized_new (32); status = G_IO_STATUS_NORMAL; while (status == G_IO_STATUS_NORMAL) { status = g_io_channel_read_line_string (channel, buffer, NULL, &error); switch (status) { case G_IO_STATUS_NORMAL: if (buffer->str[0] != '#') { char **pieces; pieces = g_strsplit (buffer->str, "\t", 2); /* Hack for rh#556292; iso3166.tab is just wrong */ pieces[1] = pieces[1] ? g_strchomp (pieces[1]) : NULL; if (pieces[1] && !strcmp (pieces[1], "Britain (UK)")) { g_free (pieces[1]); pieces[1] = g_strdup (_("United Kingdom")); } g_hash_table_insert (table, pieces[0], pieces[1]); g_free (pieces); } g_string_truncate (buffer, 0); break; case G_IO_STATUS_EOF: break; case G_IO_STATUS_ERROR: g_warning ("Error while reading: %s", error->message); g_error_free (error); break; case G_IO_STATUS_AGAIN: /* FIXME: Try again a few times, but really, it never happes, right? */ break; } } g_string_free (buffer, TRUE); g_io_channel_unref (channel); return table; }
/* Handle communications with the client. */ gboolean interface_client_event(GIOChannel* source, GIOCondition condition, gpointer data) { GString* buffer = NULL; GError* err = NULL; GIOStatus status; int client; command_result cr = CR_OK; client = g_io_channel_unix_get_fd(source); /* Ready for reading? */ if (condition & G_IO_IN) { buffer = g_string_sized_new(1024); if (!buffer) { g_warning("[ice:%d] Can't allocate buffer.", client); goto ice_client_clean; } /* Read exactly one command */ status = g_io_channel_read_line_string(source, buffer, NULL, &err); if (status == G_IO_STATUS_EOF) { g_debug("[ice:%d] Connection reset by peer.", client); goto ice_client_clean; } else if (status != G_IO_STATUS_NORMAL) { g_debug("[ice:%d] Can't read from IO channel: %s", client, err->message); goto ice_client_clean; } buffer->str[buffer->len-1] = '\0'; g_debug("[ice:%d] Received command: %s", client, buffer->str); buffer->str[buffer->len-1] = '\n'; /* Parse and run the command */ cr = interface_handle_command(source, buffer->str); g_string_free(buffer, TRUE); buffer = NULL; /* "idle" command? */ if (cr == CR_IDLE) { /* Add to list of idle channels */ g_idle_channels = g_list_prepend(g_idle_channels, source); } } /* Received hangup? */ if (condition & G_IO_HUP) { g_debug("[ice:%d] Connection hung up", client); goto ice_client_clean; } if (cr != CR_CLOSE) return TRUE; ice_client_clean: if (buffer) g_string_free(buffer, TRUE); g_idle_channels = g_list_remove(g_idle_channels, source); g_io_channel_shutdown(source, TRUE, NULL); g_io_channel_unref(source); g_info("[ice:%d] Connection closed.", client); return FALSE; }
gint main (gint argc, gchar * argv[]) { GIOChannel *gio_r, *gio_w ; GError *gerr = NULL; GString *buffer; char *filename; char *srcdir = getenv ("srcdir"); gint rlength = 0; glong wlength = 0; gsize length_out; const gchar encoding[] = "ISO-8859-5"; GIOStatus status; GIOFlags flags; #ifdef SYMBIAN g_log_set_handler (NULL, G_LOG_FLAG_FATAL| G_LOG_FLAG_RECURSION | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG, &mrtLogHandler, NULL); g_set_print_handler(mrtPrintHandler); #endif /*SYMBIAN*/ if (!srcdir) srcdir = "c:"; filename = g_strconcat (srcdir, G_DIR_SEPARATOR_S, "iochannel-test-infile", NULL); setbuf (stdout, NULL); /* For debugging */ gio_r = g_io_channel_new_file (filename, "r", &gerr); if (gerr) { g_warning ("Unable to open file %s: %s", filename, gerr->message); g_error_free (gerr); g_assert(FALSE && "iochannel-test failed"); #if SYMBIAN testResultXml("iochannel-test"); #endif /* EMULATOR */ return 1; } gio_w = g_io_channel_new_file ("c:\\iochannel-test-outfile", "w", &gerr); if (gerr) { g_warning ("Unable to open file %s: %s", "iochannel-test-outfile", gerr->message); g_error_free (gerr); g_assert(FALSE && "iochannel-test failed"); #if SYMBIAN testResultXml("iochannel-test"); #endif /* EMULATOR */ return 1; } g_io_channel_set_encoding (gio_r, encoding, &gerr); if (gerr) { g_warning (gerr->message); g_error_free (gerr); g_assert(FALSE && "iochannel-test failed"); #if SYMBIAN testResultXml("iochannel-test"); #endif /* EMULATOR */ return 1; } g_io_channel_set_buffer_size (gio_r, BUFFER_SIZE); status = g_io_channel_set_flags (gio_r, G_IO_FLAG_NONBLOCK, &gerr); if (status == G_IO_STATUS_ERROR) { g_warning (gerr->message); g_assert(FALSE && "iochannel-test failed"); g_error_free (gerr); gerr = NULL; } flags = g_io_channel_get_flags (gio_r); buffer = g_string_sized_new (BUFFER_SIZE); while (TRUE) { do status = g_io_channel_read_line_string (gio_r, buffer, NULL, &gerr); while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; rlength += buffer->len; do status = g_io_channel_write_chars (gio_w, buffer->str, buffer->len, &length_out, &gerr); while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; wlength += length_out; if (length_out < buffer->len) { g_warning ("Only wrote part of the line."); g_assert(FALSE && "iochannel-test failed"); } #ifdef VERBOSE g_print ("%s", buffer->str); #endif g_string_truncate (buffer, 0); } switch (status) { case G_IO_STATUS_EOF: break; case G_IO_STATUS_ERROR: g_warning (gerr->message); g_error_free (gerr); gerr = NULL; break; default: g_warning ("Abnormal exit from write loop."); g_assert(FALSE && "iochannel-test failed"); break; } do status = g_io_channel_flush (gio_w, &gerr); while (status == G_IO_STATUS_AGAIN); if (status == G_IO_STATUS_ERROR) { g_warning (gerr->message); g_assert(FALSE && "iochannel-test failed"); g_error_free (gerr); gerr = NULL; } #ifdef VERBOSE g_print ("read %d bytes, wrote %ld bytes\n", rlength, wlength); #endif g_io_channel_unref(gio_r); g_io_channel_unref(gio_w); #if SYMBIAN testResultXml("iochannel-test"); #endif /* EMULATOR */ return 0; }
static gboolean handle_stdin (GIOChannel * channel, GIOCondition condition, gpointer data) { if ((condition & G_IO_IN) != 0) { GString *string; GError *err = NULL; string = g_string_new (NULL); while (channel->is_readable == FALSE); do { gint status; gchar *command = NULL, *value = NULL, **args; do { status = g_io_channel_read_line_string (channel, string, NULL, &err); while (gdk_events_pending ()) gtk_main_iteration (); } while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) { if (err) { g_printerr ("yad_notification_handle_stdin(): %s\n", err->message); g_error_free (err); err = NULL; } /* stop handling but not exit */ g_io_channel_shutdown (channel, TRUE, NULL); return FALSE; } strip_new_line (string->str); if (!string->str[0]) continue; args = g_strsplit (string->str, ":", 2); command = g_strdup (args[0]); if (args[1]) value = g_strdup (args[1]); g_strfreev (args); if (value) g_strstrip (value); if (!g_ascii_strcasecmp (command, "icon") && value) { g_free (icon); icon = g_strdup (value); if (gtk_status_icon_get_visible (status_icon) && gtk_status_icon_is_embedded (status_icon)) set_icon (); } else if (!g_ascii_strcasecmp (command, "tooltip")) { if (g_utf8_validate (value, -1, NULL)) { gchar *message = g_strcompress (value); if (!options.data.no_markup) gtk_status_icon_set_tooltip_markup (status_icon, message); else gtk_status_icon_set_tooltip_text (status_icon, message); g_free (message); } else g_printerr (_("Invalid UTF-8 in tooltip!\n")); } else if (!g_ascii_strcasecmp (command, "visible")) { #if !GTK_CHECK_VERSION(2,22,0) if (!g_ascii_strcasecmp (value, "blink")) { gboolean state = gtk_status_icon_get_blinking (status_icon); gtk_status_icon_set_blinking (status_icon, !state); } else #endif if (!g_ascii_strcasecmp (value, "false")) { gtk_status_icon_set_visible (status_icon, FALSE); #if !GTK_CHECK_VERSION(2,22,0) gtk_status_icon_set_blinking (status_icon, FALSE); #endif } else { gtk_status_icon_set_visible (status_icon, TRUE); #if !GTK_CHECK_VERSION(2,22,0) gtk_status_icon_set_blinking (status_icon, FALSE); #endif } } else if (!g_ascii_strcasecmp (command, "action")) { g_free (action); if (value) action = g_strdup (value); } else if (!g_ascii_strcasecmp (command, "quit")) { exit_code = YAD_RESPONSE_OK; gtk_main_quit (); } else if (!g_ascii_strcasecmp (command, "menu")) { if (value) parse_menu_str (value); } else g_printerr (_("Unknown command '%s'\n"), command); g_free (command); g_free (value); } while (g_io_channel_get_buffer_condition (channel) == G_IO_IN); g_string_free (string, TRUE); } if ((condition & G_IO_HUP) != 0) { g_io_channel_shutdown (channel, TRUE, NULL); gtk_main_quit (); return FALSE; } return TRUE; }
static int init(struct sr_input *in, const char *filename) { int res; struct context *ctx; const char *param; GIOStatus status; gsize i, term_pos; char probe_name[SR_MAX_PROBENAME_LEN + 1]; struct sr_probe *probe; char **columns; gsize num_columns; char *ptr; if (!(ctx = g_try_malloc0(sizeof(struct context)))) { sr_err("Context malloc failed."); return SR_ERR_MALLOC; } /* Create a virtual device. */ in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL); in->internal = ctx; /* Set default samplerate. */ ctx->samplerate = 0; /* * Enable auto-detection of the number of probes in multi column mode * and enforce the specification of the number of probes in single * column mode. */ ctx->num_probes = 0; /* Set default delimiter. */ if (!(ctx->delimiter = g_string_new(","))) { sr_err("Delimiter malloc failed."); free_context(ctx); return SR_ERR_MALLOC; } /* * Set default comment prefix. Note that an empty comment prefix * disables removing of comments. */ if (!(ctx->comment = g_string_new(""))) { sr_err("Comment malloc failed."); free_context(ctx); return SR_ERR_MALLOC; } /* Enable multi column mode by default. */ ctx->multi_column_mode = TRUE; /* Use first column as default single column number. */ ctx->single_column = 0; /* * In multi column mode start parsing sample data at the first column * and in single column mode at the first bit. */ ctx->first_probe = 0; /* Start at the beginning of the file. */ ctx->start_line = 1; /* Disable the usage of the first line as header by default. */ ctx->header = FALSE; /* Set default format for single column mode. */ ctx->format = FORMAT_BIN; if (!(ctx->buffer = g_string_new(""))) { sr_err("Line buffer malloc failed."); free_context(ctx); return SR_ERR_MALLOC; } if (in->param) { if ((param = g_hash_table_lookup(in->param, "samplerate"))) { res = sr_parse_sizestring(param, &ctx->samplerate); if (res != SR_OK) { sr_err("Invalid samplerate: %s.", param); free_context(ctx); return SR_ERR_ARG; } } if ((param = g_hash_table_lookup(in->param, "numprobes"))) ctx->num_probes = g_ascii_strtoull(param, NULL, 10); if ((param = g_hash_table_lookup(in->param, "delimiter"))) { if (!strlen(param)) { sr_err("Delimiter must be at least one character."); free_context(ctx); return SR_ERR_ARG; } if (!g_ascii_strcasecmp(param, "\\t")) g_string_assign(ctx->delimiter, "\t"); else g_string_assign(ctx->delimiter, param); } if ((param = g_hash_table_lookup(in->param, "comment"))) g_string_assign(ctx->comment, param); if ((param = g_hash_table_lookup(in->param, "single-column"))) { ctx->single_column = g_ascii_strtoull(param, &ptr, 10); ctx->multi_column_mode = FALSE; if (param == ptr) { sr_err("Invalid single-colum number: %s.", param); free_context(ctx); return SR_ERR_ARG; } } if ((param = g_hash_table_lookup(in->param, "first-probe"))) ctx->first_probe = g_ascii_strtoull(param, NULL, 10); if ((param = g_hash_table_lookup(in->param, "startline"))) { ctx->start_line = g_ascii_strtoull(param, NULL, 10); if (ctx->start_line < 1) { sr_err("Invalid start line: %s.", param); free_context(ctx); return SR_ERR_ARG; } } if ((param = g_hash_table_lookup(in->param, "header"))) ctx->header = sr_parse_boolstring(param); if ((param = g_hash_table_lookup(in->param, "format"))) { if (!g_ascii_strncasecmp(param, "bin", 3)) { ctx->format = FORMAT_BIN; } else if (!g_ascii_strncasecmp(param, "hex", 3)) { ctx->format = FORMAT_HEX; } else if (!g_ascii_strncasecmp(param, "oct", 3)) { ctx->format = FORMAT_OCT; } else { sr_err("Invalid format: %s.", param); free_context(ctx); return SR_ERR; } } } if (ctx->multi_column_mode) ctx->first_column = ctx->first_probe; else ctx->first_column = ctx->single_column; if (!ctx->multi_column_mode && !ctx->num_probes) { sr_err("Number of probes needs to be specified in single column mode."); free_context(ctx); return SR_ERR; } if (!(ctx->channel = g_io_channel_new_file(filename, "r", NULL))) { sr_err("Input file '%s' could not be opened.", filename); free_context(ctx); return SR_ERR; } while (TRUE) { ctx->line_number++; status = g_io_channel_read_line_string(ctx->channel, ctx->buffer, &term_pos, NULL); if (status == G_IO_STATUS_EOF) { sr_err("Input file is empty."); free_context(ctx); return SR_ERR; } if (status != G_IO_STATUS_NORMAL) { sr_err("Error while reading line %zu.", ctx->line_number); free_context(ctx); return SR_ERR; } if (ctx->start_line > ctx->line_number) { sr_spew("Line %zu skipped.", ctx->line_number); continue; } /* Remove line termination character(s). */ g_string_truncate(ctx->buffer, term_pos); if (!ctx->buffer->len) { sr_spew("Blank line %zu skipped.", ctx->line_number); continue; } /* Remove trailing comment. */ strip_comment(ctx->buffer, ctx->comment); if (ctx->buffer->len) break; sr_spew("Comment-only line %zu skipped.", ctx->line_number); } /* * In order to determine the number of columns parse the current line * without limiting the number of columns. */ if (!(columns = parse_line(ctx, -1))) { sr_err("Error while parsing line %zu.", ctx->line_number); free_context(ctx); return SR_ERR; } num_columns = g_strv_length(columns); /* Ensure that the first column is not out of bounds. */ if (!num_columns) { sr_err("Column %zu in line %zu is out of bounds.", ctx->first_column, ctx->line_number); g_strfreev(columns); free_context(ctx); return SR_ERR; } if (ctx->multi_column_mode) { /* * Detect the number of probes in multi column mode * automatically if not specified. */ if (!ctx->num_probes) { ctx->num_probes = num_columns; sr_info("Number of auto-detected probes: %zu.", ctx->num_probes); } /* * Ensure that the number of probes does not exceed the number * of columns in multi column mode. */ if (num_columns < ctx->num_probes) { sr_err("Not enough columns for desired number of probes in line %zu.", ctx->line_number); g_strfreev(columns); free_context(ctx); return SR_ERR; } } for (i = 0; i < ctx->num_probes; i++) { if (ctx->header && ctx->multi_column_mode && strlen(columns[i])) snprintf(probe_name, sizeof(probe_name), "%s", columns[i]); else snprintf(probe_name, sizeof(probe_name), "%zu", i); probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, probe_name); if (!probe) { sr_err("Probe creation failed."); free_context(ctx); g_strfreev(columns); return SR_ERR; } in->sdi->probes = g_slist_append(in->sdi->probes, probe); } g_strfreev(columns); /* * Calculate the minimum buffer size to store the sample data of the * probes. */ ctx->sample_buffer_size = (ctx->num_probes + 7) >> 3; if (!(ctx->sample_buffer = g_try_malloc(ctx->sample_buffer_size))) { sr_err("Sample buffer malloc failed."); free_context(ctx); return SR_ERR_MALLOC; } return SR_OK; }
static int loadfile(struct sr_input *in, const char *filename) { int res; struct context *ctx; struct sr_datafeed_packet packet; struct sr_datafeed_meta meta; struct sr_config *cfg; GIOStatus status; gboolean read_new_line; gsize term_pos; char **columns; gsize num_columns; int max_columns; (void)filename; ctx = in->internal; /* Send header packet to the session bus. */ std_session_send_df_header(in->sdi, LOG_PREFIX); if (ctx->samplerate) { packet.type = SR_DF_META; packet.payload = &meta; cfg = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(ctx->samplerate)); meta.config = g_slist_append(NULL, cfg); sr_session_send(in->sdi, &packet); sr_config_free(cfg); } read_new_line = FALSE; /* Limit the number of columns to parse. */ if (ctx->multi_column_mode) max_columns = ctx->num_probes; else max_columns = 1; while (TRUE) { /* * Skip reading a new line for the first time if the last read * line was not a header because the sample data is not parsed * yet. */ if (read_new_line || ctx->header) { ctx->line_number++; status = g_io_channel_read_line_string(ctx->channel, ctx->buffer, &term_pos, NULL); if (status == G_IO_STATUS_EOF) break; if (status != G_IO_STATUS_NORMAL) { sr_err("Error while reading line %zu.", ctx->line_number); free_context(ctx); return SR_ERR; } /* Remove line termination character(s). */ g_string_truncate(ctx->buffer, term_pos); } read_new_line = TRUE; if (!ctx->buffer->len) { sr_spew("Blank line %zu skipped.", ctx->line_number); continue; } /* Remove trailing comment. */ strip_comment(ctx->buffer, ctx->comment); if (!ctx->buffer->len) { sr_spew("Comment-only line %zu skipped.", ctx->line_number); continue; } if (!(columns = parse_line(ctx, max_columns))) { sr_err("Error while parsing line %zu.", ctx->line_number); free_context(ctx); return SR_ERR; } num_columns = g_strv_length(columns); /* Ensure that the first column is not out of bounds. */ if (!num_columns) { sr_err("Column %zu in line %zu is out of bounds.", ctx->first_column, ctx->line_number); g_strfreev(columns); free_context(ctx); return SR_ERR; } /* * Ensure that the number of probes does not exceed the number * of columns in multi column mode. */ if (ctx->multi_column_mode && num_columns < ctx->num_probes) { sr_err("Not enough columns for desired number of probes in line %zu.", ctx->line_number); g_strfreev(columns); free_context(ctx); return SR_ERR; } if (ctx->multi_column_mode) res = parse_multi_columns(columns, ctx); else res = parse_single_column(columns[0], ctx); if (res != SR_OK) { g_strfreev(columns); free_context(ctx); return SR_ERR; } g_strfreev(columns); /* * TODO: Parse sample numbers / timestamps and use it for * decompression. */ /* Send sample data to the session bus. */ res = send_samples(in->sdi, ctx->sample_buffer, ctx->sample_buffer_size, 1); if (res != SR_OK) { sr_err("Sending samples failed."); free_context(ctx); return SR_ERR; } } /* Send end packet to the session bus. */ packet.type = SR_DF_END; sr_session_send(in->sdi, &packet); free_context(ctx); return SR_OK; }
static void rspamd_process_file (const gchar *fname) { struct rspamd_task *task; GIOChannel *f; GError *err = NULL; GString *buf; struct received_header rh; gdouble t1, t2; f = g_io_channel_new_file (fname, "r", &err); if (!f) { rspamd_fprintf (stderr, "cannot open %s: %e\n", fname, err); g_error_free (err); return; } g_io_channel_set_encoding (f, NULL, NULL); buf = g_string_sized_new (8192); task = g_malloc0 (sizeof (*task)); task->task_pool = rspamd_mempool_new (rspamd_mempool_suggest_size (), "test"); while (g_io_channel_read_line_string (f, buf, NULL, &err) == G_IO_STATUS_NORMAL) { while (buf->len > 0 && g_ascii_isspace (buf->str[buf->len - 1])) { buf->len --; } t1 = rspamd_get_virtual_ticks (); rspamd_smtp_recieved_parse (task, buf->str, buf->len, &rh); t2 = rspamd_get_virtual_ticks (); total_time += t2 - t1; total_parsed ++; if (rh.addr) { total_real_ip ++; } if (rh.real_hostname) { total_real_host ++; } if (rh.type != RSPAMD_RECEIVED_UNKNOWN) { total_known_proto ++; } if (rh.by_hostname || rh.timestamp > 0) { total_valid ++; } if (rh.timestamp != 0) { total_known_ts ++; } } if (err) { rspamd_fprintf (stderr, "cannot read %s: %e\n", fname, err); g_error_free (err); } g_io_channel_unref (f); g_string_free (buf, TRUE); rspamd_mempool_delete (task->task_pool); g_free (task); }
void test_iochannel (void) { GIOChannel *gio_r, *gio_w ; GString *buffer; char *filename; char *srcdir = getenv ("srcdir"); gint rlength = 0; glong wlength = 0; gsize length_out; const gchar encoding[] = "EUC-JP"; GIOStatus status; GError *error = NULL; if (!srcdir) srcdir = "."; filename = g_build_filename (srcdir, "iochannel-test-infile", NULL); gio_r = g_io_channel_new_file (filename, "r", &error); gcut_assert_error (error); gio_w = g_io_channel_new_file ("iochannel-test-outfile", "w", &error); gcut_assert_error (error); g_io_channel_set_encoding (gio_r, encoding, &error); gcut_assert_error (error); g_io_channel_set_buffer_size (gio_r, BUFFER_SIZE); status = g_io_channel_set_flags (gio_r, G_IO_FLAG_NONBLOCK, &error); gcut_assert_error (error); buffer = g_string_sized_new (BUFFER_SIZE); while (TRUE) { do { status = g_io_channel_read_line_string (gio_r, buffer, NULL, &error); gcut_assert_error (error); } while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; rlength += buffer->len; do { status = g_io_channel_write_chars (gio_w, buffer->str, buffer->len, &length_out, &error); gcut_assert_error (error); } while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; wlength += length_out; if (length_out < buffer->len) g_warning ("Only wrote part of the line."); g_string_truncate (buffer, 0); } switch (status) { case G_IO_STATUS_EOF: break; case G_IO_STATUS_ERROR: gcut_assert_error(error); break; default: g_warning ("Abnormal exit from write loop."); break; } do { status = g_io_channel_flush (gio_w, &error); gcut_assert_error (error); } while (status == G_IO_STATUS_AGAIN); cut_assert_equal_int (G_IO_STATUS_NORMAL, status); g_io_channel_unref(gio_r); g_io_channel_unref(gio_w); test_small_writes (); }
static void xmms_sid_get_songlength (xmms_xform_t *xform) { xmms_config_property_t *config; const gchar *tmp, *md5sum, *songlength_path; gint subtune = 1; GIOChannel* io; GString *buf; g_return_if_fail (xform); config = xmms_xform_config_lookup (xform, "songlength_path"); g_return_if_fail (config); songlength_path = xmms_config_property_get_string (config); if (!songlength_path[0]) return; if (xmms_xform_metadata_get_str (xform, "subtune", &tmp)) { subtune = atoi (tmp); } if (!xmms_xform_metadata_get_str (xform, "HVSCfingerprint", &md5sum)) { return; } io = g_io_channel_new_file (songlength_path, "r", NULL); if (!io) { xmms_log_error ("Unable to load songlengths database '%s'", songlength_path); return; } buf = g_string_new (""); while (g_io_channel_read_line_string (io, buf, NULL, NULL) == G_IO_STATUS_NORMAL) { if (buf->len > 33 && g_ascii_strncasecmp (buf->str, md5sum, 32) == 0) { gint cur = 0; gchar *b; b = buf->str + 33; while (*b) { gint min, sec; /* read timestamp */ if (sscanf (b, "%d:%d", &min, &sec) != 2) { /* no more timestamps on this line */ break; } else { cur++; } if (cur == subtune) { const gchar *metakey; gchar ms_str[10 + 1]; /* LONG_MAX in str, \w NULL */ glong ms; ms = (min * 60 + sec) * 1000; metakey = XMMS_MEDIALIB_ENTRY_PROPERTY_DURATION; xmms_xform_metadata_set_int (xform, metakey, ms); if (g_snprintf (ms_str, 10 + 1, "%ld", ms) > 0) { metakey = XMMS_MEDIALIB_ENTRY_PROPERTY_STARTMS; xmms_xform_metadata_set_str (xform, metakey, "0"); metakey = XMMS_MEDIALIB_ENTRY_PROPERTY_STOPMS; xmms_xform_metadata_set_str (xform, metakey, ms_str); } goto done; } /* forward to next possible timestamp */ b = strchr (b, ' '); if (!b) { /* no more timestamps on this line */ break; } b++; } } } xmms_log_info ("Couldn't find sid tune in songlength.txt"); done: g_io_channel_unref (io); }
GSList * parseTestFile (gchar * filename) { /* open test file */ GIOChannel *testFile = g_io_channel_new_file (filename, "r", NULL); if (testFile == NULL) return NULL; GSList *testPairs = NULL; GString *line = g_string_new(NULL); int linecount = 0; while (g_io_channel_read_line_string (testFile, line, NULL, NULL) == G_IO_STATUS_NORMAL) { linecount++; /* strip of comments and whitespace */ for (int i = 0; i < line->len; i++) { if (line->str[i] == '#') { g_string_truncate (line, i); break; } } g_strstrip (line->str); /* skip line if blank */ if (strlen (line->str) == 0) continue; /* initialize test pair */ TestPair *testPair = g_malloc (sizeof (TestPair)); testPair->linenr = linecount; testPair->line = g_strdup (line->str); testPair->keyevent = NULL; testPair->commands = NULL; TIL_Keyevent *keyevent = NULL; /*gboolean hit = FALSE;*/ TIL_Keyevent_Type type; gboolean autorep = FALSE; gint modifiers = 0; /* extract the fields */ gchar **fields = g_strsplit (line->str, "::", 0); if (fields[0] == NULL || fields[1] == NULL) goto parseError; /* * FIELD 1 - EVENT TYPE */ g_strstrip (fields[0]); if (g_ascii_strcasecmp (fields[0], "press") == 0) { type = TIL_Event_Pressed; } else if (g_ascii_strcasecmp (fields[0], "pressrep") == 0) { type = TIL_Event_Pressed; autorep = TRUE; } else if (g_ascii_strcasecmp (fields[0], "release") == 0) { type = TIL_Event_Released; } /*else if (g_ascii_strcasecmp (fields[0], "hit") == 0) { type = TIL_Event_Pressed; hit = TRUE; }*/ else { goto parseError; } /* * FIELD 2 - KEY */ char *keystring = g_strstrip (fields[1]); TIL_Keycode code = TIL_Key_unknown; GString *text = g_string_new (""); gboolean hasNonPrintable = FALSE; /* TRUE <=> the key sequence has non-printable chars */ while (*keystring != '\0') { gunichar c = g_utf8_get_char_validated (keystring, -1); if (!g_unichar_validate (c)) goto parseError; keystring = g_utf8_next_char (keystring); if (c == (gunichar) '<' && *keystring != '\0') { /* an escaped key */ gchar *esckey = keystring; /* go to the next '>' */ gunichar ch; do { ch = g_utf8_get_char_validated (keystring, -1); if (!g_unichar_validate (ch)) goto parseError; keystring = g_utf8_next_char (keystring); } while (*keystring != '\0' && ch != (gunichar) '>'); if (*keystring == '\0' && ch != (gunichar) '>') { /* string not finished with '>' */ goto parseError; } /* overwrite the '>' with NULL character, so that esckey contains the string * inside the brackets */ *(keystring - 1) = '\0'; TIL_Keycode tempcode = unescapeKey (esckey); if (tempcode == TIL_Key_unknown) goto parseError; c = keyToChar (tempcode); if (c == 0) { /* non-printable character */ if (code != TIL_Key_unknown) /* we already have a key - this is not valid */ goto parseError; hasNonPrintable = TRUE; code = tempcode; } } if (c != 0) { if (hasNonPrintable) /* non-printable characters and text together is not valid */ goto parseError; g_string_append_unichar (text, c); } } /* * FIELD 3 - MODIFIERS */ gchar **modv = g_strsplit (fields[2], ",", 0); gint i = 0; while (modv[i] != NULL) { g_strstrip (modv[i]); switch (g_ascii_toupper (modv[i][0])) { case 'S': modifiers |= TIL_Mod_Shift; break; case 'C': modifiers |= TIL_Mod_Control; break; case 'A': modifiers |= TIL_Mod_Alt; break; case 'M': modifiers |= TIL_Mod_Meta; break; default: break; } i++; } g_strfreev (modv); /* * CONSTRUCT THE KEY EVENTS */ keyevent = g_malloc (sizeof (TIL_Keyevent) + text->len + 1); keyevent->type = type; keyevent->autorep = autorep; keyevent->modifiers = modifiers; keyevent->keycode = code; strcpy (keyevent->text, text->str); /* * REMAINING FIELDS: COMMANDS */ GSList *cmds = NULL; int numCmds = 0; if (fields[3] != NULL) { /* ignore the last field if it consists only of white space */ g_strstrip (fields[3]); if (*fields[3] != '\0') { for (int i = 3; fields[i] != NULL; i++) { TIL_Cmd *cmd = cmdFromString (fields[i]); if (cmd == NULL) { GSList *work = cmds; while (work != NULL) { g_free(work->data); work = g_slist_next (work); } goto parseError; } cmds = g_slist_append (cmds, cmd); numCmds++; } } } /* * BUILD THE TEST PAIR */ testPair->keyevent = keyevent; testPair->commands = g_malloc (sizeof (TIL_Cmd *) * (numCmds + 1)); GSList *work = cmds; for (int j = 0; j < numCmds; j++) { testPair->commands[j] = work->data; work = g_slist_next (work); } testPair->commands[numCmds] = NULL; g_strfreev (fields); g_slist_free (cmds); testPairs = g_slist_append (testPairs, testPair); continue; parseError: g_free (keyevent); testPairs = g_slist_append (testPairs, testPair); } /* end while */ /* cleanup */ g_io_channel_shutdown (testFile, FALSE, NULL); g_io_channel_unref (testFile); g_string_free (line, FALSE); return testPairs; }
/*! \brief read_log_header() First we read the first line, try to determine if the delimiter is a COMMA, or a TAB. \param iochannel is the iochannel that represents the input file \param log_info is the the Log_Info structure */ G_MODULE_EXPORT void read_log_header(GIOChannel *iochannel, Log_Info *log_info ) { GString *a_line = g_string_new("\0"); GIOStatus status = G_IO_STATUS_ERROR; gchar *delimiter = NULL; gchar **fields = NULL; gint num_fields = 0; GArray *array = NULL; gconstpointer *object = NULL; gint i = 0; Rtv_Map *rtv_map; extern gconstpointer *global_data; rtv_map = DATA_GET(global_data,"rtv_map"); read_again: status = g_io_channel_read_line_string(iochannel,a_line,NULL,NULL); if (status == G_IO_STATUS_NORMAL) /* good read */ { /* This searched for a quoted string which should be the * ecu signature. pre 0.9.15 versions of megatunix shoved the * internal name of the firmware in there which is a problem as * it makes the logs locked to megatunix which is a bad thing * as it hurts interoperability. 0.9.16+ changes this to use * the REAL signature returned by the firmware. */ if (g_strrstr(a_line->str,"\"") != NULL) { log_info->signature = g_strdup(g_strstrip(g_strdelimit(a_line->str,"\"\n\r",' '))); /*printf(_("LOG signature is \"%s\"\n"),log_info->signature);*/ if (DATA_GET(global_data,"offline")) { printf("rtv_map->applicable_signatures is \"%s\"\n",rtv_map->applicable_signatures); if (rtv_map->applicable_signatures) { if (strstr(rtv_map->applicable_signatures,log_info->signature) != NULL) printf(_("Good this firmware is compatible with the firmware we're using\n")); else printf(_("mismatch between datalog and current firmware, playback via full gui will probably not work like you expected\n")); } } goto read_again; } if (g_strrstr(a_line->str,",") != NULL) delimiter = g_strdup(","); else if (g_strrstr(a_line->str,"\t") != NULL) delimiter = g_strdup("\t"); /* Store delimiter in structure */ log_info->delimiter = g_strdup(delimiter); /* Store field names as well... * log_info->fields is a string vector (char **) * that is NULL terminated thanks to g_strsplit(void) */ fields = parse_keys(a_line->str,&num_fields,delimiter); log_info->field_count = num_fields; /* Create objects, arrays and storage points... */ for (i=0;i<num_fields;i++) { array = NULL; object = g_new0(gconstpointer, 1); array = g_array_sized_new(FALSE,TRUE,sizeof(gfloat),4096); DATA_SET(object,"data_array",(gpointer)array); g_free(DATA_GET(object,"lview_name")); DATA_SET_FULL(object,"lview_name",g_strdup(g_strstrip(fields[i])),g_free); g_ptr_array_add(log_info->log_list,object); } /* Enable parameter selection button */ gtk_widget_set_sensitive(lookup_widget("logviewer_select_params_button"), TRUE); OBJ_SET(lookup_widget("logviewer_trace_darea"),"log_info",(gpointer)log_info); } g_free(delimiter); }
/*! \brief read_log_data() reads the log data and sticks it into the arrays in the log_info structure \param iochannel is the data source \param log_info is the pointer to log information struct */ G_MODULE_EXPORT void read_log_data(GIOChannel *iochannel, Log_Info *log_info) { GString *a_line = g_string_new("\0"); gchar **data = NULL; guint i = 0; gint x = 0; gint precision = 0; gchar ** vector = NULL; GArray *tmp_array = NULL; gfloat val = 0.0; gconstpointer *object = NULL; while(g_io_channel_read_line_string(iochannel,a_line,NULL,NULL) == G_IO_STATUS_NORMAL) { if (g_strrstr(a_line->str,"MARK")) { /* Should insert some sort of marker at this index * in the data arrays... */ printf(_("MARK found in logfile. MTX doesn't do anything with these yet...!\n")); continue; } data = g_strsplit(a_line->str,log_info->delimiter,0); if ((!g_ascii_isdigit(data[0][0])) && (!g_ascii_isdigit(data[0][1]))) { printf(_("non numerical line detected\n")); printf("text %s\n",data[0]); g_strfreev(data); continue; } if (g_strv_length(data) != log_info->field_count) { printf(_("Datalog error, field count assertion failure\nExpected %i fields, got %i instead, tossing this record!\n"),log_info->field_count,g_strv_length(data)); g_strfreev(data); continue; } for (i=0;i<(log_info->field_count);i++) { object = g_ptr_array_index(log_info->log_list, i); tmp_array = (GArray *)DATA_GET(object,"data_array"); val = (gfloat)g_ascii_strtod(g_strdelimit(data[i],",.",'.'),NULL); g_array_append_val(tmp_array,val); /*printf("data[%i]=%s\n",i,data[i]);*/ if (x == 0) /* only check first line */ { if (g_strrstr(data[i], ".") != NULL) { vector = g_strsplit(data[i],".",-1); precision = strlen(vector[1]); g_strfreev(vector); DATA_SET(object,"precision",GINT_TO_POINTER(precision)); } } } g_strfreev(data); x++; } }
gint main (gint argc, gchar * argv[]) { GIOChannel *gio_r, *gio_w ; GError *gerr = NULL; GString *buffer; char *filename; char *srcdir = getenv ("srcdir"); gint rlength = 0; glong wlength = 0; gsize length_out; const gchar encoding[] = "EUC-JP"; GIOStatus status; if (!srcdir) srcdir = "."; filename = g_strconcat (srcdir, G_DIR_SEPARATOR_S, "iochannel-test-infile", NULL); setbuf (stdout, NULL); /* For debugging */ gio_r = g_io_channel_new_file (filename, "r", &gerr); if (gerr) { g_warning ("Unable to open file %s: %s", filename, gerr->message); g_clear_error (&gerr); return 1; } gio_w = g_io_channel_new_file ("iochannel-test-outfile", "w", &gerr); if (gerr) { g_warning ("Unable to open file %s: %s", "iochannel-test-outfile", gerr->message); g_clear_error (&gerr); return 1; } g_io_channel_set_encoding (gio_r, encoding, &gerr); if (gerr) { g_warning ("%s", gerr->message); /* Keep going if this is just a case of iconv not supporting EUC-JP, see bug 428048 */ if (gerr->code != G_CONVERT_ERROR_NO_CONVERSION) return 1; g_clear_error (&gerr); } g_io_channel_set_buffer_size (gio_r, BUFFER_SIZE); status = g_io_channel_set_flags (gio_r, G_IO_FLAG_NONBLOCK, &gerr); if (status == G_IO_STATUS_ERROR) { g_warning ("%s", gerr->message); g_clear_error (&gerr); } buffer = g_string_sized_new (BUFFER_SIZE); while (TRUE) { do status = g_io_channel_read_line_string (gio_r, buffer, NULL, &gerr); while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; rlength += buffer->len; do status = g_io_channel_write_chars (gio_w, buffer->str, buffer->len, &length_out, &gerr); while (status == G_IO_STATUS_AGAIN); if (status != G_IO_STATUS_NORMAL) break; wlength += length_out; if (length_out < buffer->len) g_warning ("Only wrote part of the line."); #ifdef VERBOSE g_print ("%s", buffer->str); #endif g_string_truncate (buffer, 0); } switch (status) { case G_IO_STATUS_EOF: break; case G_IO_STATUS_ERROR: g_warning ("%s", gerr->message); g_clear_error (&gerr); break; default: g_warning ("Abnormal exit from write loop."); break; } do status = g_io_channel_flush (gio_w, &gerr); while (status == G_IO_STATUS_AGAIN); if (status == G_IO_STATUS_ERROR) { g_warning ("%s", gerr->message); g_clear_error (&gerr); } #ifdef VERBOSE g_print ("read %d bytes, wrote %ld bytes\n", rlength, wlength); #endif g_io_channel_unref(gio_r); g_io_channel_unref(gio_w); test_small_writes (); return 0; }