static gboolean do_seek (GtkWidget * widget, gboolean flush, gboolean segment) { gint64 start, stop; gboolean res = FALSE; GstEvent *s_event; gdouble rate; GTimeVal tv; gboolean valid; gdouble new_range; if (segment) new_range = gtk_range_get_value (GTK_RANGE (widget)); else { new_range = (gdouble) RANGE_PREC; cur_time = -1; } valid = prev_time != -1; GST_DEBUG ("flush %d, segment %d, valid %d", flush, segment, valid); if (new_range == cur_range) return FALSE; prev_time = cur_time; prev_range = cur_range; cur_range = new_range; g_get_current_time (&tv); cur_time = GST_TIMEVAL_TO_TIME (tv); if (!valid) return FALSE; GST_DEBUG ("cur: %lf, %" GST_TIME_FORMAT, cur_range, GST_TIME_ARGS (cur_time)); GST_DEBUG ("prev: %lf, %" GST_TIME_FORMAT, prev_range, GST_TIME_ARGS (prev_time)); diff = cur_time - prev_time; GST_DEBUG ("diff: %" GST_TIME_FORMAT, GST_TIME_ARGS (diff)); start = prev_range * duration / RANGE_PREC; /* play 50 milliseconds */ stop = segment ? cur_range * duration / RANGE_PREC : duration; if (start == stop) return FALSE; if (segment) rate = (stop - start) / (gdouble) diff; else rate = cur_speed; if (start > stop) { gint64 tmp; tmp = start; start = stop; stop = tmp; } if (rate == 0.0) return TRUE; GST_DEBUG ("seek to %" GST_TIME_FORMAT " -- %" GST_TIME_FORMAT ", rate %lf" " on element %s", GST_TIME_ARGS (start), GST_TIME_ARGS (stop), rate, GST_ELEMENT_NAME (pipeline)); s_event = gst_event_new_seek (rate, GST_FORMAT_TIME, (flush ? GST_SEEK_FLAG_FLUSH : 0) | (segment ? GST_SEEK_FLAG_SEGMENT : 0), GST_SEEK_TYPE_SET, start, GST_SEEK_TYPE_SET, stop); res = gst_element_send_event (pipeline, s_event); if (!res) g_print ("seek failed\n"); gst_element_get_state (pipeline, NULL, NULL, GST_CLOCK_TIME_NONE); return TRUE; }
void gst_multiudpsink_remove (GstMultiUDPSink * sink, const gchar * host, gint port) { GList *find; GstUDPClient udpclient; GstUDPClient *client; GTimeVal now; udpclient.host = (gchar *) host; udpclient.port = port; g_mutex_lock (&sink->client_lock); find = g_list_find_custom (sink->clients, &udpclient, (GCompareFunc) client_compare); if (!find) goto not_found; client = (GstUDPClient *) find->data; GST_DEBUG_OBJECT (sink, "found %d clients with host %s, port %d", client->refcount, host, port); client->refcount--; if (client->refcount == 0) { GInetSocketAddress *saddr = G_INET_SOCKET_ADDRESS (client->addr); GInetAddress *addr = g_inet_socket_address_get_address (saddr); GSocketFamily family = g_socket_address_get_family (G_SOCKET_ADDRESS (saddr)); GSocket *socket; /* Select socket to send from for this address */ if (family == G_SOCKET_FAMILY_IPV6 || !sink->used_socket) socket = sink->used_socket_v6; else socket = sink->used_socket; GST_DEBUG_OBJECT (sink, "remove client with host %s, port %d", host, port); g_get_current_time (&now); client->disconnect_time = GST_TIMEVAL_TO_TIME (now); if (socket && sink->auto_multicast && g_inet_address_get_is_multicast (addr)) { GError *err = NULL; if (!g_socket_leave_multicast_group (socket, addr, FALSE, sink->multi_iface, &err)) { GST_DEBUG_OBJECT (sink, "Failed to leave multicast group: %s", err->message); g_clear_error (&err); } } /* Unlock to emit signal before we delete the actual client */ g_mutex_unlock (&sink->client_lock); g_signal_emit (G_OBJECT (sink), gst_multiudpsink_signals[SIGNAL_CLIENT_REMOVED], 0, host, port); g_mutex_lock (&sink->client_lock); sink->clients = g_list_delete_link (sink->clients, find); free_client (client); } g_mutex_unlock (&sink->client_lock); return; /* ERRORS */ not_found: { g_mutex_unlock (&sink->client_lock); GST_WARNING_OBJECT (sink, "client at host %s, port %d not found", host, port); return; } }
void dlg_change_date (GthBrowser *browser, GList *file_list) { DialogData *data; GTimeVal timeval; GthDateTime *datetime; data = g_new0 (DialogData, 1); data->browser = browser; data->file_list = _g_object_list_ref (file_list); data->builder = _gtk_builder_new_from_file ("change-date.ui", "change_date"); data->settings = g_settings_new (PIX_CHANGE_DATE_SCHEMA); /* Get the widgets. */ data->dialog = GET_WIDGET ("change_date_dialog"); data->date_selector = gth_time_selector_new (); gth_time_selector_show_time (GTH_TIME_SELECTOR (data->date_selector), TRUE, TRUE); gtk_widget_show (data->date_selector); gtk_box_pack_start (GTK_BOX (GET_WIDGET ("date_selector_box")), data->date_selector, TRUE, TRUE, 0); /* Set widgets data. */ gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("change_last_modified_checkbutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_SET_LAST_MODIFIED_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("change_comment_checkbutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_SET_COMMENT_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_following_date_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_TO_FOLLOWING_DATE)); datetime = gth_datetime_new (); g_get_current_time (&timeval); if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_following_date_radiobutton")))) { char *s; s = g_settings_get_string (data->settings, PREF_CHANGE_DATE_DATE); if (strcmp (s, "") != 0) gth_datetime_from_exif_date (datetime, s); else gth_datetime_from_timeval (datetime, &timeval); g_free (s); } else gth_datetime_from_timeval (datetime, &timeval); gth_time_selector_set_value (GTH_TIME_SELECTOR (data->date_selector), datetime); gth_datetime_free (datetime); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_last_modified_date_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_TO_FILE_MODIFIED_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_creation_date_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_TO_FILE_CREATION_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_photo_original_date_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_TO_PHOTO_ORIGINAL_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("adjust_time_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_ADJUST_TIME)); if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("adjust_time_radiobutton")))) { int adjustement; int sign; int hours; int minutes; int seconds; adjustement = g_settings_get_int (data->settings, PREF_CHANGE_DATE_TIME_ADJUSTMENT); if (adjustement < 0) { sign = -1; adjustement = - adjustement; } else sign = 1; hours = adjustement / 3600; adjustement = adjustement % 3600; minutes = adjustement / 60; adjustement = adjustement % 60; seconds = adjustement; gtk_spin_button_set_value (GTK_SPIN_BUTTON (GET_WIDGET ("adjust_time_h_spinbutton")), hours); gtk_spin_button_set_value (GTK_SPIN_BUTTON (GET_WIDGET ("adjust_time_m_spinbutton")), minutes); gtk_spin_button_set_value (GTK_SPIN_BUTTON (GET_WIDGET ("adjust_time_s_spinbutton")), seconds); gtk_combo_box_set_active (GTK_COMBO_BOX (GET_WIDGET ("adjust_sign_combobox")), (sign >= 0) ? 0 : 1); } update_sensitivity (data); /* Set the signals handlers. */ g_signal_connect (G_OBJECT (data->dialog), "destroy", G_CALLBACK (dialog_destroy_cb), data); g_signal_connect_swapped (GET_WIDGET ("close_button"), "clicked", G_CALLBACK (gtk_widget_destroy), G_OBJECT (data->dialog)); g_signal_connect (GET_WIDGET ("ok_button"), "clicked", G_CALLBACK (ok_button_clicked), data); g_signal_connect (GET_WIDGET ("help_button"), "clicked", G_CALLBACK (help_button_cb), data); g_signal_connect (GET_WIDGET ("change_last_modified_checkbutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("change_comment_checkbutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("to_following_date_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("to_last_modified_date_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("to_creation_date_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("to_photo_original_date_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("adjust_time_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); /* run dialog. */ gtk_window_set_transient_for (GTK_WINDOW (data->dialog), GTK_WINDOW (browser)); gtk_window_set_modal (GTK_WINDOW (data->dialog), FALSE); gtk_widget_show (data->dialog); }
static int get_seed () { GTimeVal timeval; g_get_current_time (&timeval); return timeval.tv_usec; }
/** * gst_bus_timed_pop_filtered: * @bus: a #GstBus to pop from * @timeout: a timeout in nanoseconds, or GST_CLOCK_TIME_NONE to wait forever * @types: message types to take into account, GST_MESSAGE_ANY for any type * * Get a message from the bus whose type matches the message type mask @types, * waiting up to the specified timeout (and discarding any messages that do not * match the mask provided). * * If @timeout is 0, this function behaves like gst_bus_pop_filtered(). If * @timeout is #GST_CLOCK_TIME_NONE, this function will block forever until a * matching message was posted on the bus. * * Returns: (transfer full) (nullable): a #GstMessage matching the * filter in @types, or %NULL if no matching message was found on * the bus until the timeout expired. The message is taken from * the bus and needs to be unreffed with gst_message_unref() after * usage. * * MT safe. */ GstMessage * gst_bus_timed_pop_filtered (GstBus * bus, GstClockTime timeout, GstMessageType types) { GstMessage *message; GTimeVal now, then; gboolean first_round = TRUE; GstClockTime elapsed = 0; g_return_val_if_fail (GST_IS_BUS (bus), NULL); g_return_val_if_fail (types != 0, NULL); g_return_val_if_fail (timeout == 0 || bus->priv->poll != NULL, NULL); g_mutex_lock (&bus->priv->queue_lock); while (TRUE) { gint ret; GST_LOG_OBJECT (bus, "have %d messages", gst_atomic_queue_length (bus->priv->queue)); while ((message = gst_atomic_queue_pop (bus->priv->queue))) { if (bus->priv->poll) gst_poll_read_control (bus->priv->poll); GST_DEBUG_OBJECT (bus, "got message %p, %s from %s, type mask is %u", message, GST_MESSAGE_TYPE_NAME (message), GST_MESSAGE_SRC_NAME (message), (guint) types); if ((GST_MESSAGE_TYPE (message) & types) != 0) { /* Extra check to ensure extended types don't get matched unless * asked for */ if ((!GST_MESSAGE_TYPE_IS_EXTENDED (message)) || (types & GST_MESSAGE_EXTENDED)) { /* exit the loop, we have a message */ goto beach; } } GST_DEBUG_OBJECT (bus, "discarding message, does not match mask"); gst_message_unref (message); message = NULL; } /* no need to wait, exit loop */ if (timeout == 0) break; else if (timeout != GST_CLOCK_TIME_NONE) { if (first_round) { g_get_current_time (&then); first_round = FALSE; } else { g_get_current_time (&now); elapsed = GST_TIMEVAL_TO_TIME (now) - GST_TIMEVAL_TO_TIME (then); if (elapsed > timeout) break; } } /* only here in timeout case */ g_assert (bus->priv->poll); g_mutex_unlock (&bus->priv->queue_lock); ret = gst_poll_wait (bus->priv->poll, timeout - elapsed); g_mutex_lock (&bus->priv->queue_lock); if (ret == 0) { GST_INFO_OBJECT (bus, "timed out, breaking loop"); break; } else { GST_INFO_OBJECT (bus, "we got woken up, recheck for message"); } } beach: g_mutex_unlock (&bus->priv->queue_lock); return message; }
gboolean log_macro_expand(GString *result, gint id, gboolean escape, const LogTemplateOptions *opts, gint tz, gint32 seq_num, const gchar *context_id, const LogMessage *msg) { switch (id) { case M_FACILITY: { /* facility */ const char *n; n = syslog_name_lookup_name_by_value(msg->pri & LOG_FACMASK, sl_facilities); if (n) { g_string_append(result, n); } else { format_uint32_padded(result, 0, 0, 16, (msg->pri & LOG_FACMASK) >> 3); } break; } case M_FACILITY_NUM: { format_uint32_padded(result, 0, 0, 10, (msg->pri & LOG_FACMASK) >> 3); break; } case M_LEVEL: { /* level */ const char *n; n = syslog_name_lookup_name_by_value(msg->pri & LOG_PRIMASK, sl_levels); if (n) { g_string_append(result, n); } else { format_uint32_padded(result, 0, 0, 10, msg->pri & LOG_PRIMASK); } break; } case M_LEVEL_NUM: { format_uint32_padded(result, 0, 0, 10, msg->pri & LOG_PRIMASK); break; } case M_TAG: { format_uint32_padded(result, 2, '0', 16, msg->pri); break; } case M_TAGS: { log_msg_print_tags(msg, result); break; } case M_BSDTAG: { format_uint32_padded(result, 0, 0, 10, (msg->pri & LOG_PRIMASK)); g_string_append_c(result, (((msg->pri & LOG_FACMASK) >> 3) + 'A')); break; } case M_PRI: { format_uint32_padded(result, 0, 0, 10, msg->pri); break; } case M_HOST: { if (msg->flags & LF_CHAINED_HOSTNAME) { /* host */ const gchar *p1, *p2; int remaining, length; gssize host_len; const gchar *host = log_msg_get_value(msg, LM_V_HOST, &host_len); p1 = memchr(host, '@', host_len); if (p1) p1++; else p1 = host; remaining = host_len - (p1 - host); p2 = memchr(p1, '/', remaining); length = p2 ? p2 - p1 : host_len - (p1 - host); result_append(result, p1, length, escape); } else { _result_append_value(result, msg, LM_V_HOST, escape); } break; } case M_SDATA: if (escape) { GString *sdstr = g_string_sized_new(0); log_msg_append_format_sdata(msg, sdstr, seq_num); result_append(result, sdstr->str, sdstr->len, TRUE); g_string_free(sdstr, TRUE); } else { log_msg_append_format_sdata(msg, result, seq_num); } break; case M_MSGHDR: { gssize len; const gchar *p; p = log_msg_get_value(msg, LM_V_LEGACY_MSGHDR, &len); if (len > 0) result_append(result, p, len, escape); else { /* message, complete with program name and pid */ len = result->len; _result_append_value(result, msg, LM_V_PROGRAM, escape); if (len != result->len) { const gchar *pid = log_msg_get_value(msg, LM_V_PID, &len); if (len > 0) { result_append(result, "[", 1, FALSE); result_append(result, pid, len, escape); result_append(result, "]", 1, FALSE); } result_append(result, ": ", 2, FALSE); } } break; } case M_MESSAGE: _result_append_value(result, msg, LM_V_MESSAGE, escape); break; case M_SOURCE_IP: { gchar *ip; gchar buf[MAX_SOCKADDR_STRING]; if (_is_message_source_an_ip_address(msg)) { g_sockaddr_format(msg->saddr, buf, sizeof(buf), GSA_ADDRESS_ONLY); ip = buf; } else { ip = "127.0.0.1"; } result_append(result, ip, strlen(ip), escape); break; } case M_SEQNUM: { if (seq_num) { format_uint32_padded(result, 0, 0, 10, seq_num); } break; } case M_CONTEXT_ID: { if (context_id) { result_append(result, context_id, strlen(context_id), escape); } break; } case M_RCPTID: { rcptid_append_formatted_id(result, msg->rcptid); break; } case M_RUNID: { run_id_append_formatted_id(result); break; } case M_HOSTID: { host_id_append_formatted_id(result, msg->host_id); break; } case M_UNIQID: { if (msg->rcptid) { host_id_append_formatted_id(result, msg->host_id); g_string_append(result, "@"); format_uint64_padded(result, 16, '0', 16, msg->rcptid); break; } break; } case M_LOGHOST: { const gchar *hname = get_local_hostname_fqdn(); result_append(result, hname, -1, escape); break; } case M_SYSUPTIME: { GTimeVal ct; g_get_current_time(&ct); format_uint64_padded(result, 0, 0, 10, g_time_val_diff(&ct, &app_uptime) / 1000 / 10); break; } default: { /* year, month, day */ struct tm *tm, tm_storage; gchar buf[64]; gint length; time_t t; const LogStamp *stamp; LogStamp sstamp; glong zone_ofs; guint tmp_hour; if (id >= M_TIME_FIRST && id <= M_TIME_LAST) { stamp = &msg->timestamps[LM_TS_STAMP]; } else if (id >= M_TIME_FIRST + M_RECVD_OFS && id <= M_TIME_LAST + M_RECVD_OFS) { id -= M_RECVD_OFS; stamp = &msg->timestamps[LM_TS_RECVD]; } else if (id >= M_TIME_FIRST + M_STAMP_OFS && id <= M_TIME_LAST + M_STAMP_OFS) { id -= M_STAMP_OFS; stamp = &msg->timestamps[LM_TS_STAMP]; } else if (id >= M_TIME_FIRST + M_CSTAMP_OFS && id <= M_TIME_LAST + M_CSTAMP_OFS) { GTimeVal tv; id -= M_CSTAMP_OFS; cached_g_current_time(&tv); sstamp.tv_sec = tv.tv_sec; sstamp.tv_usec = tv.tv_usec; sstamp.zone_offset = -1; stamp = &sstamp; } else { g_assert_not_reached(); break; } /* try to use the following zone values in order: * destination specific timezone, if one is specified * message specific timezone, if one is specified * local timezone */ zone_ofs = (opts->time_zone_info[tz] != NULL ? time_zone_info_get_offset(opts->time_zone_info[tz], stamp->tv_sec) : stamp->zone_offset); if (zone_ofs == -1) zone_ofs = stamp->zone_offset; t = stamp->tv_sec + zone_ofs; cached_gmtime(&t, &tm_storage); tm = &tm_storage; switch (id) { case M_WEEK_DAY_ABBREV: g_string_append_len(result, weekday_names_abbrev[tm->tm_wday], 3); break; case M_WEEK_DAY_NAME: g_string_append(result, weekday_names[tm->tm_wday]); break; case M_WEEK_DAY: format_uint32_padded(result, 0, 0, 10, tm->tm_wday + 1); break; case M_WEEK: format_uint32_padded(result, 2, '0', 10, (tm->tm_yday - (tm->tm_wday - 1 + 7) % 7 + 7) / 7); break; case M_YEAR: format_uint32_padded(result, 4, '0', 10, tm->tm_year + 1900); break; case M_YEAR_DAY: format_uint32_padded(result, 3, '0', 10, tm->tm_yday + 1); break; case M_MONTH: format_uint32_padded(result, 2, '0', 10, tm->tm_mon + 1); break; case M_MONTH_WEEK: format_uint32_padded(result, 0, 0, 10, ((tm->tm_mday / 7) + ((tm->tm_wday > 0) && ((tm->tm_mday % 7) >= tm->tm_wday)))); break; case M_MONTH_ABBREV: g_string_append_len(result, month_names_abbrev[tm->tm_mon], 3); break; case M_MONTH_NAME: g_string_append(result, month_names[tm->tm_mon]); break; case M_DAY: format_uint32_padded(result, 2, '0', 10, tm->tm_mday); break; case M_HOUR: format_uint32_padded(result, 2, '0', 10, tm->tm_hour); break; case M_HOUR12: if (tm->tm_hour < 12) tmp_hour = tm->tm_hour; else tmp_hour = tm->tm_hour - 12; if (tmp_hour == 0) tmp_hour = 12; format_uint32_padded(result, 2, '0', 10, tmp_hour); break; case M_MIN: format_uint32_padded(result, 2, '0', 10, tm->tm_min); break; case M_SEC: format_uint32_padded(result, 2, '0', 10, tm->tm_sec); break; case M_MSEC: format_uint32_padded(result, 3, '0', 10, stamp->tv_usec/1000); break; case M_USEC: format_uint32_padded(result, 6, '0', 10, stamp->tv_usec); break; case M_AMPM: g_string_append(result, tm->tm_hour < 12 ? "AM" : "PM"); break; case M_DATE: case M_STAMP: case M_ISODATE: case M_FULLDATE: case M_UNIXTIME: { gint format = id == M_DATE ? TS_FMT_BSD : id == M_ISODATE ? TS_FMT_ISO : id == M_FULLDATE ? TS_FMT_FULL : id == M_UNIXTIME ? TS_FMT_UNIX : opts->ts_format; log_stamp_append_format(stamp, result, format, zone_ofs, opts->frac_digits); break; } case M_TZ: case M_TZOFFSET: length = format_zone_info(buf, sizeof(buf), zone_ofs); g_string_append_len(result, buf, length); break; default: g_assert_not_reached(); break; } break; } } return TRUE; }
// THIS FUNCTION NEEDS TO BE BROKEN UP INTO SMALLER PIECES! void build_erlang(gchar* repo, gchar* tag, gchar* id, gchar* build_config) { // check to see if the ID has already been used GHashTable* otps = get_erlangs(); gboolean has_otp = g_hash_table_contains(otps, id); g_hash_table_destroy(otps); if(has_otp) { g_error("A version of Erlang already exists with this id: %s\n", id); } // check to see if the repo exists GHashTable* repos = get_repos(); gboolean has_repo = g_hash_table_contains(repos, repo); g_hash_table_destroy(repos); if(!has_repo) { g_error("Unconfigured repo: %s\n", repo); } // check for a valid build config if one is specified GHashTable* configs = get_configs(); if(build_config) { if(!g_hash_table_contains(configs, build_config)) { g_hash_table_destroy(configs); g_error("Unconfigured build config: %s\n", build_config); } } else { // check the default GHashTable* e8 = get_erln8(); if(g_hash_table_contains(e8, "default_config")) { build_config = strdup((gchar*)g_hash_table_lookup(e8, "default_config")); printf("%sUsing default config %s%s\n", build_config, yellow(), color_reset()); } g_hash_table_destroy(e8); } // CHECK FOR MAKE VS GMAKE const gchar* make_bin = g_getenv("MAKE_BIN"); if(make_bin == NULL) { make_bin = "make"; } gchar pattern[] = "/tmp/erln8.buildXXXXXX"; gchar* tmp = g_mkdtemp(pattern); g_debug("building in %s\n", tmp); gchar* output_root = get_config_subdir_file_name("otps",id); gchar* output_path = g_strconcat(output_root, "/dist", NULL); gchar* source_path = get_config_subdir_file_name("repos", repo); GTimeVal t; g_get_current_time(&t); gchar* ts = g_time_val_to_iso8601(&t); gchar* ld = g_strconcat("logs/build_", id, "_", ts, NULL); gchar* log_path = get_configdir_file_name(ld); // check that the branch or tag exists in the specified repo gchar* check_obj = g_strconcat("cd ", source_path, "&& git show-ref ", tag, " > /dev/null", NULL); if(system(check_obj) != 0) { g_free(check_obj); g_error("branch or tag %s does not exist in %s Git repo\n", tag, repo); } g_free(check_obj); /// check that the repo has been cloned if(!g_file_test(source_path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR)) { g_error("Missing repo for %s, which should be in %s.\nDid you forget to `erln8 --clone <repo_name>?`\n", repo, source_path); } gchar* bc = NULL; gchar* env = NULL; if(build_config != NULL) { bc = (gchar*)g_hash_table_lookup(configs, build_config); // don't drop a NULL into the middle of the command string if(bc == NULL) { bc = ""; } else { gchar* env_name = g_strconcat(build_config, "_env", NULL); env = (gchar*)g_hash_table_lookup(configs, env_name); if(env == NULL) { env = ""; } g_free(env_name); } } else { if(env == NULL) { env = ""; } } g_free(ld); g_debug("Output path = %s\n", output_path); g_debug("Source path = %s\n", source_path); g_debug("Log path = %s\n", log_path); printf("Building %s from tag/branch %s of repo %s\n", id, tag, repo); printf("Custom build config: %s\n", bc); printf("Custom build env: %s\n", env); printf("Using %s command to exec build\n", make_bin); printf("Build log: %s\n", log_path); gchar* buildcmd0 = g_strconcat(env, " cd ", source_path, " && git archive ", tag, " | (cd ", tmp, "; tar -f - -x)", NULL); gchar* buildcmd1 = g_strconcat(env, " cd ", tmp, " && ./otp_build autoconf > ", log_path, " 2>&1", NULL); gchar* buildcmd2 = g_strconcat(env, " cd ", tmp, " && ./configure --prefix=", output_path," ", bc == NULL ? "" : bc, " >> ", log_path, " 2>&1", NULL); gchar* buildcmd3 = g_strconcat(env, " cd ", tmp, " && ",make_bin," >> ", log_path, " 2>&1", NULL); gchar* buildcmd4 = g_strconcat(env, " cd ", tmp, " && ",make_bin," install >> ", log_path, " 2>&1", NULL); gchar* buildcmd5 = g_strconcat(env, " cd ", tmp, " && ",make_bin," install-docs >> ", log_path, " 2>&1", NULL); gchar* build_cmds[] = { buildcmd0, buildcmd1, buildcmd2, buildcmd3, buildcmd4, buildcmd5, NULL }; int result = 0; int i = 0; for(i = 0; i < step_count; i++) { show_build_progress(i, result); if(result != 0) { g_debug("STATUS = %d\n", result); printf("Here are the last 10 lines of the log file:\n"); gchar* tail = g_strconcat("tail -10 ", log_path, NULL); int tailresult = system(tail); if(tailresult != 0) { g_error("Cannot run tail -10 on %s\n", log_path); } g_free(tail); printf("---------------------------------------------------------\n"); g_error("Build error, please check the build logs for more details\n"); } g_debug("running %s\n", build_cmds[i]); if(!opt_dryrun) { result = system(build_cmds[i]); } else { result = 0; printf("%s\n", build_cmds[i]); } } show_build_progress(step_count, result); printf("Registering Erlang installation\n"); if(!opt_dryrun) { set_config_kv("Erlangs", id, output_root); } printf("Generating links\n"); setup_binaries(id); printf("%sBuild complete%s\n", green(), color_reset() ); g_free(buildcmd0); g_free(buildcmd1); g_free(buildcmd2); g_free(buildcmd3); g_free(buildcmd4); g_free(log_path); g_free(source_path); g_free(output_path); g_free(output_root); // destroy close to the end so the string isn't freed before it's used g_hash_table_destroy(configs); }
static GError * _client_manage_reply(struct gridd_client_s *client, MESSAGE reply) { GError *err; gint status = 0; gchar *message = NULL; if (!metaXClient_reply_simple(reply, &status, &message, NULL)) return NEWERROR(500, "Invalid reply"); switch (status / 100) { case 0: err = NEWERROR(status, "net error: %s", message); g_free(message); metautils_pclose(&(client->fd)); client->step = STATUS_FAILED; return err; case 1: /* Informational reply : */ g_get_current_time(&(client->tv_step)); client->step = REP_READING_SIZE; g_free(message); return NULL; case 2: g_get_current_time(&(client->tv_step)); client->step = (status==200) ? STATUS_OK : REP_READING_SIZE; if (client->step == STATUS_OK) { if (!client->keepalive) metautils_pclose(&(client->fd)); } g_free(message); if (client->on_reply) { if (!client->on_reply(client->ctx, reply)) return NEWERROR(500, "Handler error"); } return NULL; case 3: /* redirection */ if (status == CODE_REDIRECT) { /* Reset the context */ _client_reset_reply(client); _client_reset_cnx(client); client->sent_bytes = 0; if ((++ client->nb_redirects) > 7) { g_free(message); return NEWERROR(CODE_TOOMANY_REDIRECT, "Too many redirections"); } /* Save the current URL to avoid looping, and check * for a potential loop */ g_string_append_c(client->past_url, '|'); g_string_append(client->past_url, client->url); if (_client_looped(client, message)) { g_free(message); return NEWERROR(CODE_LOOP_REDIRECT, "Looping on redirections"); } /* Replace the URL */ memset(client->url, 0, sizeof(client->url)); g_strlcpy(client->url, message, sizeof(client->url)-1); if (NULL != (err = _client_connect(client))) { g_free(message); g_prefix_error(&err, "Redirection error: Connect error: "); return err; } g_free(message); return NULL; } /* FALLTHROUGH */ default: /* all other are considered errors */ err = NEWERROR(status, "Request error: %s", message); g_free(message); if (!client->keepalive) _client_reset_cnx(client); _client_reset_reply(client); return err; } }
static GError * _client_manage_event_in_buffer(struct gridd_client_s *client, guint8 *d, gsize ds) { ssize_t rc; switch (client->step) { case CONNECTING: g_assert(client->fd >= 0); client->step = client->request ? REQ_SENDING : CONNECTED; return NULL; case REQ_SENDING: client->step = REQ_SENDING; g_get_current_time(&(client->tv_step)); if (!client->request) return NULL; _client_reset_reply(client); /* Continue to send the request */ rc = metautils_syscall_write(client->fd, client->request->data + client->sent_bytes, client->request->len - client->sent_bytes); if (rc < 0) return (errno == EINTR || errno == EAGAIN) ? NULL : NEWERROR(errno, "write error (%s)", strerror(errno)); if (rc > 0) client->sent_bytes += rc; if (client->sent_bytes < client->request->len) return NULL; client->step = REP_READING_SIZE; case REP_READING_SIZE: client->step = REP_READING_SIZE; g_get_current_time(&(client->tv_step)); if (!client->reply) client->reply = g_byte_array_new(); if (client->reply->len < 4) { /* Continue reading the size */ rc = metautils_syscall_read(client->fd, d, ds); if (rc < 0) return (errno == EINTR || errno == EAGAIN) ? NULL : NEWERROR(errno, "read error (%s)", strerror(errno)); if (rc > 0) g_byte_array_append(client->reply, d, rc); if (client->reply->len < 4) { if (!rc) return NEWERROR(errno, "EOF!"); return NULL; } } client->size = l4v_get_size(client->reply->data); case REP_READING_DATA: client->step = REP_READING_DATA; g_get_current_time(&(client->tv_step)); rc = 0; if (client->reply->len < client->size+4) { rc = metautils_syscall_read(client->fd, d, ds); if (rc < 0) return (errno == EINTR || errno == EAGAIN) ? NULL : NEWERROR(errno, "read error (%s)", strerror(errno)); if (rc > 0) g_byte_array_append(client->reply, d, rc); } if (client->reply->len >= client->size+4) { GError *err = _client_manage_reply_data(client); if (err) { client->step = STATUS_FAILED; return err; } else { if (client->step != CONNECTING && client->step != STATUS_FAILED && client->step != STATUS_OK) { client->reply = g_byte_array_remove_range(client->reply, 0, client->size+4); client->step = REP_READING_SIZE; client->size = 0; } } } else if (!rc) return NEWERROR(errno, "EOF!"); return NULL; default: g_assert_not_reached(); return NEWERROR(0, "Invalid state"); } g_assert_not_reached(); return NEWERROR(0, "BUG unreachable code"); }
static void yahoo_backend_add_calendar (ECollectionBackend *backend) { ESource *source; ESourceBackend *extension; ESourceRegistryServer *server; const gchar *backend_name; const gchar *extension_name; const gchar *resource_id; /* XXX We could just stick a [Calendar] and [Task List] extension * into the same ESource since all other settings are exactly * the same. But it might be confusing if tweaking a setting * in your Yahoo! Calendar also gets applied to your Yahoo! * Task List in Evolution. */ backend_name = YAHOO_CALENDAR_BACKEND_NAME; server = e_collection_backend_ref_server (backend); /* Add Yahoo! Calendar */ resource_id = YAHOO_CALENDAR_RESOURCE_ID; source = e_collection_backend_new_child (backend, resource_id); e_source_set_display_name (source, _("Calendar")); extension_name = E_SOURCE_EXTENSION_CALENDAR; extension = e_source_get_extension (source, extension_name); e_source_backend_set_backend_name (extension, backend_name); extension_name = E_SOURCE_EXTENSION_ALARMS; extension = e_source_get_extension (source, extension_name); if (!e_source_alarms_get_last_notified (E_SOURCE_ALARMS (extension))) { GTimeVal today_tv; gchar *today; g_get_current_time (&today_tv); today = g_time_val_to_iso8601 (&today_tv); e_source_alarms_set_last_notified (E_SOURCE_ALARMS (extension), today); g_free (today); } yahoo_backend_config_calendar_child (backend, source); e_source_registry_server_add_source (server, source); g_object_unref (source); /* Add Yahoo! Tasks */ resource_id = YAHOO_TASKS_RESOURCE_ID; source = e_collection_backend_new_child (backend, resource_id); e_source_set_display_name (source, _("Tasks")); extension_name = E_SOURCE_EXTENSION_TASK_LIST; extension = e_source_get_extension (source, extension_name); e_source_backend_set_backend_name (extension, backend_name); yahoo_backend_config_calendar_child (backend, source); e_source_registry_server_add_source (server, source); g_object_unref (source); g_object_unref (server); }
void dlg_change_date (GthBrowser *browser, GList *file_list) { DialogData *data; GTimeVal timeval; GthDateTime *datetime; data = g_new0 (DialogData, 1); data->browser = browser; data->file_list = _g_object_list_ref (file_list); data->builder = _gtk_builder_new_from_file ("change-date.ui", "change_date"); data->settings = g_settings_new (GTHUMB_CHANGE_DATE_SCHEMA); /* Get the widgets. */ data->dialog = g_object_new (GTK_TYPE_DIALOG, "title", _("Change Date"), "transient-for", GTK_WINDOW (browser), "modal", FALSE, "destroy-with-parent", FALSE, "use-header-bar", _gtk_settings_get_dialogs_use_header (), NULL); gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area (GTK_DIALOG (data->dialog))), _gtk_builder_get_widget (data->builder, "dialog_content")); gtk_dialog_add_buttons (GTK_DIALOG (data->dialog), _GTK_LABEL_CANCEL, GTK_RESPONSE_CANCEL, _GTK_LABEL_EXECUTE, GTK_RESPONSE_OK, NULL); _gtk_dialog_add_class_to_response (GTK_DIALOG (data->dialog), GTK_RESPONSE_OK, GTK_STYLE_CLASS_SUGGESTED_ACTION); data->date_selector = gth_time_selector_new (); gth_time_selector_show_time (GTH_TIME_SELECTOR (data->date_selector), TRUE, TRUE); gtk_widget_show (data->date_selector); gtk_box_pack_start (GTK_BOX (GET_WIDGET ("date_selector_box")), data->date_selector, TRUE, TRUE, 0); /* Set widgets data. */ gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("change_last_modified_checkbutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_SET_LAST_MODIFIED_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("change_comment_checkbutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_SET_COMMENT_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_following_date_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_TO_FOLLOWING_DATE)); datetime = gth_datetime_new (); g_get_current_time (&timeval); if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_following_date_radiobutton")))) { char *s; s = g_settings_get_string (data->settings, PREF_CHANGE_DATE_DATE); if (strcmp (s, "") != 0) gth_datetime_from_exif_date (datetime, s); else gth_datetime_from_timeval (datetime, &timeval); g_free (s); } else gth_datetime_from_timeval (datetime, &timeval); gth_time_selector_set_value (GTH_TIME_SELECTOR (data->date_selector), datetime); gth_datetime_free (datetime); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_last_modified_date_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_TO_FILE_MODIFIED_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_creation_date_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_TO_FILE_CREATION_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("to_photo_original_date_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_TO_PHOTO_ORIGINAL_DATE)); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("adjust_time_radiobutton")), g_settings_get_boolean (data->settings, PREF_CHANGE_DATE_ADJUST_TIME)); if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("adjust_time_radiobutton")))) { int adjustement; int sign; int hours; int minutes; int seconds; adjustement = g_settings_get_int (data->settings, PREF_CHANGE_DATE_TIME_ADJUSTMENT); if (adjustement < 0) { sign = -1; adjustement = - adjustement; } else sign = 1; hours = adjustement / 3600; adjustement = adjustement % 3600; minutes = adjustement / 60; adjustement = adjustement % 60; seconds = adjustement; gtk_spin_button_set_value (GTK_SPIN_BUTTON (GET_WIDGET ("adjust_time_h_spinbutton")), hours); gtk_spin_button_set_value (GTK_SPIN_BUTTON (GET_WIDGET ("adjust_time_m_spinbutton")), minutes); gtk_spin_button_set_value (GTK_SPIN_BUTTON (GET_WIDGET ("adjust_time_s_spinbutton")), seconds); gtk_combo_box_set_active (GTK_COMBO_BOX (GET_WIDGET ("adjust_sign_combobox")), (sign >= 0) ? 0 : 1); } update_sensitivity (data); /* Set the signals handlers. */ g_signal_connect (G_OBJECT (data->dialog), "destroy", G_CALLBACK (dialog_destroy_cb), data); g_signal_connect_swapped (gtk_dialog_get_widget_for_response (GTK_DIALOG (data->dialog), GTK_RESPONSE_CANCEL), "clicked", G_CALLBACK (gtk_widget_destroy), G_OBJECT (data->dialog)); g_signal_connect (gtk_dialog_get_widget_for_response (GTK_DIALOG (data->dialog), GTK_RESPONSE_OK), "clicked", G_CALLBACK (ok_button_clicked), data); g_signal_connect (GET_WIDGET ("change_last_modified_checkbutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("change_comment_checkbutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("to_following_date_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("to_last_modified_date_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("to_creation_date_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("to_photo_original_date_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); g_signal_connect (GET_WIDGET ("adjust_time_radiobutton"), "clicked", G_CALLBACK (radio_button_clicked), data); /* run dialog. */ gtk_widget_show (data->dialog); }
ph_stats_t* ph_stats_new(void) { ph_stats_t *ps; guint32 framenum; frame_data *frame; guint tot_packets, tot_bytes; progdlg_t *progbar = NULL; gboolean stop_flag; int count; float progbar_val; GTimeVal start_time; gchar status_str[100]; int progbar_nextstep; int progbar_quantum; /* Initialize the data */ ps = g_new(ph_stats_t, 1); ps->tot_packets = 0; ps->tot_bytes = 0; ps->stats_tree = g_node_new(NULL); ps->first_time = 0.0; ps->last_time = 0.0; /* Update the progress bar when it gets to this value. */ progbar_nextstep = 0; /* When we reach the value that triggers a progress bar update, bump that value by this amount. */ progbar_quantum = cfile.count/N_PROGBAR_UPDATES; /* Count of packets at which we've looked. */ count = 0; /* Progress so far. */ progbar_val = 0.0f; stop_flag = FALSE; g_get_current_time(&start_time); tot_packets = 0; tot_bytes = 0; for (framenum = 1; framenum <= cfile.count; framenum++) { frame = frame_data_sequence_find(cfile.frames, framenum); /* Create the progress bar if necessary. We check on every iteration of the loop, so that it takes no longer than the standard time to create it (otherwise, for a large file, we might take considerably longer than that standard time in order to get to the next progress bar step). */ if (progbar == NULL) progbar = delayed_create_progress_dlg( "Computing", "protocol hierarchy statistics", TRUE, &stop_flag, &start_time, progbar_val); /* Update the progress bar, but do it only N_PROGBAR_UPDATES times; when we update it, we have to run the GTK+ main loop to get it to repaint what's pending, and doing so may involve an "ioctl()" to see if there's any pending input from an X server, and doing that for every packet can be costly, especially on a big file. */ if (count >= progbar_nextstep) { /* let's not divide by zero. I should never be started * with count == 0, so let's assert that */ g_assert(cfile.count > 0); progbar_val = (gfloat) count / cfile.count; if (progbar != NULL) { g_snprintf(status_str, sizeof(status_str), "%4u of %u frames", count, cfile.count); update_progress_dlg(progbar, progbar_val, status_str); } progbar_nextstep += progbar_quantum; } if (stop_flag) { /* Well, the user decided to abort the statistics. computation process Just stop. */ break; } /* Skip frames that are hidden due to the display filter. XXX - should the progress bar count only packets that passed the display filter? If so, it should probably do so for other loops (see "file.c") that look only at those packets. */ if (frame->flags.passed_dfilter) { if (tot_packets == 0) { double cur_time = nstime_to_sec(&frame->abs_ts); ps->first_time = cur_time; ps->last_time = cur_time; } /* we don't care about colinfo */ if (!process_frame(frame, NULL, ps)) { /* * Give up, and set "stop_flag" so we * just abort rather than popping up * the statistics window. */ stop_flag = TRUE; break; } tot_packets++; tot_bytes += frame->pkt_len; } count++; } /* We're done calculating the statistics; destroy the progress bar if it was created. */ if (progbar != NULL) destroy_progress_dlg(progbar); if (stop_flag) { /* * We quit in the middle; throw away the statistics * and return NULL, so our caller doesn't pop up a * window with the incomplete statistics. */ ph_stats_free(ps); return NULL; } ps->tot_packets = tot_packets; ps->tot_bytes = tot_bytes; return ps; }
static void ga_log(const gchar *domain, GLogLevelFlags level, const gchar *msg, gpointer opaque) { GAState *s = opaque; GTimeVal time; const char *level_str = ga_log_level_str(level); if (!ga_logging_enabled(s)) { return; } level &= G_LOG_LEVEL_MASK; #ifndef _WIN32 if (domain && strcmp(domain, "syslog") == 0) { syslog(LOG_INFO, "%s: %s", level_str, msg); } else if (level & s->log_level) { #else if (level & s->log_level) { #endif g_get_current_time(&time); fprintf(s->log_file, "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg); fflush(s->log_file); } } void ga_set_response_delimited(GAState *s) { s->delimit_response = true; } #ifndef _WIN32 static bool ga_open_pidfile(const char *pidfile) { int pidfd; char pidstr[32]; pidfd = open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR); if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) { g_critical("Cannot lock pid file, %s", strerror(errno)); if (pidfd != -1) { close(pidfd); } return false; } if (ftruncate(pidfd, 0) || lseek(pidfd, 0, SEEK_SET)) { g_critical("Failed to truncate pid file"); goto fail; } sprintf(pidstr, "%d", getpid()); if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) { g_critical("Failed to write pid file"); goto fail; } return true; fail: unlink(pidfile); return false; }
/*! \brief create a new page object * \par Function Description * Creates a new page and add it to <B>toplevel</B>'s list of pages. * * It initializes the #PAGE structure and set its <B>page_filename</B> * to <B>filename</B>. <B>toplevel</B>'s current page is not changed by * this function. */ PAGE *s_page_new (TOPLEVEL *toplevel, const gchar *filename) { PAGE *page; /* Now create a blank page */ page = (PAGE*)g_new0 (PAGE, 1); page->pid = global_pid++; page->CHANGED = 0; /* big assumption here that page_filename isn't null */ if (g_path_is_absolute (filename)) { page->page_filename = g_strdup (filename); } else { gchar *pwd = g_get_current_dir (); page->page_filename = g_build_filename (pwd, filename, NULL); g_free (pwd); } g_assert (toplevel->init_bottom != 0); page->coord_aspectratio = ( ((float) toplevel->init_right) / ((float) toplevel->init_bottom)); page->up = -2; page->page_control = 0; /* Init tile array */ s_tile_init (toplevel, page); /* Init the object list */ page->_object_list = NULL; /* new selection mechanism */ page->selection_list = o_selection_new(); /* net/pin/bus stretch when doing moves */ page->stretch_list = NULL; page->place_list = NULL; /* init undo struct pointers */ s_undo_init(page); page->object_lastplace = NULL; set_window (toplevel, page, toplevel->init_left, toplevel->init_right, toplevel->init_top, toplevel->init_bottom); /* Backup variables */ g_get_current_time (&page->last_load_or_save_time); page->ops_since_last_backup = 0; page->saved_since_first_loaded = 0; page->do_autosave_backup = 0; page->load_newer_backup_func = load_newer_backup_func; /* now append page to page list of toplevel */ geda_list_add( toplevel->pages, page ); return page; }
static void * arv_gv_stream_thread (void *data) { ArvGvStreamThreadData *thread_data = data; ArvGvStreamFrameData *frame; ArvGvspPacket *packet; guint32 packet_id; guint32 frame_id; GTimeVal current_time; guint64 time_us; GPollFD poll_fd; size_t read_count; int timeout_ms; int n_events; int i; gboolean first_packet = TRUE; thread_data->frames = NULL; arv_debug_stream_thread ("[GvStream::stream_thread] Packet timeout = %g ms", thread_data->packet_timeout_us / 1000.0); arv_debug_stream_thread ("[GvStream::stream_thread] Frame retention = %g ms", thread_data->frame_retention_us / 1000.0); if (thread_data->callback != NULL) thread_data->callback (thread_data->user_data, ARV_STREAM_CALLBACK_TYPE_INIT, NULL); poll_fd.fd = g_socket_get_fd (thread_data->socket); poll_fd.events = G_IO_IN; poll_fd.revents = 0; packet = g_malloc0 (ARV_GV_STREAM_INCOMING_BUFFER_SIZE); do { if (thread_data->frames != NULL) timeout_ms = thread_data->packet_timeout_us / 1000; else timeout_ms = ARV_GV_STREAM_POLL_TIMEOUT_US / 1000; n_events = g_poll (&poll_fd, 1, timeout_ms); g_get_current_time (¤t_time); time_us = current_time.tv_sec * 1000000 + current_time.tv_usec; if (n_events > 0) { thread_data->n_received_packets++; read_count = g_socket_receive (thread_data->socket, (char *) packet, ARV_GV_STREAM_INCOMING_BUFFER_SIZE, NULL, NULL); frame_id = arv_gvsp_packet_get_frame_id (packet); packet_id = arv_gvsp_packet_get_packet_id (packet); if (first_packet) { thread_data->last_frame_id = frame_id - 1; first_packet = FALSE; } frame = _find_frame_data (thread_data, frame_id, packet, packet_id, read_count, time_us); if (frame != NULL) { ArvGvspPacketType packet_type = arv_gvsp_packet_get_packet_type (packet); if (packet_type != ARV_GVSP_PACKET_TYPE_OK && packet_type != ARV_GVSP_PACKET_TYPE_RESEND) { arv_debug_stream_thread ("[GvStream::stream_thread]" " Error packet at dt = %" G_GINT64_FORMAT ", packet id = %u" " frame id = %u", time_us - frame->first_packet_time_us, packet_id, frame->frame_id); arv_gvsp_packet_debug (packet, read_count, ARV_DEBUG_LEVEL_DEBUG); frame->error_packet_received = TRUE; thread_data->n_error_packets++; } else { /* Check for duplicated packets */ if (packet_id < frame->n_packets) { if (frame->packet_data[packet_id].received) thread_data->n_duplicated_packets++; else frame->packet_data[packet_id].received = TRUE; } /* Keep track of last packet of a continuous block starting from packet 0 */ for (i = frame->last_valid_packet + 1; i < frame->n_packets; i++) if (!frame->packet_data[i].received) break; frame->last_valid_packet = i - 1; switch (arv_gvsp_packet_get_content_type (packet)) { case ARV_GVSP_CONTENT_TYPE_DATA_LEADER: _process_data_leader (thread_data, frame, packet, packet_id); break; case ARV_GVSP_CONTENT_TYPE_DATA_BLOCK: _process_data_block (thread_data, frame, packet, packet_id, read_count); break; case ARV_GVSP_CONTENT_TYPE_DATA_TRAILER: _process_data_trailer (thread_data, frame, packet, packet_id); break; default: thread_data->n_ignored_packets++; break; } _missing_packet_check (thread_data, frame, packet_id, time_us); } } else thread_data->n_ignored_packets++; } else frame = NULL; _check_frame_completion (thread_data, time_us, frame); } while (!thread_data->cancel); _flush_frames (thread_data); if (thread_data->callback != NULL) thread_data->callback (thread_data->user_data, ARV_STREAM_CALLBACK_TYPE_EXIT, NULL); g_free (packet); return NULL; }
static void test_event (GstBin * pipeline, GstEventType type, GstPad * pad, gboolean expect_before_q, GstPad * fake_srcpad) { GstEvent *event; GstPad *peer; gint i; SignalData data; gulong id; got_event_before_q = got_event_after_q = NULL; gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PLAYING); gst_element_get_state (GST_ELEMENT (pipeline), NULL, NULL, GST_CLOCK_TIME_NONE); GST_DEBUG ("test event called"); event = gst_event_new_custom (type, gst_structure_new_empty ("application/x-custom")); g_get_current_time (&sent_event_time); got_event_time.tv_sec = 0; got_event_time.tv_usec = 0; signal_data_init (&data); /* We block the pad so the stream lock is released and we can send the event */ id = gst_pad_add_probe (fake_srcpad, GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM, signal_blocked, &data, NULL); fail_unless (id != 0); signal_data_wait (&data); /* We send on the peer pad, since the pad is blocked */ GST_DEBUG ("sending event %p", event); fail_unless ((peer = gst_pad_get_peer (pad)) != NULL); gst_pad_send_event (peer, event); gst_object_unref (peer); gst_pad_remove_probe (fake_srcpad, id); if (expect_before_q) { /* Wait up to 5 seconds for the event to appear */ for (i = 0; i < 500; i++) { g_usleep (G_USEC_PER_SEC / 100); if (got_event_before_q != NULL) break; } fail_if (got_event_before_q == NULL, "Expected event failed to appear upstream of the queue " "within 5 seconds"); fail_unless (GST_EVENT_TYPE (got_event_before_q) == type); } else { /* Wait up to 10 seconds for the event to appear */ for (i = 0; i < 1000; i++) { g_usleep (G_USEC_PER_SEC / 100); if (got_event_after_q != NULL) break; } fail_if (got_event_after_q == NULL, "Expected event failed to appear after the queue within 10 seconds"); fail_unless (GST_EVENT_TYPE (got_event_after_q) == type); } gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PAUSED); gst_element_get_state (GST_ELEMENT (pipeline), NULL, NULL, GST_CLOCK_TIME_NONE); if (got_event_before_q) gst_event_unref (got_event_before_q); if (got_event_after_q) gst_event_unref (got_event_after_q); got_event_before_q = got_event_after_q = NULL; signal_data_cleanup (&data); }
//client draw callback static gboolean drawCallback (void * gl_sink, GLuint texture, GLuint width, GLuint height, gpointer data) { static GLfloat xrot = 0; static GLfloat yrot = 0; static GLfloat zrot = 0; static GTimeVal current_time; static glong last_sec = current_time.tv_sec; static gint nbFrames = 0; g_get_current_time (¤t_time); nbFrames++ ; if ((current_time.tv_sec - last_sec) >= 1) { std::cout << "GRPHIC FPS = " << nbFrames << std::endl; nbFrames = 0; last_sec = current_time.tv_sec; } glEnable(GL_DEPTH_TEST); glEnable (GL_TEXTURE_2D); glBindTexture (GL_TEXTURE_2D, texture); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f,0.0f,-5.0f); glRotatef(xrot,1.0f,0.0f,0.0f); glRotatef(yrot,0.0f,1.0f,0.0f); glRotatef(zrot,0.0f,0.0f,1.0f); glBegin(GL_QUADS); // Front Face glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Back Face glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Top Face glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Bottom Face glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Right face glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Left Face glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glEnd(); xrot+=0.03f; yrot+=0.02f; zrot+=0.04f; //return TRUE causes a postRedisplay //so you have to return FALSE to synchronise to have a graphic FPS //equals to the input video frame rate //Usually, we will not always return TRUE (or FALSE) //For example, if you want a fixed graphic FPS equals to 60 //then you have to use the timeclock to return TRUE or FALSE //in order to increase or decrease the FPS in real time //to reach the 60. return TRUE; }
/*! \brief signal_read_rtvars_thread() is thread which fires off the read msg to get a new set of realtime variables. It does so by queing messages to a thread which handles I/O. This function will check the queue depth and if the queue is backed up it will skip sending a request for data, as that will only aggravate the queue roadblock. \param data is unused \returns 0 on signal to exit */ G_MODULE_EXPORT void * signal_read_rtvars_thread(gpointer data) { static void (*signal_read_rtvars)(void); static gboolean (*setup_rtv)(void); Serial_Params *serial_params; GMutex * mutex = g_mutex_new(); GTimeVal time; GAsyncQueue *io_data_queue = NULL; GAsyncQueue *pf_dispatch_queue = NULL; GCond *rtv_thread_cond = NULL; GMutex *rtv_thread_mutex = NULL; gint count = 0; gint io_queue_len = 0; gint pf_queue_len = 0; gint delay = 0; g_mutex_lock(mutex); serial_params = (Serial_Params *)DATA_GET(global_data,"serial_params"); io_data_queue = (GAsyncQueue *)DATA_GET(global_data,"io_data_queue"); pf_dispatch_queue = (GAsyncQueue *)DATA_GET(global_data,"pf_dispatch_queue"); rtv_thread_cond = (GCond *)DATA_GET(global_data,"rtv_thread_cond"); rtv_thread_mutex = (GMutex *)DATA_GET(global_data,"rtv_thread_mutex"); get_symbol("signal_read_rtvars",(void **)&signal_read_rtvars); get_symbol("setup_rtv",(void **)&setup_rtv); g_return_val_if_fail(serial_params,NULL); g_return_val_if_fail(signal_read_rtvars,NULL); g_return_val_if_fail(io_data_queue,NULL); g_return_val_if_fail(pf_dispatch_queue,NULL); g_return_val_if_fail(rtv_thread_cond,NULL); g_return_val_if_fail(rtv_thread_mutex,NULL); g_return_val_if_fail(setup_rtv,NULL); if (!setup_rtv()) { g_mutex_unlock(mutex); g_mutex_free(mutex); g_thread_exit(NULL); } g_async_queue_ref(io_data_queue); g_async_queue_ref(pf_dispatch_queue); g_mutex_lock(rtv_thread_mutex); while (TRUE) { MTXDBG(IO_MSG|THREADS,_("Sending message to thread to read RT vars\n")); signal_read_rtvars(); count = 0; /* Auto-throttling if gui gets sluggish */ while ((g_async_queue_length(io_data_queue) > 2) || (g_async_queue_length(pf_dispatch_queue) > 3)) { count++; pf_queue_len = g_async_queue_length(pf_dispatch_queue); io_queue_len = g_async_queue_length(io_data_queue); //printf("Auto-throttling, io queue length %i, pf queue length %i, loop iterations %i\n",io_queue_len,pf_queue_len,count); g_get_current_time(&time); delay = MAX(io_queue_len,pf_queue_len); g_time_val_add(&time,10000*(delay)); //printf("io_queue_len is %i pf queue length is %i, delay is %i\n",io_queue_len,pf_queue_len,delay ); if (g_cond_timed_wait(rtv_thread_cond,rtv_thread_mutex,&time)) goto breakout; } g_get_current_time(&time); //printf("serial_params->read_wait is %i\n",serial_params->read_wait); g_time_val_add(&time,serial_params->read_wait*1000); if (g_cond_timed_wait(rtv_thread_cond,rtv_thread_mutex,&time)) goto breakout; } breakout: g_async_queue_unref(io_data_queue); g_async_queue_unref(pf_dispatch_queue); g_mutex_unlock(mutex); g_mutex_free(mutex); g_mutex_unlock(rtv_thread_mutex); g_thread_exit(0); return NULL; }
/** * oh_dequeue_session_event * @sid: * @event: * * * * Returns: **/ SaErrorT oh_dequeue_session_event(SaHpiSessionIdT sid, SaHpiTimeoutT timeout, struct oh_event * event, SaHpiEvtQueueStatusT * eventq_status) { struct oh_session *session = NULL; struct oh_event *devent = NULL; GTimeVal gfinaltime; GAsyncQueue *eventq = NULL; SaHpiBoolT subscribed; SaErrorT invalid; if (sid < 1 || (event == NULL)) return SA_ERR_HPI_INVALID_PARAMS; wrap_g_static_rec_mutex_lock(&oh_sessions.lock); /* Locked session table */ session = g_hash_table_lookup(oh_sessions.table, &sid); if (!session) { wrap_g_static_rec_mutex_unlock(&oh_sessions.lock); return SA_ERR_HPI_INVALID_SESSION; } if (eventq_status) { *eventq_status = session->eventq_status; } session->eventq_status = 0; eventq = session->eventq; g_async_queue_ref(eventq); wrap_g_static_rec_mutex_unlock(&oh_sessions.lock); if (timeout == SAHPI_TIMEOUT_IMMEDIATE) { devent = g_async_queue_try_pop(eventq); } else if (timeout == SAHPI_TIMEOUT_BLOCK) { while (devent == NULL) { g_get_current_time(&gfinaltime); g_time_val_add(&gfinaltime, 5000000L); devent = wrap_g_async_queue_timed_pop(eventq, &gfinaltime); /* compliance with spec page 63 */ invalid = oh_get_session_subscription(sid, &subscribed); /* Is the session still open? or still subscribed? */ if (invalid || !subscribed) { g_async_queue_unref(eventq); oh_event_free(devent, FALSE); return invalid ? SA_ERR_HPI_INVALID_SESSION : SA_ERR_HPI_INVALID_REQUEST; } } } else { g_get_current_time(&gfinaltime); g_time_val_add(&gfinaltime, (glong) (timeout / 1000)); devent = wrap_g_async_queue_timed_pop(eventq, &gfinaltime); invalid = oh_get_session_subscription(sid, &subscribed); if (invalid || !subscribed) { g_async_queue_unref(eventq); oh_event_free(devent, FALSE); return invalid ? SA_ERR_HPI_INVALID_SESSION : SA_ERR_HPI_INVALID_REQUEST; } } g_async_queue_unref(eventq); if (devent) { int cc; cc = oh_detect_quit_event(devent); if (cc == 0) { // OpenHPI is about to quit oh_event_free(devent, FALSE); return SA_ERR_HPI_NO_RESPONSE; } memcpy(event, devent, sizeof(struct oh_event)); g_free(devent); return SA_OK; } else { memset(event, 0, sizeof(struct oh_event)); return SA_ERR_HPI_TIMEOUT; } }
static GRealThreadPool* g_thread_pool_wait_for_new_pool (void) { GRealThreadPool *pool; gint local_wakeup_thread_serial; guint local_max_unused_threads; gint local_max_idle_time; gint last_wakeup_thread_serial; gboolean have_relayed_thread_marker = FALSE; local_max_unused_threads = g_atomic_int_get (&max_unused_threads); local_max_idle_time = g_atomic_int_get (&max_idle_time); last_wakeup_thread_serial = g_atomic_int_get (&wakeup_thread_serial); g_atomic_int_inc (&unused_threads); do { if (g_atomic_int_get (&unused_threads) >= local_max_unused_threads) { /* If this is a superfluous thread, stop it. */ pool = NULL; } else if (local_max_idle_time > 0) { /* If a maximal idle time is given, wait for the given time. */ GTimeVal end_time; g_get_current_time (&end_time); g_time_val_add (&end_time, local_max_idle_time * 1000); DEBUG_MSG (("thread %p waiting in global pool for %f seconds.", g_thread_self (), local_max_idle_time / 1000.0)); pool = g_async_queue_timed_pop (unused_thread_queue, &end_time); } else { /* If no maximal idle time is given, wait indefinitely. */ DEBUG_MSG (("thread %p waiting in global pool.", g_thread_self ())); pool = g_async_queue_pop (unused_thread_queue); } if (pool == wakeup_thread_marker) { local_wakeup_thread_serial = g_atomic_int_get (&wakeup_thread_serial); if (last_wakeup_thread_serial == local_wakeup_thread_serial) { if (!have_relayed_thread_marker) { /* If this wakeup marker has been received for * the second time, relay it. */ DEBUG_MSG (("thread %p relaying wakeup message to " "waiting thread with lower serial.", g_thread_self ())); g_async_queue_push (unused_thread_queue, wakeup_thread_marker); have_relayed_thread_marker = TRUE; /* If a wakeup marker has been relayed, this thread * will get out of the way for 100 microseconds to * avoid receiving this marker again. */ g_usleep (100); } } else { if (g_atomic_int_add (&kill_unused_threads, -1) > 0) { pool = NULL; break; } DEBUG_MSG (("thread %p updating to new limits.", g_thread_self ())); local_max_unused_threads = g_atomic_int_get (&max_unused_threads); local_max_idle_time = g_atomic_int_get (&max_idle_time); last_wakeup_thread_serial = local_wakeup_thread_serial; have_relayed_thread_marker = FALSE; } } } while (pool == wakeup_thread_marker); g_atomic_int_add (&unused_threads, -1); return pool; }
/*! \brief signal_read_rtvars_thread() is thread which fires off the read msg to get a new set of realtiem variables. It does so by queing messages to a thread which handles I/O. This function will check the queue depth and if the queue is backed up it will skip sending a request for data, as that will only aggravate the queue roadblock. \returns 0 on signal to exit */ G_MODULE_EXPORT void * signal_read_rtvars_thread(gpointer data) { static void (*signal_read_rtvars)(void); static gboolean (*setup_rtv)(void); static gboolean (*teardown_rtv)(void); Serial_Params *serial_params; GMutex * mutex = g_mutex_new(); GTimeVal time; GAsyncQueue *io_data_queue = NULL; GAsyncQueue *pf_dispatch_queue = NULL; GCond *rtv_thread_cond = NULL; GMutex *rtv_thread_mutex = NULL; serial_params = DATA_GET(global_data,"serial_params"); io_data_queue = DATA_GET(global_data,"io_data_queue"); pf_dispatch_queue = DATA_GET(global_data,"pf_dispatch_queue"); rtv_thread_cond = DATA_GET(global_data,"rtv_thread_cond"); rtv_thread_mutex = DATA_GET(global_data,"rtv_thread_mutex"); get_symbol("signal_read_rtvars",(void *)&signal_read_rtvars); get_symbol("setup_rtv",(void *)&setup_rtv); get_symbol("teardown_rtv",(void *)&teardown_rtv); g_return_val_if_fail(serial_params,NULL); g_return_val_if_fail(signal_read_rtvars,NULL); g_return_val_if_fail(io_data_queue,NULL); g_return_val_if_fail(pf_dispatch_queue,NULL); g_return_val_if_fail(rtv_thread_cond,NULL); g_return_val_if_fail(rtv_thread_mutex,NULL); if (setup_rtv) if (!setup_rtv()) g_thread_exit(NULL); g_mutex_lock(mutex); g_async_queue_ref(io_data_queue); g_async_queue_ref(pf_dispatch_queue); g_mutex_lock(rtv_thread_mutex); while (TRUE) { dbg_func(IO_MSG|THREADS,g_strdup(__FILE__": signal_read_rtvars_thread()\n\tsending message to thread to read RT vars\n")); signal_read_rtvars(); /* Auto-throttling if gui gets sluggish */ while (( g_async_queue_length(io_data_queue) > 2) || (g_async_queue_length(pf_dispatch_queue) > 3)) { g_get_current_time(&time); g_time_val_add(&time,1000*g_async_queue_length(pf_dispatch_queue)); if (g_cond_timed_wait(rtv_thread_cond,rtv_thread_mutex,&time)) goto breakout; } g_get_current_time(&time); g_time_val_add(&time,serial_params->read_wait*1000); if (g_cond_timed_wait(rtv_thread_cond,rtv_thread_mutex,&time)) goto breakout; } breakout: g_mutex_unlock(rtv_thread_mutex); g_async_queue_unref(io_data_queue); g_async_queue_unref(pf_dispatch_queue); g_mutex_unlock(mutex); g_mutex_free(mutex); if (teardown_rtv) teardown_rtv(); g_thread_exit(0); return NULL; }
static void fetch_net_wm_check_window (GdkScreen *screen) { GdkX11Screen *x11_screen; GdkDisplay *display; Atom type; gint format; gulong n_items; gulong bytes_after; guchar *data; Window *xwindow; GTimeVal tv; gint error; x11_screen = GDK_X11_SCREEN (screen); display = x11_screen->display; g_return_if_fail (GDK_X11_DISPLAY (display)->trusted_client); g_get_current_time (&tv); if (ABS (tv.tv_sec - x11_screen->last_wmspec_check_time) < 15) return; /* we've checked recently */ x11_screen->last_wmspec_check_time = tv.tv_sec; data = NULL; XGetWindowProperty (x11_screen->xdisplay, x11_screen->xroot_window, gdk_x11_get_xatom_by_name_for_display (display, "_NET_SUPPORTING_WM_CHECK"), 0, G_MAXLONG, False, XA_WINDOW, &type, &format, &n_items, &bytes_after, &data); if (type != XA_WINDOW) { if (data) XFree (data); return; } xwindow = (Window *)data; if (x11_screen->wmspec_check_window == *xwindow) { XFree (xwindow); return; } gdk_x11_display_error_trap_push (display); /* Find out if this WM goes away, so we can reset everything. */ XSelectInput (x11_screen->xdisplay, *xwindow, StructureNotifyMask); error = gdk_x11_display_error_trap_pop (display); if (!error) { x11_screen->wmspec_check_window = *xwindow; x11_screen->need_refetch_net_supported = TRUE; x11_screen->need_refetch_wm_name = TRUE; /* Careful, reentrancy */ _gdk_x11_screen_window_manager_changed (GDK_SCREEN (x11_screen)); } else if (error == BadWindow) { /* Leftover property, try again immediately, new wm may be starting up */ x11_screen->last_wmspec_check_time = 0; } XFree (xwindow); }
static _ais_t *_getAIS (unsigned int mmsi) { // return this _ais_t *ais = NULL; // check that gps_done() haven't flush this if (NULL == _ais_list) { g_print("s52ais:_getAIS() no AIS list\n"); return NULL; } unsigned int i = 0; for (i=0; i<_ais_list->len; ++i) { ais = &g_array_index(_ais_list, _ais_t, i); if (mmsi == ais->mmsi) { return ais; } } { // NEW AIS (not found hence new) _ais_t newais; __builtin_bzero(&newais, sizeof(_ais_t)); newais.mmsi = mmsi; newais.status = -1; // 0 indicate that status form report is needed //newais.name[AIS_SHIPNAME_MAXLEN + 1] = '\0'; newais.name[0] = '\0'; g_get_current_time(&newais.lastUpdate); newais.course = -1.0; newais.speed = 0.0; // create an active symbol, put mmsi since status is not known yet g_sprintf(newais.name, "%i", mmsi); #ifdef S52_USE_SOCK // debug: make ferry acte as ownshp if (OWNSHIP == mmsi) { gchar *resp = _encodeNsend("S52_newOWNSHP", "\"%s\"", newais.name); if (NULL != resp) { sscanf(resp, "[ %lu", (long unsigned int *) &newais.vesselH); } g_print("s52ais:_getAIS(): new ownshpH:%lu\n", (long unsigned int) newais.vesselH); } else { gchar *resp = _encodeNsend("S52_newVESSEL", "%i,\"%s\"", 2, newais.name); if (NULL != resp) { sscanf(resp, "[ %lu", (long unsigned int *) &newais.vesselH); } g_print("s52ais:_getAIS(): new vesselH:%lu\n", (long unsigned int) newais.vesselH); } #else // S52_USE_SOCK // debug: make ferry acte as ownshp if (OWNSHIP == mmsi) { newais.vesselH = S52_newOWNSHP(newais.name); } else { //int vesrce = 1; // ARPA int vesrce = 2; // AIS //int vesrce = 3; // VTS newais.vesselH = S52_newVESSEL(vesrce, newais.name); } #endif // S52_USE_SOCK // new AIS failed if (NULL == newais.vesselH) { g_print("s52ais:_getAIS(): new vesselH fail\n"); return NULL; } #ifdef S52_USE_AFGLOW #ifdef S52_USE_SOCK // debug: make ferry acte as ownshp if (OWNSHIP == mmsi) { gchar *resp = _encodeNsend("S52_newMarObj", "\"%s\",%i,%i", "afgshp", S52_LINES, MAX_AFGLOW_PT); if (NULL != resp) { sscanf(resp, "[ %lu", (long unsigned int *) &newais.afglowH); } g_print("s52ais:_getAIS(): new afglowH:%lu\n", (long unsigned int) newais.afglowH); } else { gchar *resp = _encodeNsend("S52_newMarObj", "\"%s\",%i,%i", "afgves", S52_LINES, MAX_AFGLOW_PT); if (NULL != resp) { sscanf(resp, "[ %lu", (long unsigned int *) &newais.afglowH); } g_print("s52ais:_getAIS(): new afglowH:%lu\n", (long unsigned int) newais.afglowH); } #else // S52_USE_SOCK // debug: make ferry acte as ownshp if (OWNSHIP == mmsi) newais.afglowH = S52_newMarObj("afgshp", S52_LINES, MAX_AFGLOW_PT, NULL, NULL); else newais.afglowH = S52_newMarObj("afgves", S52_LINES, MAX_AFGLOW_PT, NULL, NULL); #endif // S52_USE_SOCK if (NULL == newais.afglowH) { g_print("s52ais:_getAIS(): new afglowH fail\n"); return NULL; } #endif // save S52obj handle after registered in libS52 g_array_append_val(_ais_list, newais); ais = &g_array_index(_ais_list, _ais_t, _ais_list->len - 1); #ifdef S52_USE_DBUS _signal_newVESSEL(_dbus, newais.vesselH, newais.name); #endif } return ais; }
static void server_api_status_callback (SoupServer * server, SoupMessage * msg, const char *path, GHashTable * query, SoupClientContext * client, gpointer user_data) { (void) server; (void) path; (void) query; (void) client; (void) user_data; char *response = NULL; GPtrArray *r_array = NULL; GPtrArray *unr_array = NULL; GPtrArray *connected_sensors = NULL; GHashTable *hash; GString *st_sensors = NULL; GString *st_unrsensors = NULL; GString *st_csensors = NULL; gchar *per_session_stats = NULL; gchar *engine_stats = NULL; gchar *server_stats = NULL; GTimeVal current_time; SoupSocket *sock = NULL; SoupAddress *sockaddr = NULL; SoupURI *uri = NULL; guint i; /* Only get methods and no params */ g_get_current_time (¤t_time); if (msg->method != SOUP_METHOD_GET || query != NULL) { soup_message_set_status (msg, SOUP_STATUS_NOT_IMPLEMENTED); return; } /* Verificación anti listos */ if ((sock = soup_client_context_get_socket (client)) == NULL) { soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR); return; } /* If host == 127.0.0.1 or host == localhost, verify that the localaddress == 127.0.0.1 */ if ((uri = soup_message_get_uri (msg)) == NULL) { soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR); return; } if (strcmp (uri->host,"127.0.0.1") == 0 || strcmp (uri->host,"localhost") == 0) { if ((sockaddr = soup_socket_get_local_address (sock)) == NULL) { soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR); return; } else { /* Aquí hay un listo */ if (strcmp ( soup_address_get_physical(sockaddr),"127.0.0.1") != 0) { soup_message_set_status (msg, SOUP_STATUS_UNAUTHORIZED); return; } } } if (server_api_get_info_sensors (&r_array, &unr_array, &hash) == FALSE) { soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR); return; } /* Load the info of connected sensors */ if (sim_server_get_sensor_uuids_unique (ossim.server, &connected_sensors) == FALSE) { soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR); return; } if ((st_sensors = g_string_new ("")) == NULL) { soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR); return; } if ((st_unrsensors = g_string_new ("")) == NULL) { soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR); return; } if ((st_csensors = g_string_new ("")) == NULL) { soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR); return; } /* For the register sensors */ if (r_array->len > 0) { for (i = 0; i < r_array->len; i++) { g_string_append_printf (st_sensors, "\"%s\"", (gchar *) g_ptr_array_index (r_array, i)); if ((i != (r_array->len - 1))) { g_string_append_c (st_sensors, ','); } } g_string_prepend_c (st_sensors, '['); g_string_append_c (st_sensors, ']'); } else { g_string_printf (st_sensors, "[null]"); } /* For the unregister sensors */ if (unr_array->len > 0) { for (i = 0; i < unr_array->len; i++) { g_string_append_printf (st_unrsensors, "\"%s\"", (gchar *) g_ptr_array_index (unr_array, i)); if ((i != (unr_array->len - 1))) { g_string_append_c (st_unrsensors, ','); } } g_string_prepend_c (st_unrsensors, '['); g_string_append_c (st_unrsensors, ']'); } else { g_string_printf (st_unrsensors, "[null]"); } /* The connected sensors */ if (connected_sensors->len > 0) { int count = 0; for (i = 0; i < connected_sensors->len; i++) { char *av_uuid; if ((av_uuid = g_hash_table_lookup (hash, (gchar *) g_ptr_array_index (connected_sensors, i))) != NULL) { g_string_append_printf (st_csensors, "\"%s\"", av_uuid); count++; if ((i != (connected_sensors->len - 1))) { g_string_append_c (st_csensors, ','); } } } if (count > 0) { g_string_prepend_c (st_csensors, '['); g_string_append_c (st_csensors, ']'); } else { g_string_printf (st_csensors, "[null]"); } } else { g_string_printf (st_csensors, "[null]"); } per_session_stats = sim_server_api_get_per_session_stats (); server_stats = server_api_get_server_stats (¤t_time); engine_stats = server_api_get_engine_stats (¤t_time); old_time.tv_sec = current_time.tv_sec; response = g_strdup_printf ("{\"result\":{\"request\":\"/server/status\",\n\"timestamp\":\"%lld\",\n\"rsensors\":%s,\n\"unrsensors\":%s,\n\"csensors\":%s,\n\"engine_stats\":[%s],\n\"server_stats\":%s,\n\"per_session_stats\":%s\n},\n\"status\":\"OK\"\n}", (long long) time (NULL), st_sensors->str, st_unrsensors->str, st_csensors->str, engine_stats, server_stats, per_session_stats ); soup_message_set_response (msg, "application/json", SOUP_MEMORY_TAKE, response, strlen (response)); soup_message_set_status (msg, SOUP_STATUS_OK); if (r_array != NULL) g_ptr_array_unref (r_array); if (unr_array != NULL) g_ptr_array_unref (unr_array); if (hash != NULL) g_hash_table_destroy (hash); if (st_sensors != NULL) { g_string_free (st_sensors, TRUE); } if (st_unrsensors != NULL) { g_string_free (st_unrsensors, TRUE); } if (st_csensors != NULL) { g_string_free (st_csensors, TRUE); } if (connected_sensors != NULL) g_ptr_array_unref (connected_sensors); g_free (per_session_stats); g_free (engine_stats); g_free (server_stats); }
guint32 get_time() { GTimeVal t; g_get_current_time(&t); return (t.tv_sec * 1000) + (t.tv_usec / 1000); }
network_socket *network_connection_pool_get_new(chassis *chas, network_backend_t *backend, proxy_rw type, network_connection_pool *pool, const GString *username, user_pool_config *user_pool_conf, connection_scaler_pool_statistics *pool_stats) { guint pool_conn_current_using_sum = 0; GQueue *conns = NULL; network_connection_pool_entry *entry = NULL; GTimeVal now_tv; guint removed = 0; network_socket *sock = NULL; g_assert(chas); g_assert(backend); g_assert(type == PROXY_TYPE_WRITE || type == PROXY_TYPE_READ); g_assert(pool); g_assert(username); g_assert(user_pool_conf); g_assert(pool_stats); g_assert(backend->pool[type] == pool); /** * 取用户连接池 */ g_mutex_lock(&(pool->connection_pool_mutex)); conns = network_connection_pool_get_conns(pool, username, NULL ); if (conns == NULL ) { pool_stats->conn_nopool++; goto NETWORK_CONNECTION_POOL_GET_NEW_EXIT; } pool_stats->conn_length = g_queue_get_length(conns); /** * 删除空的用户连接池 * 比如最小连接数等于零 */ if (pool_stats->conn_length == 0) { pool_stats->conn_zerosize++; g_hash_table_remove(pool->users, username); goto NETWORK_CONNECTION_POOL_GET_NEW_EXIT; } /** * 取用户连接池当前连接数,包括未决的和已用的,不包括空闲的(空闲数量应该约等于连接池长度) */ pool_conn_current_using_sum = get_conn_using_pending_count(pool, username->str); /** * 是否[连接池当前连接]大于[最大连接数] */ if (pool_conn_current_using_sum > user_pool_conf->max_connections) { pool_stats->conn_toomany++; goto NETWORK_CONNECTION_POOL_GET_NEW_EXIT; } g_get_current_time(&now_tv); /**取出一个连接*/ for (entry = g_queue_pop_head(conns); conns != NULL && entry != NULL ; entry = g_queue_pop_head(conns)) { pool_stats->conn_checked++; /**proxy_get_server_connection_list()这里idle--*/ //update_conn_pool_status_in_state(pool, username->str, POOL_STATUS_STATE_REMOVE_FROM_POOL); /** * 检查时间间隔未到,不需要检查,退出(此用户连接池)循环 */ if (check_pool_entry_connectivity_timeout(entry, &now_tv) == FALSE) { pool_stats->conn_again++; break; } /** * 是否断开 */ if (check_pool_entry_connectivity(entry) == FALSE) { update_conn_pool_status_in_state(pool, username->str, POOL_STATUS_STATE_REMOVE_FROM_POOL); garbage_connection_pool_add_entry(pool->garbage_connection_pool, entry); pool_stats->conn_disconnected++; entry = NULL; pool_conn_current_using_sum = get_conn_using_pending_count(pool, username->str); continue; } /** * 正常的连接 */ if (entry != NULL) { pool_stats->conn_good++; break; } } NETWORK_CONNECTION_POOL_GET_NEW_EXIT: g_mutex_unlock( &(pool->connection_pool_mutex)); removed += pool_stats->conn_disconnected; if (entry == NULL ) { #ifdef DEBUG_CONN_POOL g_debug("%s: (get) no entry for user '%s' -> %p", G_STRLOC, username ? username->str : "", conns); #endif return NULL ; } else { sock = entry->sock; network_connection_pool_entry_free(entry, FALSE); #ifdef DEBUG_CONN_POOL g_debug("%s: (get) got socket for user '%s' -> %p", G_STRLOC, username ? username->str : "", sock); #endif } return sock; }
void oauth_service_add_signature (OAuthService *self, const char *method, const char *url, GHashTable *parameters) { GTimeVal t; GString *param_string; GList *keys; GList *scan; GString *base_string; GString *signature_key; /* Add the OAuth specific parameters */ g_get_current_time (&t); g_free (self->priv->timestamp); self->priv->timestamp = oauth_create_timestamp (&t); g_hash_table_insert (parameters, "oauth_timestamp", self->priv->timestamp); g_free (self->priv->nonce); self->priv->nonce = oauth_create_nonce (&t); g_hash_table_insert (parameters, "oauth_nonce", self->priv->nonce); g_hash_table_insert (parameters, "oauth_version", OAUTH_VERSION); g_hash_table_insert (parameters, "oauth_signature_method", OAUTH_SIGNATURE_METHOD); g_hash_table_insert (parameters, "oauth_consumer_key", (gpointer) self->priv->consumer->consumer_key); if (self->priv->token != NULL) g_hash_table_insert (parameters, "oauth_token", self->priv->token); /* Create the parameter string */ param_string = g_string_new (""); keys = g_hash_table_get_keys (parameters); keys = g_list_sort (keys, (GCompareFunc) strcmp); for (scan = keys; scan; scan = scan->next) { char *key = scan->data; char *value = g_hash_table_lookup (parameters, key); g_string_append_uri_escaped (param_string, key, NULL, FALSE); g_string_append (param_string, "="); g_string_append_uri_escaped (param_string, value, NULL, FALSE); if (scan->next != NULL) g_string_append (param_string, "&"); } /* Create the Base String */ base_string = g_string_new (""); g_string_append_uri_escaped (base_string, method, NULL, FALSE); g_string_append (base_string, "&"); g_string_append_uri_escaped (base_string, url, NULL, FALSE); g_string_append (base_string, "&"); g_string_append_uri_escaped (base_string, param_string->str, NULL, FALSE); /* Calculate the signature value */ signature_key = g_string_new (""); g_string_append_uri_escaped (signature_key, self->priv->consumer->consumer_secret, NULL, FALSE); g_string_append (signature_key, "&"); if (self->priv->token_secret != NULL) g_string_append_uri_escaped (signature_key, self->priv->token_secret, NULL, FALSE); g_free (self->priv->signature); self->priv->signature = g_compute_signature_for_string (G_CHECKSUM_SHA1, G_SIGNATURE_ENC_BASE64, signature_key->str, signature_key->len, base_string->str, base_string->len); g_hash_table_insert (parameters, "oauth_signature", self->priv->signature); g_string_free (signature_key, TRUE); g_string_free (base_string, TRUE); g_list_free (keys); g_string_free (param_string, TRUE); }
static long calc_current_period(void) { GTimeVal tv; g_get_current_time(&tv); return tv.tv_sec*BIN_SEC_DIV + tv.tv_usec/BIN_USEC; }
/* Return the current time, in microseconds since the epoch. */ int64_t bluesky_get_current_time() { GTimeVal t; g_get_current_time(&t); return (int64_t)t.tv_sec * 1000000 + t.tv_usec; }
void draw_box_animation (MetaScreen *screen, MetaRectangle *initial_rect, MetaRectangle *destination_rect, double seconds_duration) { BoxAnimationContext *context; #ifdef HAVE_SHAPE XSetWindowAttributes attrs; #else XGCValues gc_values; #endif g_return_if_fail (seconds_duration > 0.0); if (g_getenv ("CONSORTIUM_DEBUG_EFFECTS")) seconds_duration *= 10; /* slow things down */ /* Create the animation context */ context = g_new0 (BoxAnimationContext, 1); context->screen = screen; context->millisecs_duration = seconds_duration * 1000.0; context->start_rect = *initial_rect; context->end_rect = *destination_rect; #ifdef HAVE_SHAPE attrs.override_redirect = True; attrs.background_pixel = BlackPixel (screen->display->xdisplay, screen->number); context->wireframe_xwindow = XCreateWindow (screen->display->xdisplay, screen->xroot, initial_rect->x, initial_rect->y, initial_rect->width, initial_rect->height, 0, CopyFromParent, CopyFromParent, (Visual *)CopyFromParent, CWOverrideRedirect | CWBackPixel, &attrs); update_wireframe_window (screen->display, context->wireframe_xwindow, initial_rect); XMapWindow (screen->display->xdisplay, context->wireframe_xwindow); #else /* !HAVE_SHAPE */ context->first_time = TRUE; gc_values.subwindow_mode = IncludeInferiors; gc_values.function = GXinvert; context->gc = XCreateGC (screen->display->xdisplay, screen->xroot, GCSubwindowMode | GCFunction, &gc_values); /* Grab the X server to avoid screen dirt */ meta_display_grab (context->screen->display); meta_ui_push_delay_exposes (context->screen->ui); #endif /* Do this only after we get the pixbuf from the server, * so that the animation doesn't get truncated. */ g_get_current_time (&context->start_time); /* Add the timeout - a short one, could even use an idle, * but this is maybe more CPU-friendly. */ g_timeout_add (15, (GSourceFunc)effects_draw_box_animation_timeout, context); /* kick changes onto the server */ XFlush (context->screen->display->xdisplay); }